text
stringlengths
8
267k
meta
dict
Q: How can I use XPATH to add data of subtree to main tree in Python/Django I'm using etree to parse an external xml file and trying to get the listing data from a tree from the below external xml file and add the subtree agancy data to it. I am able to pull the data for isting and agancy just fine seperately, but don't know how to merge them so that the listing gets the correct agency info. xml: <response> <listing> <bathrooms>2.1</bathrooms> <bedrooms>3</bedrooms> <agency> <name>Bob's Realty</name> <phone>555-693-4356</phone> </agency> </listing> <listing> <bathrooms>3.1</bathrooms> <bedrooms>5</bedrooms> <agency> <name>Larry's Homes</name> <phone>555-324-6532</phone> </agency> </listing> </response> python: tree = lxml.etree.parse("http://www.someurl.com?random=blahblahblah") listings = tree.xpath("/response/listing") agencies = tree.xpath("/response/listing/agency") listings_info = [] for listing in listings: this_value = { "bedrooms":listing.findtext("bedrooms"), "bathrooms":listing.findtext("bathrooms"), } for agency in agencies: this_value['agency']= agency.findtext("name") listings_info.append(this_value) I tried adding this at one point just above where the listing_info.append(this_value) occurs, however this is not correct and just appends the last agency value to every listing. I'm outputting the data into json and here's what it looks like (You can see how one agency's info is being put into both results: {"listings":[{"agency": "Bob's Realty", "phone":"555-693-4356" "bathrooms": "2.1", "bedrooms": "3"},{"agency": "Bob's Realty", "phone":"555-693-4356" "bathrooms": "3.1", "bedrooms": "5"} ]} How can I merge the data from response/listing/agency with response/listing in my original for statement? A: You can use listing.xpath('agency/name/text()')[0] as you iterate through your list to get the agency's name for just that listing. for listing in listings: this_value = { 'bedrooms': listing.findtext('bedrooms'), 'bathrooms': listing.findtext('bathrooms'), 'agency': listing.xpath('agency/name/text()')[0] } listings_info.append(this_value)
{ "language": "en", "url": "https://stackoverflow.com/questions/7532200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regular expression for remove html links Possible Duplicate: Regular expression for parsing links from a webpage? RegEx match open tags except XHTML self-contained tags i need a regular expression to strip html <a> tags , here is sample: <a href="xxxx" class="yyy" title="zzz" ...> link </a> should be converted to link A: Answers given above would match valid html tags such as <abbr> or <address> or <applet> and strip them out erroneously. A better regex to match only anchor tags would be </?a(?:(?= )[^>]*)?> A: You're going to have to use this hackish solution iteratively, and it won't probably even work perfectly for complicated HTML: <a(\s[^>]*)?>.*?(</a>)? Alternatively, you can try one of the existing HTML sanitizers/parsers out there. HTML is not a regular language; any regex we give you will not be 'correct'. It's impossible. Even Jon Skeet and Chuck Norris can't do it. Before I lapse into a fit of rage, like @bobince [in]famously once did, I'll just say this: Use a HTML Parser. (Whatever they're called.) EDIT: If you want to 'incorrectly' strip out </a>s that don't have any <a>s as well, do this: </?[a\s]*[^>]*> A: Here's what I would use: </?a\b[^>]*> A: I think you're looking for: </?a(|\s+[^>]+)> A: </?a.*?> would work. Replace it with ''
{ "language": "en", "url": "https://stackoverflow.com/questions/7532202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery UI autocomplete on select input box I have JSON data feeding id, label and value as keys for values. When I select data I select the label/value values onto the textbox #id_emp_name. I want to be able to insert the id of the label/value that was selected into the hidden textbox #id_emp_id. My current javascript code: $('#id_emp_name').autocomplete({ source: '/best_choose/employees.json', minLength: 1, dataType: 'json', max: 12 }); A: Use the "select" option of autocomplete to define a function to handle selections: $('#id_emp_name').autocomplete({ source: '/best_choose/employees.json', minLength: 1, dataType: 'json', max: 12, select: function(event, ui) { $('#id_emp_id').val(ui.item.id); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7532203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a function to print string as is in escaped mode? That is, prt("a \t\n") should print "a \t\n" literally, is there any available function that does this? A: I am assuming you want to escape special characters; that is, you want to print \n instead of a newline character. Not in the standard library, as far as I know. You can easily write it yourself; the core of the function is something like this: static char *escape_char(char *buf, const char *s) { switch (*s) { case '\n': return "\\n"; case '\t': return "\\t"; case '\'': return "\\\'"; case '\"': return "\\\""; case '\\': return "\\\\"; /* ... some more ... */ default: buf[0] = *s; buf[1] = '\0'; return buf; } } /* Warning: no safety checks -- buf MUST be long enough */ char *escape_string(char *buf, const char *s) { char buf2[2]; buf[0] = '\0'; for (; *s != '\0'; s++) { strcat(buf, escape_char(buf2, s)); } return buf; } Generating the function body is also an option, as it can get quite tedious and repetitive. This is how you can test it: int main() { const char *orig = "Hello,\t\"baby\"\nIt\'s me."; char escaped[100]; puts(orig); puts(escape_string(escaped, orig)); return 0; } A: Glib has a function g_strescape() which does this. If the added dependency to glib is not a problem for you, at least. A: No, because string literals are already "unescaped" during the parsing of the source code, so the compiler never sees the literal backslashes or quotation marks. You'll just have to escape the backslashes yourself: "\"a \\t\\n\"". Alternatively you could take a given string and search and replace all occurrences of control characters by their escape sequence. A: You have to escape the backslashes and the quotes with backslashes: printf( "\"a \\t\\n\"" ); A: There is not a function as such but you can always printf("a \\t\\n");
{ "language": "en", "url": "https://stackoverflow.com/questions/7532211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Tomcat 7, can I use regular expressions in ? Does Tomcat 7 have such a facility? Although I could write a filter to parse regular expression in url, it would make another project. I think such a facility should be provided in mainstream servlet containers. A: The Servlet API specification does not specify that. So no one container supports it. Best what you can get is using Tuckey's URLRewriteFilter. It's much similar to HTTPD's mod_rewrite.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: add alt attribute to href depending on the class the default state is: <a href="./" class="dynamic dynamic-children menu-item"><span class="additional-background"><span class="menu-item-text">Présentation</span></span></a> so if class = rfr-opened add alt="open" <a alt="open" href="./" class="dynamic dynamic-children menu-item rfr-opened"><span class="additional-background"><span class="menu-item-text">Présentation</span></span></a> so if class doesn't have rfr-opened add alt="close" <a alt="closed" href="./" class="dynamic dynamic-children menu-item"><span class="additional-background"><span class="menu-item-text">Présentation</span></span></a> A: Something like this? $('a').attr('alt', 'closed'); $('a.rfr-opened').attr('alt', 'open'); Demonstration: http://jsfiddle.net/9xLYV/ A: Tried and tested: http://jsfiddle.net/eMagu/ (I used inspector to check the alt value) jQuery one liner... // set all menu items to closed, then filter just the open class and set to open $('.menu-item').attr('alt','closed').filter('.rfr-opened').attr('alt','open') A: This should help: $('.menu-item').each(function () { if ($(this).hasClass('rtf-opened')) $(this).attr('alt', 'open'); else $(this).attr('alt', 'closed'); }); A: I think something along the lines of . . . $('a.menu-item')each(function() { if($(this).hasClass('rfr-opened')) { $(this).attr('alt', 'open'); } else { $(this).attr('alt', 'closed'); } }); A: this works for me jQuery("#rfr-topnav a").click(function () { $('#rfr-topnav a').attr('title', 'closed'); $('#rfr-topnav a.rfr-opened').attr('title', 'open'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7532219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: rubymine only able to run model tests one by one I am able to right-click on any of my 3 spec/models but when I right click the spec/models folder and select 'run all tests in models' I get 'Unable to attach test reporter to test framework'. The first line of my model tests is: require 'spec_helper.rb' A: I posted this answer for another question. It may help with this one as well: On my system, the problem was the "redgreen" gem. It automatically colors the progress marks (dots) and the Test::Unit summary messages based on success or failure. There must be something in RubyMine that's trying to parse the Test::Unit results (the output of "rake test", I imagine), and it's choking on the ANSI sequences. I commented out "require 'redgreen'" in my test/test_helper.rb, and the problem went away. I really like redgreen for executing "rake test" from the shell, though, so I put this in test_helper to make it work for both "rake test" and within RubyMine: require 'redgreen' if $stdin.tty? It may not be redgreen that's causing your problem, but be suspicious of anything which might create unconventional Test::Unit output. Good luck! A: I had the same issue and had to add the following to /etc/launcd.conf (I had to create this file as well): setenv DYLD_LIBRARY_PATH /usr/local/mysql/lib/ and reboot. There are other ways to do it as well (a plist file, adding this environmental variable to RubyMine, etc… but this was most reliable. Of course, this assumes that you use MySQL. A: The answer in the end for my setup was to fiddle around with the IDE settings including the ruby version, making sure it was 1.9.2 and the directories referenced in the config. screens were correct. This plus some restarts resolved the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding global maximum in matlab Can any body know how to find the global maximum of a signal in matlab. Any help will be highly appreciated. Thanks A: assuming your signal is a vector x, just do [max_value, index_number] = max(x) max_value will be the biggest value and index_number will be the index number of your original vector x. A: the biggest peak is not always the maximum it can always be the first or last element in the vector (if of curse you really mean the biggest peak and not maximum of function ) [~,indexes]=findpeaks(x,'SORTSTR','descend'); i=indexes(1); A: This is a very bad question as not enough information has been provided by the OP. but fminbnd() might be a good option to look into: clear; close all; clc; myFun = @(x) -min(sin(x), x^2); [x1, y1] = fminbnd(myFun, -1, 2); A: You can use isoutlier function like this example A = [57 59 60 100 59 58 57 58 300 61 62 60 62 58 57]; TF = isoutlier(A) If you want only specific parts, you can divide your vector as isoutlier(A(5:25)) or similar
{ "language": "en", "url": "https://stackoverflow.com/questions/7532223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Sending binary data to a servlet I am trying send a file to a servlet. function sendToServlet(){ var file = Components.classes["@mozilla.org/file/local;1"]. createInstance(Components.interfaces.nsILocalFile); file.initWithPath("C:\\Documents and Settings\\me\\Meus documentos\\Downloads\\music.mp3"); var boundary = "--------------" + (new Date).getTime(); var stream = Components.classes["@mozilla.org/network/file-input-stream;1"] .createInstance(Components.interfaces.nsIFileInputStream); stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsIFile instance // Send var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createInstance(Components.interfaces.nsIXMLHttpRequest); req.open('POST', 'http://localhost:8080/app/server' , false); var contentType = "multipart/form-data; boundary=" + boundary; req.setRequestHeader("Content-Type", contentType); req.send(stream); } The source of javascript: https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Sending_binary_data But does not work. Hi, this the serlevt code used: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub int size = 1024*20000; long sizeFile = 0; File savedFile = null; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(new Long("-1")); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); try { if (item.isFormField()) { ; }else{ String itemName = item.getName(); int sizeName = itemName.length(); int end = itemName.indexOf('\n'); int start = itemName.lastIndexOf('\\'); itemName = itemName.substring(start + 1, sizeName-end-1); savedFile = new File("C:\\Documents and Settings\\eric.silva\\Meus documentos\\"+itemName); item.write(savedFile); } } catch (Exception e) { e.printStackTrace(); } } } }//metodo But when i try to send a file the servlet dont create the file sent. Quando eu tento enviar via javascript a requisição é enviada. Mas o arquivo não é criado no lado do servidor. Acredito que o código apresentado no site da MDN esteja incompleto. When I try to send via javascript the request is sent. But the file is not created on the server side. I believe the code shown on the site of the MDN is incomplete. A: Note how the example code you are using is sending data with method PUT - valid multipart-formdata request needs to have some additional headers, not only the file itself. For example, the file you are sending should have a name (normally the name of the form field). You should use a FormData object instead, it will generate a valid request automatically. You should be able to create a File object directly. Something along these lines: var file = File("C:\\Documents and Settings\\me\\Meus documentos\\Downloads\\music.mp3"); var data = new FormData(); data.append("file", file); var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createInstance(Components.interfaces.nsIXMLHttpRequest); req.open('POST', 'http://localhost:8080/app/server', false); request.send(data); Note that creating File objects like this is only supported starting with Firefox 6. A: The problem lies more likely in how you're trying to obtain the uploaded file with the servlet. Being a low level impelementation, the servlet doesn't have much of an abstraction for handling uploaded files (multi part requests). Luckily there are libraries who take care of that for you like commons.FileUpload: http://commons.apache.org/fileupload/using.html Just set up a servlet with fileUpload like it sais in the doc, then make a simple html page with a form that has a file upload input, and use that as a basic functional test to see that it works, then return to making your own client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I apply XACML rules to every child URI? I'm working with XACML policies and I have a rule that includes a resource target similar to the following: <Resources> <Resource> <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">/MyDirectory</AttributeValue> <ResourceAttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" DataType="http://www.w3.org/2001/XMLSchema#anyURI"/> </ResourceMatch> </Resource> </Resources> I want this rule to apply to all subdirectories of /Mydirectory. However, if I were to evaluate a request with the resource /MyDirectory/MySubdirectory, I would get a DECISION_NOT_APPLICABLE (3) response. Is there an XQuery function that would allow me to apply a rule to all subdirectories of a single directory? A: You may use urn:oasis:names:tc:xacml:2.0:function:anyURI-regexp-match and define the AttributeValue as a regular expression.. <Resources> <Resource> <ResourceMatch MatchId="urn:oasis:names:tc:xacml:2.0:function:anyURI-regexp-match"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">^/MyDirectory/</AttributeValue> <ResourceAttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" DataType="http://www.w3.org/2001/XMLSchema#anyURI"/> </ResourceMatch> </Resource> </Resources>
{ "language": "en", "url": "https://stackoverflow.com/questions/7532237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ext JS - A start Folks, I am starting off to learn ExtJS. I had a look through Sencha's website. I went through some of the questions also already asked here. But had some doubts, * *What is the difference between ExtJS designer and Aptana ? Do we require both ? *How to start building your own 1st application in ExtJS ? Any tutorials for the total beginners. *Will I need to write JavaScript code manually or use a ExtJS designer to do that for me ? Thanks. A: I'll disagree a bit with the already-accepted answer. * *They are both optional. I use neither. OK, not too helpful. Aptana is a general-purpose IDE. It is based on Eclipse, but unlike vanilla Eclipse (which is Java-oriented) Aptana has lots of additions and plugins for doing JavaScript, PHP and other "web-centric" development. I actually use Aptana myself, even for Ext development, because it works for me. IDE discussions tend to get religious -- everyone has their own requirements and peeves, YMMV. Aptana does actually support framework-specific autocomplete, including for Ext JS (though I think they are still on an older version). Note that you can accomplish the same things as Aptana (generally-spekaing) using WebStorm, Komodo, NetBeans, TextMate or any old text editor -- just depends on what IDE-specific features you find helpful or not. Ext Designer (now Sencha Architect) on the other hand is NOT a general-purpose IDE -- it is strictly intended as an Ext UI design tool. However, it does go beyond simply "placing widgets" on the page. You can easily drag-drop things into place and also preview how they will render, hook up data stores to databound widgets (again via simple drag/drop interactions), it includes context-specific config and property setting (which makes it much easier to know what options are available without having to refer to the API docs constantly), etc. Architect then generates classes, in best-practice code format, that you can drop into your app and then extend as needed with your own business logic. The output of Architect could basically become the input project for Aptana (or whatever) where you would build your application code (although many people stick exclusively to Architect). Regarding tutorials, the docs site of Sencha.com was revamped recently and includes many tutorials updated for the most current versions of Ext. Of course the official examples are also a good place to start. The best book on Ext development is probably Jay Garcia's Ext JS in Action, though unfortunately it has not yet been updated for Ext 4 (he's currently working on that). It's a great overview of the concepts and best practices for Ext in general though, and a lot of what's in that book will still apply today. Finally, while Architect will definitely get you started with good UI code, it will not wire your app together or write any business logic for you. For that, you'll have to use the existing tutorials and examples to help guide you to write your own code. A: * *They are both optional. I use neither. *Depends on how “total” a beginner you are. Judging from your questions, I guess you aren’t familiar with JavaScript and web development in general. If that is the case, start by reading some tutorials on JavaScript and AJAX—you’ll need a solid grounding in those to make good use of Ext JS. I am yet to see a good tutorial for Ext JS (version 4) itself, and you’ll probably end up gathering pieces from the official docs, the Sencha blog, and the examples that ship with Ext JS. *You will have to write JavaScript (and maybe also HTML and CSS, depending on your scenario). The designer can only help you with placing widgets (like buttons or text boxes) on the page. In my experience so far, this has been the easy part, so unless you’re doing a complex user interface, you probably don’t need the designer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java DNS suffix When I do ipconfig /all I see DNS Suffix Search List. I need to retrieve that value from java. Does anyone knows how to get it or where does it come from? A: The DNS suffix list is read from HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\SearchList A: You could use the Runtime class to execute Windows commands (e.g. ipconfig /all) and parse the standard input.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Validation Layer in a PHP Class I need help understanding the logic to deal with validating user inputs. my current state of validating user data is at worst, i feel pretty awkward using these messy lines of codes, have a look at my typical function which i uses it to get input from the user and process it to database. public function saveUser($arguments = array()) { //Check if $arguments have all the required values if($this->isRequired(array('name','email','password','pPhone','gender','roleId'))) { //$name should could minimum of 5 and maximum of 25 chars, and is a strict character. $name = $this->isString(5, 25, $this->data['name'], 'STRICT_CHAR'); $email = $this->isEmail($this->data['email']); $pPhone = $this->isString(5, 12, $this->data['pPhone'], 'STRICT_NUMBER'); $sPhone = (!empty($this->data['sPhone'])) ? $this->isString(5, 12, $this->data['sPhone'], 'STRICT_NUMBER') : 0; //Check For Duplicate Email Value $this->duplicate('user_details','email',$email); //If Static Variable $error is not empty return false if(!empty(Validation::$error)) { return false; } //After Validation Insert the value into the database. $sth = $this->dbh->prepare('INSERT QUERY'); $sth->execute(); } } Now is the time i focus on improving my validation code. i would like all my class methods to validate the user inputs before inserting into the database. basically a class methods which takes user input should be able to perform the following. * *If class method accepts user input as an array then check for all required inputs from within the array. *Check the Minimum and Maximum Length of the input. *Check for any illegal character. etc. I would like to know how to deal with this, and also if there is any PHP Independent Validation Component which can come to my rescue. it would be of great help. if i am doing it wrong please suggest me on improving my code, i won't mind going to any extent as long as it guarantees that my code follows the coding standard. I will also appreciate if someone could explain me on dealing with validation logic for validating user input for a class method of an object. Thank you.. A: PHP 5.2 has a new core extension called "filter functions". You can use this extension to sanitize and validate user data. For example, to validate an email address: if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "This (email) email address is considered valid."; } As for dealing with validation in general, you want to decouple the validation process from the incoming data and the objects themselves. I use the Lithium PHP framework, and their data validation class is implemented as a nearly independant utility class. Check it out for ideas on how to roll your own: http://li3.me/docs/lithium/util/Validator Using their class, you get something like this: // Input data. This can be an $object->data() or $_POST or whatever $data = array( 'email' => 'someinvalidemailaddress'; ); // Validation rules $rules = array( 'email' => array( array('notEmpty', 'message' => 'email is empty'), array('email', 'message' => 'email is not valid') ) ); // Perform validation Validator::check($data, $rules); // If this were in your object public validate($data = array(), $rules = array()) { $data = !empty($data) ? $data : $this->data; // Use whatever data is available $rules = $this->rules + $rules; // Merge $this's own rules with any passed rules return Validator::check($data, $rules)); } // You can have a save method like public save() { if ($this->validates()) { // insert or update } } // And your object would $user = new User(); $user->data = array('email' => 'whatever'); $user->save(); And there's always Zend Validate. You can look it up at http://framework.zend.com/manual/en/zend.validate.set.html A: Create your validation class first...Then when they submit the code. Just include the class on where every you have action set to on the form. You can create a loop to pass the POST or GET data though the instance which validates the input. Then if the input is good, return it(maybe as an array, that's what I do) and pass it to your database. Example: $validate = new validation_Class; //new instance of the validation class $output = foreach($_POST as $input) // loop each input data into the class { $validate->$input; } Now if your validation class is setup right, you can have all the clean data stored in $output
{ "language": "en", "url": "https://stackoverflow.com/questions/7532247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add an Image pre-loader into a JS function I have this JS function, which will call the next image: function showNextManifest() { var currentManifest = jQuery('#selectedManifestId').val(); jQuery.ajax({ url: "${createLink(action:'nextManifest')}?currentManifestId=" + currentManifest, dataType: "json", success: function(e) { if (e.success) { jQuery('#gotoPageNumber').val(e.pageNumber); jQuery('#selectedManifestId').val(e.id); jQuery('#popupManifestCustomItemId').val(e.id); showLargeManifestViewer(e.url); } else { alert('No more additional frames for this roll.'); } } }); } I would like to drop in a gif preloading until the image gets displayed. Does this go before the if (e.success) ? A: Just add the loader gif to your container before ajaxing; I can see your function replace the url. function showNextManifest() { showLargeManifestViewer('/loading.gif'); //now it shows loader gif until ajax completed var currentManifest = jQuery('#selectedManifestId').val(); jQuery.ajax({ url: "${createLink(action:'nextManifest')}?currentManifestId=" + currentManifest, dataType: "json", success: function(e) { if (e.success) { jQuery('#gotoPageNumber').val(e.pageNumber); jQuery('#selectedManifestId').val(e.id); jQuery('#popupManifestCustomItemId').val(e.id); showLargeManifestViewer(e.url); } else { alert('No more additional frames for this roll.'); } } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7532251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Must NSManagedObject subclasses by passed to the controller or should these objects remain only in the model The reason I ask is because I have separate domain objects which I map from the NSManagedObject subclasses so as to keep my data access logic separate. But I think its going to be a problem for updating. A: I wouldn't say that NSManagedObject subclasses must be passed to a controller object: In theory you could do what you're describing, and build a "front end" layer that sits between your Core Data model and your controllers – you're creating a lot more work, of course, and it might be just as easy to throw out your old model and start over, if and when you ever do decide to stop using Core Data. You may also have to put more effort into keeping your model objects separate from your controller objects, what with a middle layer that could easily become a hodgepodge of both. It sounds like you've already gone down this road, though, so the question is probably more about the best use of your time and resources, and whether it's more cost-effective to phase out the middle layer or maintain it. A: If you mean should you pass MySubclass vs NSManagedObject; it does not matter. The instance is what it is, your subclass. You can call it anything in between id and MySubclass. So you can set up your controller to accept just an id or NSManagedObject you can pass it your subclass without an issue. If you want more exposed control to the subclass then you can pass around the subclass. If that does not answer your question then I suggest you expound upon your question with an example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running compiled python (py2app) as administrator in Mac After looking at Running compiled python (py2exe) as administrator in Vista I was wondering if there's an easy way to get the Mac Authentication dialog in Python (specifically py2app) I know mac has the built in Authentication services too http://developer.apple.com/library/mac/#documentation/Security/Reference/authorization_ref/Reference/reference.html Also, I know I could do something like this: os.system("""osascript -e 'do shell script "<commands here>" with administrator privileges'""") but was wondering if there was a built in way to do this A: From what I can tell there was a Python Egg for doing this, but it's been unsupported by the author for several years now
{ "language": "en", "url": "https://stackoverflow.com/questions/7532256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why does key equivalent work with escape but not with return? I have a button on my window that is set in interface builder to have the key equivalent of enter, but after switching a content view from using IKImageBrowserView to NSCollectionView, the keyEquivalent is being ignored. From what it says in the docs: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW10 The keyEquivalent events are handled "special" and should be pretty straight forward. I am subclassing the NSCollectionViewItem and the view of the item but neither of these subclasses are getting the performKeyEquivalent:theEvent when I override that method. There is a cancel button right next to the default button and is mapped to the esacpe key. Cancel continues to work, but the default button does not. How can I tell where the enter key event is getting handled? Edit: I actually found the same issue in the sample app that I used to learn about NSCollectionView. I added a default button to the bottom of the window and found that return did not trigger the button but enter (fn + return) did trigger the button. IconCollection sample app from Apple Any ideas on what is stealing the return key event in this example? Edit: I posted a sample project here: https://github.com/watkyn/NSCollectionViewIssue. Why doesn't the default button work? A: Return and Enter are two different keys. Return (on a US keyboard) is to the right of the apostrophe key. Enter is the lower-right key on the keypad. If you are using a laptop without a numeric keypad, you get Enter by pressing fn+Return. Edit after sample code was posted MyCollectionView is absorbing the return/enter keystroke and not passing it up the responder chain. Add this to the implementation of MyCollectionView and return and enter will press the button: - (void)keyDown:(NSEvent *)theEvent { // NSLog(@"event: %@", theEvent); if (36 == theEvent.keyCode || 76 == theEvent.keyCode) { //pass return and enter up the responder chain [[self window] keyDown:theEvent]; } else { //process all other keys in the default manner [super keyDown:theEvent]; } } This may cause problems if you need MyControllerView to actually do something itself with return/enter. In that case, you can add [super keyDown:theEvent] before [[self window] keyDown:theEvent].
{ "language": "en", "url": "https://stackoverflow.com/questions/7532260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AJAX and FormsAuthentication, how prevent FormsAuthentication overrides HTTP 401? In one application configured with FormsAuthentication, when a user access without the auth cookie or with an outdated one to a protected page, ASP.NET issue a HTTP 401 Unauthorized, then the FormsAuthentication module intercepts this response before the request end, and change it for a HTTP 302 Found, setting a HTTP header "Location: /path/loginurl" in order to redirect the user agent to the login page, then the browser goes to that page and retrieves the login page, that is not protected, getting an HTTP 200 OK. That was a very good idea indeed, when AJAX was not being considered. Now I have a url in my application that returns JSON data and it needs the user to be authenticated. Everything works well, the problems is that if the auth cookie expires, when my client side code call the server it will get a HTTP 200 OK with the html of the login page, instead a HTTP 401 Unauthorized (because the explained previously). Then my client side is trying to parse the login page html as json, and failing. The question then is : How to cope with an expired authentication from client side? What is the most elegant solution to cope with this situation? I need to know when the call has been successful or not, and I would like to do it using the HTTP semantic. Is it possible to read custom HTTP Headers from client side in a safe cross browser way? Is there a way to tell the FormsAuthenticationModule to not perform redirections if the request is an AJAX request? Is there a way to override the HTTP status using a HTTP header in the same way you can override the HTTP request method? I need the Forms authentication, and I would like to avoid rewrite that module or write my own form authentication module. Regards. A: I'm stealing this answer heavily from other posts, but an idea might be to implement an HttpModule to intercept the redirect to the login page (instructions at that link). You could also modify that example HttpModule to only intercept the redirect if the request was made via AJAX if the default behavior is correct when the request is not made via AJAX: Detect ajax call, ASP.net So something along the lines of: class AuthRedirectHandler : IHttpModule { #region IHttpModule Members public void Dispose() { } public void Init(HttpApplication context) { context.EndRequest+= new EventHandler(context_EndRequest); } void context_EndRequest(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; if (app.Response.StatusCode == 302 && app.Request.Headers["X-Requested-With"] == "XMLHttpRequest" && context.Response.RedirectLocation.ToUpper().Contains("LOGIN.ASPX")) { app.Response.ClearHeaders(); app.Response.ClearContent(); app.Response.StatusCode = 401; } } #endregion } You could also ensure the redirect is to your actual login page if there are other legit 302 redirects in your app. Then you would just add to your web.config: <httpModules> <add name="AuthRedirectHandler" type="SomeNameSpace.AuthRedirectHandler, SomeNameSpace" /> </httpModules> Anyhow. Again, actual original thought went into this answer, I'm just pulling various bits together from SO and other parts of the web. A: I was having issues implementing the accepted answer. Chiefly, my error logs were getting filled with Server cannot set status after HTTP headers have been sent errors. I tried implementing the accepted answer to question Server cannot set status after HTTP headers have been sent IIS7.5, again no success. Googling a bit I stumbled upon the SuppressFormsAuthenticationRedirect property If your .Net version is >= 4.5, then you can add the following code to the HandleUnauthorizedRequest method of your custom AuthorizeAttribute class. public sealed class CustomAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; base.HandleUnauthorizedRequest(filterContext); return; } base.HandleUnauthorizedRequest(filterContext); return; } } The important part is the if block. This is the simplest thing to do if you are on .Net 4.5 & already have custom authorization in place. A: I had the same problem, and had to use custom attribute in MVC. You can easy adapt this to work in web forms, you could override authorization of your pages in base page if all your pages inherit from some base page (global attribute in MVC allows the same thing - to override OnAuthorization method for all controllers/actions in application) This is how attribute looks like: public class AjaxAuthorizationAttribute : FilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest() && !filterContext.HttpContext.User.Identity.IsAuthenticated && (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).Count() > 0 || filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).Count() > 0)) { filterContext.HttpContext.SkipAuthorization = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized; filterContext.Result = new HttpUnauthorizedResult("Unauthorized"); filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext); filterContext.HttpContext.Response.End(); } } } Note that you need to call HttpContext.Response.End(); or your request will be redirected to login (I lost some of my hair because of this). On client side, I used jQuery ajaxError method: var lastAjaxCall = { settings: null, jqXHR: null }; var loginUrl = "yourloginurl"; //... //... $(document).ready(function(){ $(document).ajaxError(function (event, jqxhr, settings) { if (jqxhr.status == 401) { if (loginUrl) { $("body").prepend("<div class='loginoverlay'><div class='full'></div><div class='iframe'><iframe id='login' src='" + loginUrl + "'></iframe></div></div>"); $("div.loginoverlay").show(); lastAjaxCall.jqXHR = jqxhr; lastAjaxCall.settings = settings; } } } } This showed login in iframe over current page (looking like user was redirected but you can make it different), and when login was success, this popup was closed, and original ajax request resent: if (lastAjaxCall.settings) { $.ajax(lastAjaxCall.settings); lastAjaxCall.settings = null; } This allows your users to login when session expires without losing any of their work or data typed in last shown form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Ajax jQuery picture upload - newbie question whats the best way to handle this? I have a page with a form on it that the user visits to fill in some info before he signs up for a profile. Underneath the form is a preview of what the profile will look like. I have some javascript so that as the user types into the boxes in the form, the corresponding bit of their profile fills with whatever they're typing. IE they type into the 'title' form input and it will appear in the id="title" div below. In that form I also have a field so the user can upload a photograph. When the user chooses the pic he wants to upload and closes the dialog, I'd like a resized (so that it fits my max height/width requirements) image to also appear in the preview bit below the form. All this would happen before the profile form had been submitted. Whats the best way to go about this? I've done a fair bit of googling and while there's plenty of plugings they all seem to either do something far too complicated or miss something out. Can anyone please tell me the best way to handle this? Thanks :) If it makes any difference I'm using cakephp. Side question - is there a way to make sure that when the choose file dialog opens, there is only the option to select image file types. IE all the .doc .xlt etc aren't there? A: As to your first question, you'll have to upload the file. So you'd upload the image and store it in a temporary location that you can still stream back in an IMG element. When the user saves the form, you can then discard the temp image. You'll probably also need some sort of cron/scheduled task that cleans them up if folks never save the information and just leave. As to your second question, nope. You can check it on the client after they have selected a file, but then I strongly recommend checking it again on the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error in matplotlib library in python while using csv2rec I am working in Ipython, trying to load a csv file. from matplotlib import * data=matplotlib.mlab.csv2rec('helix.csv',delimiter='\t') Here is the error message IOError Traceback (most recent call last) /mnt/hgfs/docs/python/<ipython console> in <module>() /usr/lib/pymodules/python2.7/matplotlib/mlab.pyc in csv2rec(fname, comments, skiprows, checkrows, delimiter, converterd, names, missing, missingd, use_mrecords) 2125 2126 # reset the reader and start over -> 2127 fh.seek(0) 2128 reader = csv.reader(fh, delimiter=delimiter) 2129 process_skiprows(reader) IOError: [Errno 29] Illegal seek Does someone already run on this error? I tried to re-install everything, I am working with Python2.7 and I have Matplotlib v0.99.3, Numpy v1.5.1, Ipython0.10.1 A: I tried with this file: snp1,snp2,snp3 A,A,A A,B,A B,B,B and here is the result: In [3]: csv2rec('helix.csv') Out[3]: rec.array([('A', 'A', 'A'), ('A', 'B', 'A'), ('B', 'B', 'B')], dtype=[('snp1', '|S1'), ('snp2', '|S1'), ('snp3', '|S1')]) I have matplotlib 1.0.1, so you might try updating it, I do not have access to older matplotlib for testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django/Apache freezing with mod_wsgi I have a Django application that is running behind 2 load balanced mod_wsgi/Apache servers behind Nginx (static files, reverse proxy/load balance). Every few days, my site becomes completely unresponsive. My guess is that a bunch of clients are requesting URLs that are blocking. Here is my config WSGIDaemonProcess web1 user=web1 group=web1 processes=8 threads=15 maximum-requests=500 python-path=/home/web1/django_env/lib/python2.6/site-packages display-name=%{GROUP} WSGIProcessGroup web1 WSGIScriptAlias / /home/web1/django/wsgi/wsgi_handler.py I've tried experimenting with only using a single thread and more processes, and more threads and a single process. Pretty much everything I try sooner or later results in timed out page loads. Any suggestions for what I might try? I'm willing to try other deployment options if that will fix the problem. Also, is there a better way to monitor mod_wsgi other than the Apache status module? I've been hitting: curl http://localhost:8080/server-status?auto And watching the number of busy workers as an indicator for whether I'm about to get into trouble (I assume the more busy workers I have, the more blocking operations are currently taking place). NOTE: Some of these requests are to a REST web service that I host for the application. Would it make sense to rate limit that URL location through Nginx somehow? A: Use: http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Extracting_Python_Stack_Traces to embed functionality that you can trigger at a time where you expect stuck requests and find out what they are doing. Likely the requests are accumulating over time rather than happening all at once, so you could do it periodically rather than wait for total failure. As a fail safe, you can add the option: inactivity-timeout=600 to WSGIDaemonProcess directive. What this will do is restart the daemon mode process if it is inactive for 10 minutes. Unfortunately at the moment this happens in two scenarios though. The first is where there have been no requests at all for 10 minutes, the process will be restarted. The second, and the one you want to kick in, is if all request threads are blocked and none of them has read any input from wsgi.input, nor have any yielded any response content, in 10 minutes, the process will again be restarted automatically. This will at least mean your process should recover automatically and you will not be called out of bed. Because you are running so many processes, chances are that they will not all get stuck at the same time so restart shouldn't be noticed by new requests as other processes will still handle the requests. What you should work out is how low you can make that timeout. You don't want it so low that processes will restart because of no requests at all as it will unload the application and next request if lazy loading being used will incur slow down. What I should do is actually add a new option blocked-timeout which specifically checks for all requests being blocked for the defined period, therefore separating it from restarts due to no requests at all. This would make this more flexible as having it restart due to no requests brings its own issues with loading application again. Unfortunately one can't easily implement a request-timeout which applies to a single request because the hosting configuration could be multithreaded. Injecting Python exceptions into a request will not necessarily unblock the thread and ultimately you would have to kill process anyway and interupt other concurrent requests. Thus blocked-timeout is probably better. Another interesting thing to do might be for me to add stuff into mod_wsgi to report such forced restarts due to blocked processes into the New Relic agent. That would be really cool then as you would get visibility of them in the monitoring tool. :-) A: We had a similar problem at my work. Best we could ever figure out was race/deadlock issues with the app, causing mod_wsgi to get stuck. Usually killing one or more mod_wsgi processes would un-stick it for a while. Best solution was to move to all-processes, no-threads. We confirmed with our dev teams that some of the Python libraries they were pulling in were likely not thread-safe. Try: WSGIDaemonProcess web1 user=web1 group=web1 processes=16 threads=1 maximum-requests=500 python-path=/home/web1/django_env/lib/python2.6/site-packages display-name=%{GROUP} Downside is, processes suck up more memory than threads do. Consequently we usually end up with fewer overall workers (hence 16x1 instead of 8x15). And since mod_wsgi provides virtually nothing for reporting on how busy the workers are, you're SOL apart from just blindly tuning how many you have. Upside is, this problem never happens anymore and apps are completely reliable again. Like with PHP, don't use a threaded implementation unless you're sure it's safe... that means the core (usually ok), the framework, your own code, and anything else you import. :) A: If I've understood your problem properly, you may try the following options: * *move URL fetching out of the request/response cycle (using e.g. celery); *increase thread count (they can handle such blocks better than processes because they consume less memory); *decrease timeout for the urllib2.urlopen; *try gevent or eventlet (they will magically solve your problem but can introduce another subtle issues) I don't think this is a deployment issue, this is more of a code issue and there is no apache configuration solving it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: c++ win32 efficient context menus and submenus I would like to add a right click context menu/sub menus to my win32 application (c++) when the user right clicks on the notifiyicon data (tray icon). I can make a simple 1 level menu, but can't find a example for multiple level menus. I would like to a create a menu which looks something like this: Settings -> Setting 1 -> Setting 2 -> Setting 3 -> Settings 4 -> Setting 5 -> Setting 6 Exit I'm creating the menu with this code: HMENU hPopupMenu = CreatePopupMenu(); InsertMenu(hPopupMenu, 0, MF_BYPOSITION | MF_STRING, IDM_EXIT, L"Exit"); SetForegroundWindow(hWnd); TrackPopupMenu(hPopupMenu, TPM_BOTTOMALIGN | TPM_RIGHTALIGN, p.x, p.y, 0, hWnd, NULL); The code above is placed inside the notifyicondata message handler (WM_RBUTTONUP). How can i create submenus using the above code? Do i create a new HMENU and insert it in the parent menu? The other thing that bothers me is that the menu is always created when a right click event is triggered, so every time it fires it creates a new HMENU. Is it possible to create the menu (with submenus) when the application starts and destroy it when the application closes? Does windows handle the destroying of the menu? Thanks for reply's. A: A submenu is just another HMENU (From CreatePopupMenu()) inserted as a menu item with AppendMenu/InsertMenu using the MF_POPUP flag or with InsertMenuItem with MIIM_SUBMENU in the mask. There is nothing stopping you from creating the menu when your application starts but unless the menu has a large amount of items or creating the items requires a lot of calculation I don't see the problem with creating them in response to the tray icon message. You have to destroy a HMENU yourself (Except if it is attached to a HWND with SetMenu())
{ "language": "en", "url": "https://stackoverflow.com/questions/7532278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Printing with javascript problems.....div comes as a null string I am using a javascript function to print a page. I keep getting the string as a null value and im not sure how.....here is the code. The div i have is called divSheet and its set to visible false to begin...when you load information it creates a table in the divSheet and sets it to true. Any ideas why it says the strid in getPrint function is null? Thank you! <asp:ImageButton runat="server" ID="imageBtnPrint" Style="z-index: 100" ImageUrl="~/Images/printerIcon.gif" OnClientClick="javascript:getPrint('divSheet')" ToolTip="Print" /> function getPrint(strid) { var pp = window.open(); var prtContent = document.getElementById(strid); pp.document.writeln('<HTML><HEAD><title>Print Confirmation Sheet</title><LINK href=PrintStyle.css type="text/css" rel="stylesheet">') pp.document.writeln('<LINK href=PrintStyle.css type="text/css" rel="stylesheet" media="print"><base target="_self"></HEAD>') pp.document.writeln('<body MS_POSITIONING="GridLayout" bottomMargin="0" leftMargin="0" topMargin="0" rightMargin="0">'); pp.document.writeln('<form method="post">'); pp.document.writeln('<TABLE width=100%><TR><TD></TD></TR><TR><TD align=right><INPUT ID="PRINT" type="button" value="Print" onclick="javascript:location.reload(true);window.print();"><INPUT ID="CLOSE" type="button" value="Close" onclick="window.close();"></TD></TR><TR><TD></TD></TR></TABLE>'); pp.document.writeln(document.getElementById(strid).innerHTML); pp.document.writeln('</form></body></HTML>'); } A: I think that's because you are spawning a child window from your main HTML, and the child page cannot access parent's variables directly. You could set a local variable in the parent HTML to your div's ID, and then from your JS function access it using: window.opener.<variable name> Something like this: (warning : untested) ... var divId; function getPrint(strid) { divId = strid; var pp = window.open(); var prtContent = document.getElementById(window.opener.divId); ... ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7532281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best way of writing box-box ray collision detection in three.js? The objects in this experiment are moving around randomly: http://deeplogic.info/project/webGL/ What is the best way of writing a box-box ray collision detection for this using the three.js library? A: If you're using raytracing: For both boxes, check it's 12 edges against the other box's 6 faces. If none of them intersect, you can be sure that there is no collision. To check one box's edge against another box's face: Define an infinite ray that goes directly along the edge. Define an infinite plane that lies on the other box's face. Use ray-plane intersection to find the intersection point of the infinite plane and the infinite ray. Check that the intersection point: a) lies on the edge of your box, and b) lies within the other box's face. If so, you have an intersection! As for what to do with that intersection once you know it's happened, that's a whole new topic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which format should the version constant of my project have Ive seen lots of stuff Foo::VERSION::STRING Foo::VERSION Foo::Version any suggestions what the best/most-common default is ? A: First of all, Foo::Version seems wrong to me. That implicates that version is a Class or a Module, but should be a constant, as first two of your examples. Apart from that, there is no golden rule here. Here are a few examples: Rails: Rails::VERSION::STRING (Note: a module VERSION with all capitals.) SimpleForm: SimpleForm::VERSION Nokogiri: Nokogiri::VERSION RSpec: RSpec::Version::STRING (Note, a module Version, compare with Rails above.) Cucumber: Cucumber::VERSION SimpleForm: SimpleForm::VERSION Most of the above have their version defined in the lib/[name]/version.rb file, except for Rails, which has a version.rb in the root of the project, and Cucumber, which has buried it in the lib/cucumber/platform.rb file. Also note that all of the above use Strings as a version. (Rails even concatenates MAJOR, MINOR, TINY, and PRE constants into a single VERSION constant.) This allows for easy comparison of versions: "1.2.3" > "0.4.2" # => true "1.2.3" > "1.2.2" # => true "1.2.3" > "1.2" # => true However, such a comparison fails when you run into double digits for the patch level: "1.2.3" > "1.2.12" # => true To me, defining Foo::VERSION is your best bet, define it in lib/foo/version.rb, and make it a String value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it necessary to Dispose() when using a custom ServiceHostFactory? Is it necessary to Dispose() when using a custom ServiceHostFactory? In my WCF .svc file I have defined a custom Factory as: <%@ ServiceHost Factory="Service.ServiceHostFactory" %> It appears that a Dispose() is not being called since the overridden CreateServiceHost() method is not being called at each execution of the application calling the service. (Also, among other things, logging is not being performed after each call and the trace.xml file I generated says that it is in use by another process). I do have the service decorated with [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] so I expect something else is going on that I'm not aware of. In the client application where the instance to the service is created I am Dispose()'ing of the reference via a finally block but is it necessary to perform a similar operation in the Factory on the server side? Finally service.Dispose() End Try Thanks A: The service host factory returns a service host, not an instance of the service class. The factory is usually called only once per activation of the service, and the host it returns is used until the IIS application pool is recycled. The service instance is handled by an IInstanceProvider, not the service host (although as you're creating the host you can change the instance provider if you want to dispose the service instance - for more information about instance providers, see http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/31/wcf-extensibility-iinstanceprovider.aspx and http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx). So in short, you should not dispose the service (or is it the host?) which you're returning from the service host factory. If you want to handle service disposal, you should implement your own instance provider.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What does Int32.Parse do exactly? I am just beginning to learn C#. I am reading a book and one of the examples is this: using System; public class Example { public static void Main() { string myInput; int myInt; Console.Write("Please enter a number: "); myInput = Console.ReadLine(); myInt = Int32.Parse(myInput); Console.WriteLine(myInt); Console.ReadLine(); } } When i run that and enter say 'five' and hit return, i get 'input string not in correct format' error. The thing i don't understand is, i converted the string myInput to a number didn't i? Microsoft says that In32.Parse 'Converts the string representation of a number to its 32-bit signed integer equivalent.' So how come it doesn't work when i type the word five? It should be converted to an integer shouldn't it... confused. Thanks for advice. A: 'five' is not a number. It's a 4-character string with no digits in it. What parse32 is looking for is a STRING that contains numeric digit characters. You have to feed it "5" instead. A: The string representation that Int32.Parse expects is a sequence of decimal digits (base 10), such as "2011". It doesn't accept natural language. What is does is essentially this: return 1000 * ('2' - '0') + 100 * ('0' - '0') + 10 * ('1' - '0') + 1 * ('1' - '0'); You can customize Int32.Parse slightly by passing different NumberStyles. For example, NumberStyles.AllowLeadingWhite allows leading white-space in the input string: " 2011". A: The words representing a number aren't converted; it converts the characters that represent numbers into actual numbers. "5" in a string is stored in memory as the ASCII (or unicode) character representation of a 5. The ASCII for a 5 is 0x35 (hex) or 53 (decimal). An integer with the value '5' is stored in memory as an actual 5, i.e. 0101 binary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript to jQuery Conversion for an xml ajax call I have the following script if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET", "/getSelectedProductData?offerCollectionRef=" + offerCollectionRef + "&brandRef=" + brandRef + "&priceRef=" + priceRef + "&defaultSmallImage=" + defaultSmallImage + "&offerCode=" + offerCode + "&index=" + index, false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; I know how to write a $.ajax in jQuery. But I am stuck at how to send data. My questions are * *The return is XML and so the dataType: xml. am I correct? *How should I pass the data to the url? Please elaborate on these things. Disclaimer: The thing is that I couldn't test it myself and so this question. A: 1 The return is XML and so the dataType: xml. am I correct? You actually don;t need to specify it if the server sets proper Content-Type header to text/xml. jQuery will automatically consider the result as XML 2 How should I pass the data to the url? You could use the data hash: $.ajax({ url: '/getSelectedProductData', type: 'GET', dataType: 'xml', // not necessary if the server sets the Content-Type: text/xml response header data: { offerCollectionRef: offerCollectionRef, brandRef: brandRef, priceRef: priceRef, defaultSmallImage: defaultSmallImage, offerCode: offerCode, index: index }, success: function(xml) { // ... } }); Also you seem to be sending a synchronous request by setting the async parameter to false. To emulate the same with jQuery you could add the async: false option. This being said, you probably shouldn't be doing it. SJAX (sync javascript) will block the browser during the request and ruin the user experience. A: * *Yep. *You can use the data property when passing settings to $.ajax(). It can be an object (it will be converted to a query string) or a query string. Please check the jQuery Manual for further details. Excerpt from the manual: data (Object, String) Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). So from your example, url shall be '/getSelectedProductData', and data could be everything after ?. Or you can organize them into an object like { 'offerCollectionRef': offerCollectionRef, ... }, it is a bit more readable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: django + javascript Application framework (not Jquery)? Step up from the Django + jQuery / Prototype question... Can anyone tell me about their experience with a UI application framework like YUI or spoutcore, but that works best with django? A: I've found that jQuery (or jQuery UI if you like) is always a solid choice no matter what you're building, and I always end up using it with Django (or any other language/framework for that matter). Users almost always have it cached in their browsers, it's easy to use/learn, tons of examples on the net, and other developers probably already know it. Technically you should be able to set up almost any JS framework you like with Django, but some might require more 'setting up' than others.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert a byte array to uint64 and back in C#? I have been trying this for long. I have a byte array, which I want to convert to ulong and return the value to another function and that function should get the byte values back. I tried bitshifting, but it was unsuccessfull in few cases. Is there any alternate to bitshifting? or do you have any short example? Thanks for the help. Here is the bitshift code that I used, I don't understant why the second entry is not 00000001: using System; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int[]responseBuffer = {0,1,2,3,4,5}; UInt64 my = (UInt64)(((UInt64)(((responseBuffer[0]) << 40) & 0xFF0000000000)) | (UInt64)(((responseBuffer[1]) << 32) & 0x00FF00000000) | (UInt64)(((responseBuffer[2]) << 24) & 0x0000FF000000) | (UInt64)(((responseBuffer[3]) << 16) & 0x000000FF0000) | (UInt64)(((responseBuffer[4]) << 8) & 0x00000000FF00) | (UInt64)(responseBuffer[5] & 0xFF)); UInt64[] m_buffer = {(UInt64)((my >> 40) & 0xff), (UInt64)((my >> 33) & 0xff) , (UInt64)((my >> 24) & 0xff) , (UInt64)((my>> 16) & 0xff) , (UInt64)((my>> 8) & 0xff) , (UInt64)(my& 0xff)}; Console.WriteLine("" + m_buffer[1]); //string m_s = ""; StringBuilder sb = new StringBuilder(); for (int k = 0; k < 6; k++) { int value = (int)m_buffer[k]; for (int i = 7; i >= 0; i--) { if ((value >> i & 0x1) > 0) { sb.Append("1"); value &= (Byte)~(0x1 << i); } else sb.Append("0"); } sb.Append(" "); } Console.WriteLine(sb.ToString()); Console.Read(); } } } A: Firstly I'd work out what went wrong with bitshifting, in case you ever needed it again. It should work fine. Secondly, there's an alternative with BitConverter.ToUInt64 and BitConverter.GetBytes(ulong) if you're happy using the system endianness. If you want to be able to specify the endianness, I have an EndianBitConverter class in my MiscUtil library which you could use. (If you just need it to be reversible on the same sort of machine, I'd stick with the built in one though.) A: I'm not sure what the point of the left bitshifting and right bitshifting you're doing initially.(i'm assuming you're trying to generate Uint64 values to test your function with). To fix your function, just cast the numbers to UInt64 and then test them. Alternatively you can create long literals by using a suffix of l. such as UInt64[] responseBuffer = {0l,1l}; static void Main(string[] args) { int[] responseBuffer = { 0, 1, 2, 3, 4, 5 }; List<UInt64> bufferList = new List<ulong>(); foreach (var r in responseBuffer) bufferList.Add((UInt64)r); UInt64[] m_buffer = bufferList.ToArray(); foreach (var item in m_buffer) Console.WriteLine(item); //string m_s = ""; StringBuilder sb = new StringBuilder(); for (int k = 0; k < m_buffer.Length; k++) { int value = (int)m_buffer[k]; for (int i = 7; i >= 0; i--) { if ((value >> i & 0x1) > 0) { sb.Append("1"); value &= (Byte)~(0x1 << i); } else sb.Append("0"); } sb.Append(" "); } Console.WriteLine(sb.ToString()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7532297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to tell if my unbound service is running? I have read the other threads about checking if a service is running but this is not working for me. My situation is that am creating a background web server service but not binding to it because I want it to continue running after the activity ends. The service creates a notification so users can see it is running. The user can stop the service through a button on the Activity. This is all working fine, except on launch of the activity, I can't determine if the service is already running. Am using the following: if (isMyServiceRunning() == false) { Intent ws = new Intent(this, WebServerService.class); startService(ws); } And this private boolean isMyServiceRunning() { String sClassName; ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { sClassName = service.service.getClassName(); DebugMsg("Service: " + sClassName); if (sClassName.contains("com.<mydomain>.webservice")) { return true; } } return false; } I get a list of services running, for both system and 3rd party services. But my service doesn't show up in the list, even though I know it's running. If I go into the phone's Settings -> Applications -> Running Services, I can see it running there. I read in the documentation somewhere that calling startService on a service that is already running should be ignored. But that isn't the case as I can see in the debugger that both OnCreate and OnStart are being called. It is important that I do not create a new service each time because the background service may be in the middle of serving a file. The activity does not need to do any communication with the service - only start it if it isn't running and kill it if the user hits a button. Any idea on why my service is not showing up in the getRunningServices list? A: Step #1: Add static boolean isRunning=false to your service. Step #2: Set isRunning to true in onCreate() of the service. Step #3: Set isRunning to false in onDestroy() of the service. Step #4: Examine isRunning to see if the service is running. I read in the documentation somewhere that calling startService on a service that is already running should be ignored. But that isn't the case as I can see in the debugger that both OnCreate and OnStart are being called. I am very confident that onCreate() is not called when startService() is invoked on a running service. onStartCommand() (and, hence, onStart() for older services) will be called for every startService() call. It is important that I do not create a new service each time Services are natural singletons. There will be precisely 0 or 1 copies of the service in memory. There will never be 2 or more. A: Actually, my service is now showing up in the list of services. I'm now thinking that maybe the service name wasn't registered until after restarting the phone, because I didn't make any changes but everything is working now after restarting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: skip copying to tmp table on disk mysql I have a question for large mysql queries. Is it possible to skip the copying to tmp table on disk step that mysql takes for large queries or is it possible to make it go faster? because this step is taking way too long to get the results of my queries back. I read on the MySQL page that mysql performs this to save memory, but I don't care about saving memory I just want to get the results of my queries back FAST, I have enough memory on my machine. Also, my tables are properly indexed so that's not the reason why my queries are slow. Any help? Thank you A: There are two things you can do to lessen the impact by this OPTION #1 : Increase the variables tmp_table_size and/or max_heap_table_size These options will govern how large an in-memory temp table can be before it is deemed too large and then pages to disk as a temporary MyISAM table. The larger these values are, the less likely you will get 'copying to tmp table on disk'. Please, make sure your server has enough RAM and max_connections is moderately configured should a single DB connection need a lot of RAM for its own temp tables. OPTION #2 : Use a RAM disk for tmp tables You should be able to configure a RAM disk in Linux and then set the tmpdir in mysql to be the folder that has the RAM disk mounted. For starters, configure a RAM disk in the OS Create a folder in the Linux called /var/tmpfs mkdir /var/tmpfs Next, add this line to /etc/fstab (for example, if you want a 16GB RAM disk) none /var/tmpfs tmpfs defaults,size=16g 1 2 and reboot the server. Note : It is possible to make a RAM disk without rebooting. Just remember to still add the aforementioned line to /etc/fstab to have the RAM disk after a server reboot. Now for MySQL: Add this line in /etc/my.cnf [mysqld] tmpdir=/var/tmpfs and restart mysql. OPTION #3 : Get tmp table into the RAM Disk ASAP (assuming you apply OPTION #2 first) You may want to force tmp tables into the RAM disk as quickly as possible so that MySQL does not spin its wheels migrating large in-memory tmp tables into a RAM disk. Just add this to /etc/my.cnf: [mysqld] tmpdir=/var/tmpfs tmp_table_size=2K and restart mysql. This will cause even the tiniest temp table to be brought into existence right in the RAM disk. You could periodically run ls -l /var/tmpfs to watch temp tables come and go. Give it a Try !!! CAVEAT If you see nothing but temp tables in /var/tmpfs 24/7, this could impact OS functionality/performance. To make sure /var/tmpfs does not get overpopulated, look into tuning your queries. Once you do, you should see less tmp tables materializing in /var/tmpfs. A: You can also skip the copy to tmp table on disk part (not answered in the selected answer) * *If you avoid some data types : Support for variable-length data types (including BLOB and TEXT) not supported by MEMORY. from https://dev.mysql.com/doc/refman/8.0/en/memory-storage-engine.html (or https://mariadb.com/kb/en/library/memory-storage-engine/ if you are using mariadb). *If your temporary table is small enough : as said in selected answer, you can Increase the variables tmp_table_size and/or max_heap_table_size But if you split your query in smaller queries (not having the query does not help to analyze your problem), you can make it fit inside a memory temporary table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "70" }
Q: SSRS 2008 huge pdf report, blank pages We are having an issue while generating a huge PDF Report. We are using SSRS 2008 and a particular report generates more than 1000 pages. If I export to PDF format, the data is populated upto page no. 465 and rest of the pages till 1000 are totally blank. I have Adobe Reader 9.0 installed on my machine and I thought there should be some issue with the reader itself. I upgraded to Adobe Reader 10 but experiencing same issue. Everytime I generate the report and export to PDF (using the report viewer webcontrol), the pages become blank after 465. There is absolutely no problem with the data (the stored procedure which I am using to load customers) and I have verified in the backend. We had this issue last month and somehow it got fixed automagically. Now again we have the same issue. Any help please? A: Apparently there was nothing wrong with SSRS or Adobe reader or anything related to caching. Some of the sections in each page were pushed to next page due to increase in height of an image. When I readjusted the height of the embedded image control, everything went fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run Adobe AIR Application on Apple iPad? I am Adobe Flash Designer\Developer and i ended AIR Application for desktop and need to know how to launch this app on iPad? A: You will need to port the Application to an AIR Mobile app to get it to run on the iPad. Ttis can be easier said than done depending on what you are using. If it is pure a pure ActionScript project then it will probably be easier than if you are using Flex/MXML components that are not optimized for mobile. You may want/need to create new views for the mobile platform as well. Additionally you will then probably need to change some things for specific mobile support. Will your app support rotation of the device? Will you want gesture support? Shake support? Are you using the Encrypted Local Store (Not supported in AIR Mobile 2.x, will be supported in AIR 3.0)? You'll also have to test the performance on an actual device. The iPad is considerably slower than your average desktop computer. Does your app do anything memory or processor intensive that could make the iPad freeze up for an extended period. Here is an article on considerations for AIR for Mobile that you may want to look at: http://www.adobe.com/devnet/air/articles/considerations-air-apps-mobile.html Here are some iOS Considerations: http://www.adobe.com/devnet/devices/ios.html Finally, here is a section of the Adobe AIR for Flash Developers documentation that you'll want to look at: http://help.adobe.com/en_US/air/build/WSfffb011ac560372f-5d0f4f25128cc9cd0cb-8000.html Good luck. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7532312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: In an external assets folder the best place to put libraries for CodeIgniter 2.x? when I last used CodeIgniter it was version 1.x and I read an external assets folder for css, js, and images was the best way to handle things. I wanted to know if that is the correct way to do things in 2.x. I found this on SO but it didn't address it directly: Assets in codeigniter The other SO entries were too old to address 2.x. Thank you. A: As long as they are both publicly accessible then there is no difference between application ... system ... assets css style.css images image.png and application ... system ... css style.css images image.png Depending on your .htaccess file you may need to make a change but CodeIgniter doesn't require you to use any specific scheme for storing assets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cross domain iframe resizer using postMessage I've read all the cross domain iframe posts here (my thanks to all of you!) and elsewhere. The postMessage script at cross-domain iframe resizer? works beautifully in Firefox 5 and up. It resizes the iframe every time a page is clicked within the iframe perfectly. But it doesn't resize at all in IE (7 8 or 9) on my computer. I checked the security settings and the one in IE for access across domains was checked to enable. Does postMessage not work in IE? - Or is there something else that needs to be added? thanks A: It's a great script from thomax - it also works on so you can use iframes on mobile - iphones and android For IE7 and IE8, you have to use window.attachEvent instead of window.addEventListener It should also be onmessage instead of message (see below) ps you also need to do the same on the server with the content posting its size <script type="text/javascript"> if (window.addEventListener) { function resizeCrossDomainIframe(id) { var iframe = document.getElementById(id); window.addEventListener('message', function(event) { var height = parseInt(event.data) + 32; iframe.height = height + "px"; }, false); } } else if (window.attachEvent) { function resizeCrossDomainIframe(id) { var iframe = document.getElementById(id); window.attachEvent('onmessage', function(event) { var height = parseInt(event.data) + 32; iframe.height = height + "px"; }, false); } } </script> A: Using Peter's code and some ideas from here, you could separate out the compatibility from the executable code, and add some cross-site validation. <script type="text/javascript"> // Create browser compatible event handler. var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; var eventer = window[eventMethod]; var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"; // Listen for a message from the iframe. eventer(messageEvent, function(e) { if (e.origin !== 'http://yourdomain.com' || isNaN(e.data)) return; document.getElementById('iframe_id_goes_here').style.height = e.data + 'px'; }, false); </script> Also, for completeness, you could use the following code within the iframe whenever you want to trigger the resize. parent.postMessage(document.body.offsetHeight, '*'); A: You can use the implementation of Ben Alman. Here is an example of cross-domain communication, including an example of iframe resize. http://benalman.com/code/projects/jquery-postmessage/examples/iframe/ According to the documentation, it works on Internet Explorer 6-8, Firefox 3, Safari 3-4, Chrome, Opera 9. A: Having looked a lots of different solutions to this I ended up writing a simple jQuery plugin to take a account of a number of different use cases. As I needed a solution that supported multiple user generated iFrames on a portal page, supported browser resizes and could cope with the host page JavaScript loading after the iFrame. I also added support for sizing to width and a callback function and allow the override of the body.margin, as you will likely want to have this set to zero. https://github.com/davidjbradshaw/iframe-resizer The host page users jQuery, the iframe code is just a little self-contained JavaScript, so that it's a good guest on other people pages. The jQuery is then initialised on the host page and has the following available options. More details on what these do on the GitHub page. $('iframe').iFrameSizer({ log: false, contentWindowBodyMargin:8, doHeight:true, doWidth:false, enablePublicMethods:false, interval:33, autoResize: true, callback:function(messageData){ $('p#callback').html('<b>Frame ID:</b> ' + messageData.iframe.id + ' <b>Height:</b> ' + messageData.height + ' <b>Width:</b> ' + messageData.width + ' <b>Event type:</b> ' + messageData.type); } }); If you set enablePublicMethods, it gives you access in the iframe to manually set the iFrame size and even remove the iframe from the host page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: foreach with cycle/alternate options I am looking for a fastest(performance) way to cycle/alternative 2 values inside of a foreach loop. Exactly the same as the smarty works: http://www.smarty.net/docsv2/en/language.function.cycle A: Cycling is easy with the modulo operator. $cycle = $iteration % $cycles; If $cycles is 2, for instance, then $cycle will contain 0 and 1 alternating as $iteration increases. Then if you need specific values for these cycles, use a look-up table: $lookup = array('value1', 'value2'); $value = $lookup[$cycle]; The foreach loop does not keep track of iterations, though; You'd want to use a for loop for that instead. Or increment an iteration variable yourself. A: $cycle = array('value1', 'value2'); $i = 0; foreach (...) { $cycle[$i] // current cycle value ... $i = 1 - $i; // here be cycling } P.S. And don't think you should be very concerned about performance in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: One button firing another buttons click event I'd like two submit buttons on a form i have my team building, one above the fold, and one below. I'm getting complaints from my tech team about adding it because it requires some server side coding to make sure the user doesn't click it more than once. Apparently they have it one button, but to add that validation to two would be a problem. Can you not just call the button the same thing, with the same ID and wouldn't the form treat it as one button? Another option I thought would be for new button to fire a click even on the other button. Then they still have one click even for the form, but I get my two buttons. How would I write that? Thanks, Adma A: <input type="button" id="primaryButton" onclick="ExistingLogic()" /> <input type="button" id="secondaryButton"/> $('#secondaryButton').click(function(){ $("#primaryButton").click(); }) A: I'm only familiar with ASP.net and C# buttons, but using C# you could wire two different buttons to the same click event handler. You could also do it client side by triggering the primary buttons click event with your secondary button. Here's a VERY simple example: HTML <input type="button" id="primaryButton" onclick="ExistingLogic()" /> <input type="button" id="secondaryButton" onclick="document.getElementById('primaryButton').click()" /> A: If you want to use vanillaJS to do this... here is a generic very long way (with functions for both to be clear what is happening). html <input type="button" id="primaryButton" /> <input type="button" id="secondaryButton"/> script const primary = document.getElementById('primaryButton'); const secondary = document.getElementById('secondaryButton'); function somePrimaryAction(e){ e.preventDefault(); console.log('you clicked the primary button'); } function someSecondaryFunction(e){ e.preventDefault(); console.log('you clicked the secondary button'); primary.click(); } primary.addEventListener("click", somePrimaryAction, false); secondary.addEventListener("click", someSecondaryFunction, false); A: Yeezy <button onclick="$('#button2').click()">button 1</button> <button id="button2" onclick="doSomethingWhenClick()">button 2</button> (((You need jQuery to run this)))
{ "language": "en", "url": "https://stackoverflow.com/questions/7532320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: How to consume posted file via HttpHandler? I have constructed a method that takes a local file and posts it to a remote site taken from the 2nd answer here. On the remote site, I have my HttpHandler but do not know where the file bytes are so I can save it somewhere on the remote machine. Can someone help me on how to consume that file in the HttpHandler for processing? I tried the below but Request.Files is empty: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Collections.Specialized; namespace Somewhere { public class UploadFileHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //VALIDATE FILES IN REQUEST if (context.Request.Files.Count > 0) { //HANDLE EACH FILE IN THE REQUEST foreach (HttpPostedFile item in context.Request.Files) { item.SaveAs(context.Server.MapPath("~/Temp/" + item.FileName)); context.Response.Write("File uploaded"); } } else { //NO FILES IN REQUEST TO HANDLE context.Response.Write("No file uploaded"); } } public bool IsReusable { get { return false; } } } } A: Get hold of the HttpRequest from the context, and use the Files property to get a collection of HttpPostedFile objects. You can then access the data from HttpPostedFile.InputStream (there are other properties for the name, length and MIME type). EDIT: Now that the question's been edited to show that you're already using the Files property, I strongly suspect that you're looking at the wrong HTTP request, or that there's something wrong with how you're making the request. I suggest you use Wireshark to see what's happening at the network level - that way you can check that your request really has the file data in it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableViewCell load Images I have 16 locally stored pre-rendered 40x40 px images that I want to use as my UITableViewCell images. I can get it to display them fine using [UIImage imageNamed:]; but I have noticed this slows down the table view scrolling. I have looked through the apple example for lazy loading etc. and understand I need to do it on a background thread or asynchronously, but have not found an example for local images. Can anybody help? A: Subclass the UITableView cell, and create a new method in the cell that is something like: - (void)setImage:(NSString *)imageName; Then from where you used to set the image, change it to instead do something like: [cell setImage:nil]; [cell performSelector:@selector(setImage:) withObject:@"imageName" afterDelay:0]; Changing it to performSelector:withObject:afterDelay: means that the code to set the image will not execute while the tableView is scrolling. This should lead to a significant improvement in scroll performance as it will not set images into cells until the scrolling stops. However you will notice the lack of images while scrolling so you may want to consider a small placeholder image in the images place to appear while scrolling. Personally I use this method conditionally in my code. I detect how old the UIDevice is, and if its an older generation device I will lazy load like this to increase scroll performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I need to group and summarize flat arraycollection data. Data cannot be grouped out side of app and must return arraycollection I have flat data in my app which I will need to group, summarize, and count as I normally would with a sql query. For this project though, it must be done in the flex app. I need to figure out how to group my data by day or month using a datatime field in my Arraycollection, then appropriately count or summarize data in other fields. I've used Groupingcollections before, but only when binding to hierarchical controls (like AdvancedDataGrid and Tree), but I need a resulting ArrayCollection with the grouped and summarized data. Basically, I'm trying to access my AC like a sql table (GROUP BY MONTH(datetime), COUNT, COUNT(DISTINCT(), etc.) and I'm unsure how to do it. Does anyone have experience doing this? A: You can give ActionLinq (https://bitbucket.org/briangenisio/actionlinq/wiki/Home) a try. I've not used it myself, but I've been itching to give it a try :) It's an implementation of Linq (from C#) in actionscript. This gives you a functional way of dealing with collections of data in a very SQL-like manner (select, group, filter, etc.). I would characterise it like the filter method on steroids. Here is an example from the website - it shows some of the SQL-like names and how the chaining works: var transformed:Array = [-4, -3, -2, -1, 0, 1, 2, 3, 4] .where(isEven) .select(square) .distinct() .reverse() .toArray(); assertThat(transformed, array(0, 4, 16)); More information and examples here: http://riarockstars.com/2011/02/07/processing-data-on-the-clientactionlinq/ A: You may find that this example points you in the right direction http://flexdiary.blogspot.com/2008/09/groupingcollection-example-featuring.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7532331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to get data out of Open Graph? I was wondering if facebooks open graph allows you to somehow get the data out of it. For example if you need to find all the movies people have marked up using facebooks open graph is there anyway you can get that. A: Yes, you need to get permission from the individual users though. A good source for the data available Facebook OG API is the Open Graph Explorer: https://developers.facebook.com/tools/explorer You may need to register as a Facebook Developer first ( free ).
{ "language": "en", "url": "https://stackoverflow.com/questions/7532332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: any better way of Sorting my dropdownlist After I retrieve the country names in English, I convert the country names to localized versions, I need to sort those names again, so I used SortDropDownList. Here, after I sort my DropDownList Items, I am losing the PrivacyOption attribute I set. Can someone suggest solutions to sort my DropDownList while also retaining the PrivacyOption attribute? I am using asp.net4.0 along with C# as CodeBehind: int iCount = 1; //fetch country names in English List<CountryInfo> countryInfo = ReturnAllCountriesInfo(); foreach (CountryInfo c in countryInfo) { if (!string.IsNullOrEmpty(Convert.ToString( LocalizationUtility.GetResourceString(c.ResourceKeyName)))) { ListItem l = new ListItem(); l.Text = Convert.ToString( LocalizationUtility.GetResourceString(c.ResourceKeyName)); l.Value = Convert.ToString( LocalizationUtility.GetResourceString(c.ResourceKeyName)); //True /False* l.Attributes.Add("PrivacyOption", *Convert.ToString(c.PrivacyOption)); drpCountryRegion.Items.Insert(iCount, l); iCount++; } //sorts the dropdownlist loaded with country names localized language SortDropDownList(ref this.drpCountryRegion); } And the code to SortDropDownList items: private void SortDropDownList(ref DropDownList objDDL) { ArrayList textList = new ArrayList(); ArrayList valueList = new ArrayList(); foreach (ListItem li in objDDL.Items) { textList.Add(li.Text); } textList.Sort(); foreach (object item in textList) { string value = objDDL.Items.FindByText(item.ToString()).Value; valueList.Add(value); } objDDL.Items.Clear(); for (int i = 0; i < textList.Count; i++) { ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString()); objDDL.Items.Add(objItem); } } A: Sort the data before you populate the DropDownList. IEnumerable<Country> sortedCountries = countries.OrderBy( c => LocalizationUtility.GetResourceString(c.ResourceKeyName)); foreach (Country country in sortedCountries) { string name = LocalizationUtility.GetResourceString(country.ResourceKeyName); if (!string.IsNullOrEmpty(name)) { ListItem item = new ListItem(name); item.Attributes.Add( "PrivacyOption", Convert.ToString(country.PrivacyOption)); drpCountryRegion.Items.Add(item); } } A: Have you thought about sorting the information in a SortedDictionary instead of a List? A: I am not quiet sure if I understand how your implementation of SortDropDownList method works. However, I can suggest using a List<KeyValue<string, string>> to bind to your DropDownList. You can use the English part and local part in your KeyValuePair and sort accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add a menuItem to a context menu which has a set ItemsSource and ItemContainerStyle in XAML I have the following XAML code. The contents in the ItemsSource are displayed as MenuItems. <controls:DropDownButton x:Name="btnOwner" DockPanel.Dock="Left" Style="{StaticResource btnStyle}" HorizontalAlignment="Left" Visibility="{Binding IsOwnerVisible}"> <controls:DropDownButton.Content> <ContentControl Width="22" Height="22" Style="{StaticResource iconOwner}"/> </controls:DropDownButton.Content> <controls:DropDownButton.DropDown> <ContextMenu HorizontalContentAlignment="Stretch" ItemsSource="{Binding Owners, Mode = TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemContainerStyle="{StaticResource OwnerStyle}"> </ContextMenu> </controls:DropDownButton.DropDown> How can I add a new menuItem something like a SubMenuHeader via XAML to this List? A: It will create itself. All that you need to provide the ItemTemplate in which you will decide what to show and how to show in each MenuItem. Otherwise, the default implemention will call ToString() method for each item in Owners, and will display it in MenuItem. <ContextMenu ItemsSource="{Binding Owners}"> <ContextMenu.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Title}"/> </DataTemplate> </ContextMenu.ItemTemplate> </ContextMenu> Here, I assumed that the type of owner has a property name Title. For example, if Owners is ObservableCollection<Owner>, then Owner is defined as: public class Owner { public string Title { get; set;} //... } That is basic idea as to how to use ItemTemplate. Now if you want submenuitem in the context menu, then you've to use HierarchicalDataTemplate instead of DataTemplate in the ItemTemplate definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which one to learn Python 3.x or Python 2.x? I wanted to learn the python programming but I don't know which one to learn, I mean I think there are some difference between the two languages and I wanted to know which one is going to be used in the future. It does make sense if I learn Python 2.x and it is stopped being used by anyone. Any info please? A: Most useful modules still aren't ported to Python3. So if you need to call such things you are better off learning Python 2.x until they are ported. Even today the standard version of Python that OSes call is 2.x. (For instance OSX Lion has 2.7.1) Unless there's a compelling reason to use 3.x (such as just learning it so you're ready) then go with 2.x. A: I had this same question and am always wondering why choose one over the other. Here's my approach. I learned python3 because it seems to have more 'stuff' in it than python2, but because most of the things can be done in either version, I usually code in python2. The reason, like Clark mentioned, is most of the modules I need are in python2 but as they slowly move to python3 I'll be a position to quickly move over(google app engine only supports python2 right now but I read they a considering python3 support). So far so good, other than a few sytax differences its pretty simple to code between both of them. One thing I learned from coding is although the language can be measured for its differences, it doesn't really have a huge impact on programming(at least for what I have done so far). Programming is more about how you think and at a basic level all languages will have tools to get the job done, so focus on what comes naturally to you and you enjoy. Best of luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7532339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I delete the committed files from Github? My project is here [the link is not for marketing thing as many might think], I am entirely new to Git and Github and I Use Git Extensions with Visual Studio 2008. I committed the file, directory Plug.Sln and Samples into Github, now * *How the heck do I remove it from them & leave no trail that file existed in my repository?[on github, but make them remain in local repository] *I want to untrack these checked in Files in Visual Studio[I mean like, how do I get it to state it was before checking in these] *How do I revert to a last committed version? A: Github has a help section for this situation. You can view it here. That will remove them if they never existed. If you want to keep them around, make a copy of the file before you follow the github guide. Once you have removed them from your repository, add them back to your working directory, and add than add them to your .gitignore file to keep git from tracking them. A: It sounds like you want to remove the file from version control. Check out How to stop tracking and ignore changes to a file in Git? for a solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: simple jquery each loop making browser hang so i'm calling a function in jquery that's looping over a table and determining whether to hide a row based on a hidden form element within each row. when i run this script, toggling the rows either way, the browser hangs for at least 5 seconds even though there are fewer than 100 rows. the js looks like this: $('input.vv').each(function(index) { var chk = $(this).val(); if (chk == "0") $(this).parents("tr").slideToggle(function() { tableRows(); }); }); and a sample row from the html looks like this: <tr class="sortable part item" id="row803"> <td class="col-check">Interior Fixed Dome Camera Surface Mounted<br />(Panasonic Part No. WV-CW484AS/29) <input type="hidden" class="vv" value="50" id="v803" /></td> <td class="col-equip cen" id="q803">70</td> <td class="col-equip cen" id="s803">50</td> <td class="col-equip cen"><div id="bom803|092311-001|15" />50</div></td> <td class="col-equip cen" id="b803"><span class="shipped">20</span></td> </tr> the line of jquery.js that firebug refers to is 8449 return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; i'm stuck (can't link to the live site sorry). firebug may give me a way out of this but i'm unsure how to use it well enough. thoughts anyone? thanks! A: $('input.vv') creates a loop which goes through all input elements, and checks whether they're a part of the vv class. .parents("tr") loops through all parent nodes, and selects only the <tr> elements. Then, you call .slideToggle, which creates an effect which requires a significant amount of computing power (at small intervals, CSS style adjustments through JQuery, CSS style parsing by browser). likely to be the main cause Finally, you're calling tableRows();, which you haven't defined yet. These operations, on "fewer than 100 rows" requires much computing power. A: Try being a little more specific: $('input.vv').each(function(index) { if ($(this).value == "0") $(this).parent().parent().slideToggle(function() { tableRows(); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7532346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return a list of links from a webpage in R I'm trying to write a function in r that, given an address, will return a list of links on that webpage. For example: getLinks("http://prog21.dadgum.com/109.html") Would return: "http://prog21.dadgum.com/prog21.css" "http://prog21.dadgum.com/atom.xml" "http://prog21.dadgum.com/index.html" "http://prog21.dadgum.com/archives.html" "http://prog21.dadgum.com/atom.xml" "http://prog21.dadgum.com/56.html" "http://prog21.dadgum.com/39.html" "http://prog21.dadgum.com/109.html" "http://prog21.dadgum.com/108.html" "http://prog21.dadgum.com/107.html" "http://prog21.dadgum.com/106.html" "http://prog21.dadgum.com/105.html" "http://prog21.dadgum.com/104.html" A: This function seems to work on other webpages, but for some reason does not return the complete URLs for the page in question. I'm interested to see if there's a better way to do this. getLinks <- function(URL) { require(XML) doc <- htmlParse(URL) out <- unlist(doc['//@href']) names(out) <- NULL out }
{ "language": "en", "url": "https://stackoverflow.com/questions/7532348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What interesting open source software is written in Lisp? I was looking looking for the sources of real-life applications that are written in Lisp. For example a Pacman clone or a word processor would qualify as such. A: How about a * *web server? *text editor? *a type setter? *an interactive musical score editing application? More example can be had at the cliki. Just stroll around a little bit. A: The package-management application (similar to apt-get) that I use for Arch Linux, Paktahn, is written in Common Lisp. A: Here is a list of applications written in Common Lisp. How "real world" they are is debatable, but since you consider a pacman clone to be "real world", I assume you will be satisfied. A: Two big things come to mind. EMACS Maxima The first has an incredible number of customizations. It would not surprise me in the least to find Pac-Man implemented in EMACS. Maxima does symbolic mathematics, so I imagine it'd be more difficult to grok the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Preg_replace domain problem I'm Stuck try to get domain using preg_replace, i have some list url * *download.adwarebot.com/setup.exe *athena.vistapages.com/suspended.page/ *prosearchs.com/se/tds/in.cgi?4&group=5&parameter=mail *freeserials.spb.ru/key/68703.htm what i want is * *adwarebot.com *vistapages.com *prosearchs.com *spb.ru any body can help me with preg_replace ? i'm using this http://gskinner.com/RegExr/ for testing :) A: using preg_replace, if the number of TLDs is limited: $urls = array( 'download.adwarebot.com/setup.exe', 'athena.vistapages.com/suspended.page/', 'prosearchs.com/se/tds/in.cgi?4&group=5&parameter=mail', 'freeserials.spb.ru/key/68703.htm' ); $domains = preg_replace('|([^.]*\.(?:com|ru))/', '$1', $urls); matches everything that comes before .com or .ru which is not a period. (to not match subdomains) You could however use PHPs builtin parse_url function to get the host (including subdomain) – use another regex, substr or array manipulation to get rid of it: $host = parse_url('http://download.adwarebot.com/setup.exe', PHP_URL_HOST); if(count($parts = explode('.', $host)) > 2) $host = implode('.', array_slice($parts, -2)); A: Why use a regular expression? Of course it is possible, but using this: foreach($url in $url_list){ $url_parts = explode('/', $url); $domains[] = preg_replace('~(^[^\.]+\.)~i','',$url_parts[0]); } $domains = array_unique($domains); will do just fine; A: Following code assumes that every entry is exactly at the beginning of the string: preg_match_all('@^([\w]*\.)?([\w]*\.[\w]*)/@', $list, $m); // var_dump($m[2]); P.S. But the correct answer is still parse_url. A: maybe a more generic solution: tested by grep, I don't have php environment, sorry: kent$ echo "download.adwarebot.com/setup.exe dquote> athena.vistapages.com/suspended.page/ dquote> prosearchs.com/se/tds/in.cgi?4&group=5&parameter=mail dquote> freeserials.spb.ru/key/68703.htm"|grep -Po '(?<!/)([^\./]+\.[^\./]+)(?=/.+)' output: adwarebot.com vistapages.com prosearchs.com spb.ru
{ "language": "en", "url": "https://stackoverflow.com/questions/7532354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: to develop facebook app with Rails 3 Which is the best way for to develop a facebook app (Fan page) with Ruby on Rails 3? A: Not sure what you mean by "best way". I use Koala and the FB JS API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drawable on simple button * *How can a button (Button) receive a drawable and center it on the button without the text? *If you can not do this, how then do to the background does not "stretch" button at all? The problem is that for some button have icon and text, for others only the icon and the third type only text! So I have to use an object alone, more stylish, rather than several different classes. Google needs to improve this architecture! If I want a button with or without text, occluding the center with the image, it is my problem, I should be able to do! A: Use a layout, such as AbsoluteLayout, LinearLayout, or RelativeLayout with a TextView and ImageView to create your custom clickable layout and views. Also check this article about layout reuse. A: For your first request: use ImageButton if you wanna have Both, text and drawable, or combinations of that I think you have to subclass button yourself. You can look inside the code of TabWidget how to do that (because TabWidget can already have both but was intended to start Activities)
{ "language": "en", "url": "https://stackoverflow.com/questions/7532366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Embeddable PK Object not populating after persist and flush I have an embedded PK object that doesn't populate the id field after persisting and flushing to the database. The ID is an auto-increment field in the database. Now normally, I would just try a refresh, but it throws the following error: "Entity no longer exists in the database: entity.Customers[ customersPK=entity.CustomersPK[ id=0, classesId=36 ] ]." public class Customers implements Serializable { @EmbeddedId protected CustomersPK customersPK; ... } @Embeddable public class CustomersPK implements Serializable { @Basic(optional = false) @Column(name = "id") private int id; @Basic(optional = false) @NotNull @Column(name = "classes_id") private int classesId; ..... } And here's the code that makes the call Classes cl = em.find(Classes.class, classId); CustomersPK custPK = new CustomersPK(); custPK.setClassesId(cl.getId()); Customers cust = new Customers(custPK); em.persist(cust); em.flush(); // The problem is right here where id always equals 0 int id = cust.getCustomerspk().getId(); Thanks for the help. A: Why would the id not be 0, you have never set it? If it is a generated id, you need to annotate it using @GeneratedValue, otherwise you need to set the value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert flv video to mp3 using ffmpeg programmatically? I need to create application on C++ for video conversion, and I can't use ffmpeg.exe. I need to do it programmatically, but I don't know how can I do it, and I didn't find any examples on Internet. May be somebody know something about my task? Thank you. A: ffmpeg is an open source project. The transcoding engine used by ffmpeg is in the libraries libavcodec (for the codecs) and libavformat (for the containers). You can write your conversion as calls into these libraries, without the ffmpeg command line application. Here is a tutorial on using these libraries. Good luck. A: Here's another good ffmpeg tutorial. Looking at the actual source code for ffmpeg would also help. An updated version of the tutorial source is here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery looping through classes using each() - problem I am using this code to loop through each ".accessoryrow" and then select "dialog" + counter and ".see-details" + counter. So first time when loop goes by it selects dialog1 class and see-details1 class; second time dialog2, see-details2 and so on. I think I am not correctly adding counter to the selector. Please correct me. Thank you CODE: var counter = 1; $(function () { $(".accessoryrow").each(function() { $(".dialog" + counter).dialog({ autoOpen: false, show: "blind", hide: "fade" }); $(".see-details" + counter).click(function () { $(".dialog" + counter).dialog("open"); return false; }); counter++; }); A: The problem is that the $(".dialog" + counter).dialog("open"); line isn't getting evaluated until the link is clicked. Thus it's using the value of counter which is current as of then. A better way to do it would be to take out the counter altogether, and use jQuery selectors to select the correct .dialog. Without the HTML, I can't say what it should look like, but you're going to want the click function to look like something along the lines of $(".see-details").click(function () { $(this).sibling(".dialog").dialog("open"); return false; }); Of course, that assumes that the .dialog element is actually a sibling of .see-details. You'll need to traverse the tree a bit more if it isn't. A: Try this (untested): $(function () { $(".accessoryrow").each(function(index) { $(".dialog" + (index + 1)).dialog({ autoOpen: false, show: "blind", hide: "fade" }); $(".see-details" + (index + 1)).click(function () { $(".dialog" + (index + 1)).dialog("open"); return false; }); }); Index passes the loop number to the function. It starts from 0, where I think you need it to start at 1, so I've added 1 to each where it's used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why CUDA block size of 256 or 512 gives better performance as compared to others? I ve written few programs in CUDA C on windows 7. I did the experimentation with the block size. I found that in most of the cases block size of 256 or 512 gives better performance than other. Can any body tell me the exact technical reason behind it? or point out any resource to know. Since other block sizes multiples of 32 (warp) gives less performance. Thanks in advance. A: Without actual measurements, there's no way to be sure of the optimal block size for a given chip. If you are doing 2D texturing, for example, a 16x4 block happens to work really well. In your case, it's possible that 512 happens to be a multiple of the number of memory partitions in the chip. (On the GeForce 8800 GTX, with 6 memory partitions, 384 was a really good block size for bandwidth-bound kernels). Occupancy is just one of many considerations that affect performance - more threads isn't always better - for workloads that can use registers (instead of shared memory) to hold intermediate results, blocks that use more registers and fewer threads work best. Sorry I can't give a more definitive answer, but it is a complicated issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replace a SqlDataAdapter for SqlCommand in my C# Code My code is construct to read data in a datagridView named (dg) from my database. Its actually work well whit a SqlDataAdapter. First Is it a good idea to change my SqlDataAdapter for a SqlCommand ? If YES I want to use this for change my SqlDataAdapter. //SqlCommand cmd = new SqlCommand("Command String", con); //SqlDataReader readdata; CODE SqlConnection con = new SqlConnection(dc.Con); SqlDataAdapter da = new SqlDataAdapter(); con.Open(); da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", con); DataTable dt = new DataTable(); da.Fill(dt); con.Close(); dg.DataSource = dt; A: I typically use the DataAdapter for data access when I need to do data-binding to controls. It's very convenient and efficient in those scenarios. Otherwise, I use the Command objects directly. Performance-wise, I'm inclined to agree w/ punzki. There shouldn't be much difference between the two. http://msforums.ph/forums/p/9057/9057.aspx Actually, from what I remember, SqlDataAdapter uses SqlDataReader to retrieve records. So It's always good to use SQLDataReader when you're going to just retrieve data from the backend. But if you're going to retrieve data and then update (insert, update, delete) data later on, then it's better to use SqlDataAdapter. I think it's more efficient that way. http://msforums.ph/forums/t/29256.aspx There IS an effect on performance. SqlDataReader is no doubt faster than a SqlDataAdapter as the DataReader reads data in a forward only mode and you can get a specific type of value returned back to you, such as a string or int etc... however with the SqlDataAdapter, it will fill a datatable or dataset will records it finds in your select statement, taking with it the correct value type for the columns and is a disconnected representation of in memory database and is ideal and easier to use if you are going to show large amounts of records to a binding source, as with a SqlDataReader, it is not possible but to only obtain a value for a column you specify per row. The SqlDataAdapter also allows you to Update, Delete or Insert rows into the Dataset/DataTable which is an advantage and will execute the appropriate command, if you implemented it correctly, based on how the rows were modified in the Dataset/DataTable. SqlDataAdapter is expensive compared to a fast forward read on the SqlDataReader, and has more advantages but entirely depends on your solution and what you require. You are stating that you are going to show alot of records, whilst that is all very well, it would be even better for the benefit of the performance and memory usage to only obtain records that you require to be shown and a SqlDataAdapter would be suitable for this also but still you are required to select records which are the ones you will most likely show to the user, either by input search criteria, or perhaps by paging. http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/c2d762fd-f4a0-4875-8bb8-42f7480e97c8/
{ "language": "en", "url": "https://stackoverflow.com/questions/7532379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I fade-in divs on page load and fade them out in the opposite when leaving I have 4 divs on a page, I need them to fade-in one after the other in a clockwise fashion, so not all at once. I also need them to fade out again in the opposite way they faded in when the user leaves the page however they need to have all faded away before the page redirects A: As for the "Fading in" part: $(document).ready(function(){ $('#div1, #div2, #div3, #div4').animate({'opacity' : 0}, 0); fadeInDivs(['#div1', '#div2', '#div4', '#div3']); }); function fadeInDivs(els) { e = els.pop(); $(e).animate({'opacity' : 1}, 500, function(){ if (els.length) fadeInDivs(els); }) } http://jsfiddle.net/eks5L/5/ Edit: The fading out part is a bit trickier though: You could bind to the unload Event, but chances are, that your animation won't finish before the browser redirects since there is no way to prevent or defer the unload. You could also try to bind() a click handler to each <a> tag on the page, triggering the reverse fade-out animation before the redirect. It's gonna get messy, though. Rough and untested suggestion: $('a:not(".already-clicked")').live('click', function(e){ e.preventDefault(); $(this).addClass('already-clicked'); callback = function(){$('a.already-clicked').click()}; triggerFadeOutAnimation(callback); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7532380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to search people by birthday? I've found this way, is there any other simplier? ClienteAdapter cliente = Cache.CacheManager.Get<ClienteAdapter>(); DataTable dt = cliente.GetDataTable(); DateTime dta = DateTime.Today; String dia = dta.Day.ToString(); if (dta.Day < 10) dia = '0'+dia; String mes = dta.Month.ToString(); if (dta.Month < 10) mes = '0'+mes; String aniversario = String.Format("{0}-{1}", dia, mes); dt = cliente.Get(dt, String.Format("WHERE dtNascCli LIKE '%{0}%'", aniversario)); if (dt.Rows.Count>0) { String aniversariantes = "Aniversariantes do dia:\n"; for (int i = 0; i < dt.Rows.Count; i++) { aniversariantes += ((dt.Rows[i]["nmComprador"] != null) : dt.Rows[i]["nmComprador"] ? dt.Rows[i]["nmRazao"]) + "\n"; } A: LINQ could get you started. from DataRow dr in dt.Rows where ((Date)dr["birthday"]).Month = Date.Today.Month && ((Date)dr["birthday"]).Day = Date.Today.Day select dr; That yields an IEnumerable<DataRow>, which you could iterate over with a foreach. EDIT: Incorporated bemused's comment regarding previous years. A: You could simplify this: DateTime dta = DateTime.Today; String dia = dta.Day.ToString(); if (dta.Day < 10) dia = '0'+dia; String mes = dta.Month.ToString(); if (dta.Month < 10) mes = '0'+mes; String aniversario = String.Format("{0}-{1}", dia, mes); Into this: String aniversario = DateTime.UtcNow.ToString("dd'-'MM"); // You *are* storing dates in UTC aren't you? This doesn't change the fact that this isn't a good way to store or search for dates, but its a good place to start. That's all I got, besides Jim Dagg's LINQ example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is JavaScript identity compare really needed here? This is from Crockford's JavaScript: The Good Parts var is_array = function (value) { return Object.prototype.toString.apply(value) === '[object Array]'; }; Would this code have worked just as well if he had used a simple equality compare == instead of the identity compare ===? My understanding of identity is that it allows you to check if a value is really set to something specific, and not just something equivalent. For example: x == true Will evaluate to true if x is 1, or true, but x === true will only be true if x is true. Is it ever possible for the is_array function above to work with either == or ===, but not the other? A: In this particular case == and === will work identically. There would be no real difference in this case because both sides of the quality test are already strings so the extra type conversion that == could do won't come into play here. Since there's never any type conversion here, then == and === will generate the same result. In my own personal opinion, I tend to use === unless I explicitly want to allow type conversion as I think there is less likelihood of getting surprised by some result. A: You are correct. With == instead of === it should work fine. === is a strict match, and will not return true for 'falsy' or 'truthy' values (see this for more details). Which shouldn't apply in this situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to speed up this type of query? I have a table with words from a text (the table is called token), each word is a row in the table. I want to retrieve adjacent words in the result. Example: My name is Renato must return: My | name name | is is | Renato The following query works, but is slow. The textblockid determines the text that the word belongs, the sentence is the sentence count in the textblock (but at the moment the value is 1 for all) and the position attribute determines the order of the words. select w1.text,w2.text from token as w1, (select textblockid,sentence,position,text from token order by textblockid,sentence,position) as w2 where w1.textblockid = w2.textblockid and w1.sentence = w2.sentence and w1.position = w2.position - 1 Is there a better/faster way to do this? A: I don't know postgresql in detail but for sure query could be simpler in sql server: select w1.text,w2.text from token as w1, token as w2 where w1.textblockid = w2.textblockid and w1.sentence = w2.sentence and w1.position = w2.position - 1 (I think it is better to use simplest query and leave the rest for optimizer, which may be misleaded by your from subquery). However if you have index on (textblockid, sentence, position) you really can't get anything more with sql. A: Maybe an INNER JOIN with a second instance of token performs better. But it all depends on the data types of your columns, and the indexes you have in place. For example, if sentence is a text column, the comparison between w1.sentence and w2.sentence will probably be very expensive. If it's a numeric id (a foreign key to a sentences table), and if you have an index on the column, it should be way faster. Assuming this last scenario, you could try this: select w1.text,w2.text from token as w1 INNER JOIN token as w2 ON w2.sentence = w1.sentence AND w1.position = w2.position - 1 AND w1.textblockid = w2.textblockid
{ "language": "en", "url": "https://stackoverflow.com/questions/7532387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE8 inner html and tag object properties I have some kind of trouble in my code in IE8. <script type="text/javascript" src="js/jquery.js"></script> <div class="container"> <li></li> </div> <script> var $container = $('.container'); $('li', $container).get(0).my_plugin_inited = true; alert($container.html()); </script> So I put some property to object of DOM element 'li' and fetching whole html code. In normal browsers all what I will get is just <li></li>. BUT, this is IE... So now I'm getting <LI my_plugin_inited="true"></LI> and it's clearly disappointing me. What I can do, how should I save properties in DOM objects to do not crash DOM HTML code? I tried jQuery prop() but it didn't work out. A: This: $( 'li' , $container ).data( 'my_plugin_inited', true ); Read here: http://api.jquery.com/data/ Btw you could do this: $( 'li' , $container )[0].dataset.my_plugin_inited = true; but dataset is not implemented in IE. Read here: https://developer.mozilla.org/en/DOM/element.dataset
{ "language": "en", "url": "https://stackoverflow.com/questions/7532388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make an image overwrite text within another div upon hover of first div? How do I make an image overwrite text within another div upon hover of first div? ? Any help greatly appreciated. A: window.onload = function () { // ensure that we don't try to get div1 before it's loaded document.getElementById("div1").onmouseover = function () { document.getElementById("div2").innerHTML = "<p>new HTML</p>"; }; }; Depending on your case, you may wish to use the innerText property to ensure that you don't accidentally make HTML, or you can use the DOM to make new elements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: dismissing modalViewController from UITabBarController issue so in my app delegate I am trying to present a modalViewController from a UITabBarController, by doing the following: self.tabBarController = [[UITabBarController alloc] init]; LoginViewController* loginViewController = [[LoginViewController alloc] init]; loginViewController.delegate = self; [self.tabBarController presentModalViewController:loginViewController animated:NO]; [loginViewController release]; and the delegate defined in the app delegate is: - (void)userDidLogin:(LoginViewController *) loginViewController { NSLog(@"DELEGATE CALLED, DISMISSING"); [self.tabBarController dismissModalViewControllerAnimated:NO]; } Here's my LoginViewController: protocol LoginViewControllerDelegate; @interface LoginViewController : UIViewController <MBProgressHUDDelegate> { id<LoginViewControllerDelegate> delegate; } @property (assign) id<LoginViewControllerDelegate> delegate; @end @protocol LoginViewControllerDelegate - (void)userDidLogin:(LoginViewController *) loginViewController; @end The issue is that this (userDidLogin:(LoginViewController *) loginViewController) is never called... why is this? I have called the following in my LoginViewController implementation and this is called [self.delegate userDidLogin:self]; UPDATE: I got the delegate called now. The issue now is that when I call [self.tabBarController dismissModalViewControllerAnimated:YES] it doesn't dismiss the modal view controller. A: You didn't post any code from LoginViewController, but within that class's code you need to add the following lines when you are ready to dismiss it (perhaps when the user clicks the "Login" button and the login is successful). if (delegate && [delegate respondsToSelector:@selector(userDidLogin:)]) [delegate performSelector:@selector(userDidLogin:) withObject:self]; UPDATE: I think I understand what the issue is here. According to Apple's documentation, when you call presentModalViewController:animated: the method sets the value of the "modalViewController" property of UIViewController (in this case your UITabBar). However that property only maintains a weak reference to the modalViewController. That's important because you initialize the LoginViewController, pass it in to presentModalViewController:animated: and then you release it. Since presentModalViewController:animated: is not retaining a strong reference to the LoginViewController, the UITTabBar is unable to dismiss it later on. In fact I'm surprised what you have done is not resulting in an EXC_BAD_ACCESS crash. I suggest you remove the "[loginViewController release]" statement and instead release it after you call "[self.tabBarController dismissModalViewControllerAnimated:NO]"
{ "language": "en", "url": "https://stackoverflow.com/questions/7532401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lucene searches on 2 field values as single Lucene document has field a with content hello and a with content world. If i'll search "hello world"~2 it will be founded =(. How can I fix it? FastVectorHighlighter will highlight it like <b>helloworld</b> (without any space) (anyway it shouldn't highlight it) A: a seems to be an multivalued field. Have you changed the positionincrementgap to a higher value ? The default value position increment gap is 0. This will prevent the scenario.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating a mercurial webserver I have a server running mercuial 1.7.2 and want to upgrade to the newest version. What is the best way to go about deploying a new version? Do I need to recopy the templates folder and mercurial folder for python? A: Generally speaking, you can simply replace your installed Mercurial with a new version and have it work. * *old CGI and WSGI scripts are all forward-compatible and you don't need to update them *you shouldn't need to update config files *new Mercurial versions will read and write old repositories without issue The only thing you need to worry about is if you've modified the stock web templates, in which case you'll want to back them up and restore them. See this page for other notes on upgrading: https://www.mercurial-scm.org/wiki/UpgradingMercurial
{ "language": "en", "url": "https://stackoverflow.com/questions/7532405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Load only first frame of Video I was just wondering if it is possible to just load the first frame of a video in AS3, so I can use it as a screenshot/preview type of thing? Thanks in advance :) Harry. A: Load only the first frame wouldn't be possible without starting the process to load all video, then, it would take a little while to show the image and pause the video before playing. Some CDNs provide an image url, if isn't your case, you could use FFMPEG to generate your thumbs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Help with Mule Magento Connector I have been trying for a while to get working the Mule's Magento Cloud Connector. However I have had no success. I am using magento 1.6.0, mule 3.1.2, and the Mule's Magento Cloud Connector 1.2. My code and the error stack that I'm getting after trying to execute it is in here: http://forums.mulesoft.org/thread.jspa?threadID=6286 I appreciate any help you can provide me Regards Leo A: I have found my problem. The connector's documentation is not clear about which address you should use when configuring it. I was using .http://mymagentohost/. But the address that should be used was .http://mymagentohost/index.php/api/v2_soap/ or .http://mymagentohost/index.php/api/soap/ in case of using the first version of the API. Regards Leo A: I found the solution : https://sashistore.gostorego.com + /api/v2_soap?wsdl is url Username and API key will allows you to connect using Magento connector For Reference Please go through : http://www.magentocommerce.com/api/soap/introduction.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7532409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a natural way to map a hash or a XML file to a Mongo document? Is there a way to take a hash of data (or even better an XML document) could be mapped straight to a mongo document. So this hash: @hash = { "doc_id" => 3928, "header" =>[ {"merchantId"=>["35701"], "merchantName" =>["Lingerie.com"], "createdOn" =>["2011-09-23/00:33:35"]} ], "trailer" =>[ {"numberOfProducts"=>["0"]} ] } Would become: > db.doc.first() { _id : ObjectId("4e77bb3b8a3e000000004f7a"), doc_id : 3928 header : [{ merchantId : "35701", merchantName : Lingerie.com }], trailer : [{ numberOfProducts : 0 }] } A: You could convert the hash to json with to_json: require 'json' @hash.to_json gets you(with formatting): { "doc_id":3928, "header":[{ "merchantId":["35701"], "merchantName":["Lingerie.com"], "createdOn":["2011-09-23/00:33:35"] }], "trailer":[{ "numberOfProducts":["0"] }] } It should be just a short hop to bson and mongo from there. Edit: Okay, I just read the tutorial here: http://api.mongodb.org/ruby/current/file.TUTORIAL.html and it looks like you can just put the hash in there and the mongodb driver takes care of it. Maybe I don't understand the question? A: It's not clear what you're trying to do, so I'm assuming you want to import XML data into mongo. I've been importing XML files to mongo. First I convert the xml files to json objects using this command line tool I wrote, xml-to-json. Then, I use mongoimport to import the data into mongo. Check out the documentation of xml-to-json, including some example input vs. output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to integrate google plus' +1 to a Django Website? I wanted to add a +1 button on every post in my website. How do I do that? Any resources? I am also looking for Twitter's Tweet and Facebook's Like. Or Django does not handle that? A: Check out the documents for Google Plus, it looks pretty straight forward: The simplest way to include a +1 button on your page is by just including the necessary JavaScript and adding a +1 button tag: <script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script> <g:plusone></g:plusone>
{ "language": "en", "url": "https://stackoverflow.com/questions/7532422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: box-shadow - Is this possible? I need to make a shape like the one below and was trying to get it working with CSS. The closest I could get was like this. I had to push the shadow on the bottom part down or else it would overlap with the shadow on the top. Is it possible to actually make the top version with CSS? A: Working Example Here CSS .block-a { display: block; height: 200px; width: 200px; background-color: #8BC541; -moz-box-shadow: 0 0 10px #000; -webkit-box-shadow: 0 0 10px #000; box-shadow: 0 0 10px #000; -webkit-border-radius: 10px; -webkit-border-bottom-right-radius: 0; -moz-border-radius: 10px; -moz-border-radius-bottomright: 0; border-radius: 10px; border-bottom-right-radius: 0; } .block-b { color: #fff; text-align: center; line-height: 40px; position: relative; display: block; height: 40px; width: 80px; margin-left: 120px; -moz-box-shadow: 0 0 10px #000; -webkit-box-shadow: 0 0 10px#000; box-shadow: 0 0 10px #000; -webkit-border-bottom-right-radius: 10px; -webkit-border-bottom-left-radius: 10px; -moz-border-radius-bottomright: 10px; -moz-border-radius-bottomleft: 10px; border-bottom-right-radius: 10px; border-bottom-left-radius: 10px; background-color: #8BC541; } .block-b:before { position: absolute; background-color: #8BC541; height: 11px; width: 90px; top: -11px; left: -10px; display: block; content: ""; } .block-b:after { padding-left: 5px; color: #fff; content: "▲"; } HTML <div class="block-a"></div> <div class="block-b">Login</div> Image A: It's an answer pile-on! Looks like you have lots of options to work with. I'll add another to the pile: http://jsfiddle.net/XrkJq/
{ "language": "en", "url": "https://stackoverflow.com/questions/7532424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: weird problem with .val on input and .append in jquery I have this code in jquery: $(document).ready(function () { $("#main-edit").click( function() { var cursorExists = $("#cursor").length; if (!cursorExists){ $("#cursor-start").append("<input type='text' id = 'cursor' />"); $("#cursor").markCursor(); } if (cursorExists){ $("#cursor").markCursor(); } }); jQuery.fn.enterText = function(){ if( $("#cursor").val() ){ var character = $("#cursor").val(); $("#cursor").val(""); return this.append("<span>"+character+"</span>"); } }; jQuery.fn.markCursor = function(){ $(this).focus(); $(this).keydown(function() { $("#cursor-start").enterText(); }); }; }); My problem is in the enterText function. On the keydown function, I get the value of the input, store it, clear the input, and append the stored value. But when I type something like "foo"....I get "fo".....when I type "food"....I get "foo". So its not getting the last entered value for some reason. A: You are getting the value on keydown, which is before the letter is added to the value. Get the value instead on keyup. When you type "food", the last keydown event is when the value is "foo" and you press "d". If you use keyup, the last keyup will be when you release "d", and the value will be "food" A: Use keyup() instead of keydown()
{ "language": "en", "url": "https://stackoverflow.com/questions/7532427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Image Change On Button Click In Android I'm new to android and am making a simple app. I'm trying to change the image (in an imageview) on a button click. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); frown = (ImageView)findViewById(R.id.imageView1); } public void action(View view) { Toast.makeText(getApplicationContext(), buttontest, Toast.LENGTH_SHORT).show(); frown.setImageResource(R.drawable.chimpy); } "action" is being called via XML with the "android:onClick"[insert method here]" for my button The button works fine and I get my toast, but the image stays the same. A: Try changing the drawable to something standard e.g. android.R.drawable.btn_default. Does it chnage Now? I am sure you are having some issues with R.drawable.chimpy. A: You must use .png image and you can go with the following code snippet: frown.setOnClickListener(new OnClickListener(){ public void onClick(View v) { frown.setBackgroundDrawable(R.id.chimpy); } }); If it is not working, just tell me...!
{ "language": "en", "url": "https://stackoverflow.com/questions/7532429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF RIA Services / intercept or subscribe to a RaiseDataMemberChanging So I'm new to the concept of routed events, but I know that messages are flying everywhere when fields are changing via the RaiseDataMemberChanging / RaiseDataMemberChanged messages. The quick question is how to I "listen" for those routed messages? I would like my view model, in a MVVM correct matter, intercept a message that a field is being updated, deep down in the heirarchy of tables. If a change occurs in a child (a date range), that date range change has some business logic associated with it that works from top down. I've know that I can use partial methods to inject code during the changing and changed events, but the design (one to one relationship) means that a change to the child, in the context of the child, has no reference the parent (Parent has a one to one reference to child, but child has no reference to parent). Yes I can add the reference from the child to the parent (making the parent have both a one to one, as well as a one to many relationship), but during creation of the entity, this creates a problem - parent has to exist before the child entity exists, and the child entity has to exist before a reference to the parent can exist. This design requires an insert of the parent, and child, then an update of the child - which confuses WCF RIA Services during the inital creation process. Sorry for the long winded explaination, but I'll even consider design changes if this all makes sense to anyone that cares to comment. Any input would be appreciated. A: I'm using a subscription to the PropertyChanged events of the Entity in question. It seems like a lot of work to filter out all the events for a couple of fields. Using RX, I'm hoping that the resources used are minimal, and the weak reference avoids the memory link issue when a strong reference is used to deal with events: Observable.FromEventPattern<PropertyChangedEventArgs>(this.FlowEntity, "PropertyChanged") .Where(pPropertyChanged => ( pPropertyChanged.EventArgs.PropertyName.EndsWith("Date")) || pPropertyChanged.EventArgs.PropertyName == "Capacity" ) .Subscribe(pObserver => this.RaiseFlowEntityDateChanged(this, pObserver.EventArgs)); FlowEntity is the child entity that I'm monitoring from the parent. I then raise custom event using the parent entity, rather than the entity that actually holds the event. I can't raise this event from the partial methods, as the child entity would not have the context of the parent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I use my web reference in Visual Studio 2008 I've got a sample project that has several web services and uses them during run time. The application works as intended. The web references are can be see in the Solution Explorer under a folder called "Web References" with the list of web services as single files. I'm trying to use these same Web Services in another solution but it's not working. I've added the Web Services to the solution and they have appeared under a folder called "Web_References". In addition, the list of web services under this appear with the extension .discomap and have 2 subfiles under them with the same name but with the extension .disco and .wsdl. These are the only differences I can see. However, in the 2nd solution, Visual Studio cannot resolve the references to the classes from the web services (I'm using the same code as the first solution). Does anyone know why the web references appear differently and why my 2nd solution is not allow me to use the web references that I've added? TIA Update: Following on from the comments, yes the 2nd one is a web site and the first appears to be a Windows Application using web services. Given it's a website, how do I use the web references?
{ "language": "en", "url": "https://stackoverflow.com/questions/7532434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java generics problem with Map I have this which should not compile. public boolean foo(final Map<String, String> map) { map.get(1); // No error here? } A: As of Java 6 the line you have written is exactly equivalent to: public boolean foo(final Map<String, String> map) { map.get(Integer.valueOf(1)); // compiles fine of course! } Which they call "autoboxing". On the flipside there "autounboxing", ie: public int bar(final Map<String, Integer> map) { return map.get("bar"); } This line is equivalent to: return map.get("bar").intValue(); which sometimes leads to a rather mysterious looking NullPointerException when the requested key is not found in the map. This is a common trap for programmers new to this concept. Hope that helps. A: I have this which should not compile. Why not? The definition of .get() says that it finds the key such that the given object is equal to the key. Yes, in this case we know that the object is an Integer, and Integer's .equals() method always returns false for a String object. But in general for two objects of different classes we do not know that. In fact, there are cases in the Java library where objects of different classes are required to be equal; for example, java.util.List requires lists to be equal if their contents are equal and in the same order, regardless of class. A: The get method takes an Object, so the 1 gets autoboxed to an Integer and it compiles just fine. You'll always get null back as a response though. This is done for backwards compatability. // Ideal Map: public V get(K key) { // impl here } // what we have public V get(Object key) { // impl here } Example for scorpian import java.util.*; class ScorpMain { /* This interface just has a single method on it returning an int */ static interface SomeInterface { int foo(); } /** * ExampleKey has an int and a string. It considers itself to be equal to * another object if that object implements SomeInterface and the two have * equal foo values. It believes this is sufficient, as its sole purpose is * to calculate this foo value. */ static class ExampleKey implements SomeInterface { int i; String s; ExampleKey(int i, String s) { this.i = i; this.s = s; } public int foo() { return i * s.length(); } public int hashCode() { return i ^ s.hashCode(); } // notice - equals takes Object, not ExampleKey public boolean equals(Object o) { if(o instanceof SomeInterface) { SomeInterface so = (SomeInterface)o; System.out.println(so.foo() + " " + foo()); return so.foo() == foo(); } return false; } } /** * The ImposterKey stores it's foo and hash value. It has no calculation * involved. Note that its only relation to ExampleKey is that they happen * to have SomeInterface. */ static class ImposterKey implements SomeInterface { int foo; int hash; ImposterKey(int foo, int hash) { this.foo = foo; this.hash = hash; } public int foo() { return foo; } public boolean equals(Object o) { SomeInterface so = (SomeInterface)o; return so.foo() == foo(); } public int hashCode() { return hash; } } /** * In our main method, we make a map. We put a key into the map. We get the * data from the map to prove we can get it out. Then we make an imposter, * and get the data based on that. * The moral of the story is, Map.get isn't sacred: if you can trick it * into thinking that the object inside is equal to the object you give it * in both equality and hash, it will give you the resulting object. It * doesn't have anything to do with the type except that a given type is * unlikely to be equal to another object that isn't of the given type. * This may seem like a contrived example, and it is, but it is something * to be conscious of when dealing with maps. It's entirely possible you * could get the same data and not realize what you're trying to do. Note * you cannot ADD the imposter, because that IS checked at compile time. */ public static void main(String[] args) { Map<ExampleKey,String> map = new HashMap<ExampleKey,String>(); ExampleKey key = new ExampleKey(1337,"Hi"); map.put(key,"Awesome!"); String get = map.get(key); System.out.println(get); // we got awesome ImposterKey imposter = new ImposterKey(2674,3096); // make an imposter String fake = map.get(imposter); System.out.println(fake); // we got awesome again! } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7532435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Apache unable to access local DNS ip address I just set up a server in my house using private IP. I can access my server using my domain from outside network/ outside from my house. But I cannot access it from local network using my domain or my private IP address. What can be the problem for this? is it the Apache settings? (I can access it if I edit the /etc/hosts file) A: If you can access it when you put in an entry in /etc/hosts, then likely it is DNS related. I am assuming you are putting in the public (external IP) and not an internal IP for testing. If you have recently updated your DNS, then likely your local router (or ISP's DNS server) will still have the old IP cached or the fact that there is no DNS record setup cached. You could reboot your router to try and clear the cached entry, but it could well be cached at the ISP and you can only wait until it updates there (usually somewhere under 24 hours, often just a few hours). However, you could configure your computer to use a different DNS server for a while - eg. 8.8.8.8 or 4.4.4.4 which are both run by Google. A: Did you use the internal or external IP in your hosts file to get it working? If it was external IP it's probably the DNS issue. If it was the internal IP, the issue could be in the routers NAT. Some routers/setups will only apply their NAT rules on packets traversing the external internet facing interface. ____________ | | Server ---IntIf-|IntIP--ExtIP|-ExtIf--- Internet |____________| This is a bit simplified but basically when you access the external IP from the internal network the packet, following the dotted line, reaches the routers external IP before a NAT rule can be applied on ExtIf and then the router can't find anything listening so rejects/drops the connection. To confirm if it is the DNS problem. Run an nslookup $domain from both your local and external boxes and see if they return the same IP address. If the IP's are the same and it's still not working you will need to take a closer look at the router, hopefully that's possible. If not you may need an internal DNS server that can respond with the internal IP addresses for any domains it knows about then forward any other requests externally. The NAT issue is called NAT Loopback, Hairpinning or Reflection. See here for a linux solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I make a jquery styleBox trigger when focused using tab? I have some styleBox elements that aren't triggering when I tab through the items. Does the change() also get triggered on focus? A: From the jQuery documentation for .change(): For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus. See here for details. May be better to use .focus() if you can.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: maven basic project templates i generally needs that kind of project.But most maven archetypes generating extra files,jars ... .How can i create simple template of that kind of projects . 1-jsf2 + JPA 2-jsf1.2 +JPA 3-spring +jsf2+JPA A: This is a simple example by line command: mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false fore more info: https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7532442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to specify what value is passed using a choice form field in Symfony2 I have the following code which displays all the available main pages that can be used when adding sub pages in my project: $builder->add('subtocontentid', 'entity', array( 'class'=>'Shout\AdminBundle\Entity\Content', 'property'=>'title', 'query_builder' => function (EntityRepository $repository) { return $repository->createQueryBuilder('s') ->where('s.mainpage = ?1') ->setParameter(1, '1') ->add('orderBy', 's.created ASC'); } )); In the form, it works alright. It displays the proper title of the mainpage. However, when the form is passed to the database, the page ID is passed to the database. This isn't how I want it to work, I need it to pass on a slug to the database instead. I understand that the code I'm using retrieves all of the fields in the database. How could I select just the Title field and the Slug field, and then in the form pass the Slug field to the database? Cheers A: You will have to change the Transformer used by EntityType, And it isnt the id being passed to the database it is the entity as the Transformer takes the id and looks up the entity in its list. So in your case it would be an instance of Shout\AdminBundle\Entity\Content
{ "language": "en", "url": "https://stackoverflow.com/questions/7532451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: As a user, I want a status bar (or similar) to notify me that a job is working when using a Wx.Python gui app Can someone recommend a straight forward way of adding some type of graphical notification (status bar, spinning clocks, etc...) to my wx.Python gui application? Currently, it searches logs on a server for unique strings, and often times takes upwards to 3-4 minutes to complete. However, it would be convenient to have some type of display letting a user know that the status of the job towards finishing/completion. If I added a feature like this, I'm not sure, but I'm afraid I may have to look at using threads ... and I'm a complete newbie to Python? Any help and direction will be appreciated. A: Yes, you'd need to use threads or queues or something similar. Fortunately, there are some excellent examples here: http://wiki.wxpython.org/LongRunningTasks and this tutorial I wrote is pretty straight-forward too: http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/ Using threads isn't that hard. Basically you put the long running part in the thread and every so often, you send a status update to your GUI using a thread-safe method, like wx.PostEvent or wx.CallAfter. Then you can update your statusbar or a progress bar or whatever you're using.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing a parameter to an Index view Pretty basic question here. How come I get a 404 error when I try to view /Vendors/123 But I can see the page if I go to /Vendors/Index/123 Is there any way for me to make it work the first way? I'm just using the default routes being registered in Global.asax. A: Because that's how the default route is defined. If you don't want to specify an actionname you could modify it like this: routes.MapRoute( "Default", "{controller}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); This being said you probably shouldn't be doing this because now in your route you do not have the possibility to specify the action name that you wish to invoke on a given controller which means that you can only have a single action on each controller and that action would be Index. On the other hand if you wanted to do this on some specific controller you could still preserve the default route and add another one: routes.MapRoute( "Vendors", "vendors/{id}", new { controller = "Vendors", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); A: Because in your basic routing {id} expects after action name, but you are trying to put it after controller name. routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); Change your rout to accept {id} just after {controller}. Just like @Darin described.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to redirect python's subprocess.Call methods output to a file and not console? I am using python's Call method in subprocess module to execute a sqlldr command from subprocess import call retcode = call([self.COMMAND, self.CONNECTION_STRING, "control=" +self.CONTROL_FILE, "log="+self.TEMP_LOG_FILE, self.MODE , "data="+loadfile]) When i run the above script the output of the sqlldr command gets printed to the console which i wan to redirect to a file or ignore it. since sqlldr also writes to the log specified. i tried something like this, to redirect the output to a file, but throwing error at this line retcode = call([self.COMMAND, self.CONNECTION_STRING, "control=" +self.CONTROL_FILE, "log="+self.TEMP_LOG_FILE, self.MODE , "data="+loadfile, "> discard.log"]) how to achieve this? A: Open a file for writing and pass that as the stdout keyword argument of subprocess.call: with open('stdout.txt', 'wb') as out: subprocess.call(['ls', '-l'], stdout=out) (subprocess.call accepts the same arguments as the subprocess.Popen constructor.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7532455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring Dependency not working with Webservices I have exposed a service in application as Webservice, but it is not getting handal to a Dao which is injected through Dao, any one has any idaa? Stack Sep 23, 2011 6:48:58 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container java.lang.NullPointerException at com.scor.omega2.reference.services.impl.CurrencyServiceImpl.getCurrency(CurrencyServiceImpl.java:33) at com.scor.omega2.reference.services.impl.CurrencyServiceImpl.getCurrency(CurrencyServiceImpl.java:41) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60) at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185) Code @Path("/currency") @Named("currencyService") @Scope(BeanDefinition.SCOPE_SINGLETON) public class CurrencyServiceImpl implements CurrencyService { @Inject private CurrencyDao currencyDao; /** * Service to get Currency Code Value * * @param cur_cf * @param lag_cf * @return entity. */ public BrefTcurl getCurrency(String cur_cf, char lag_cf) { return currencyDao.getCurrency(cur_cf, lag_cf); } @GET @Produces( { MediaType.APPLICATION_XML}) @Path("{cur_cf}/{lag_cf}") public BrefTcurl getCurrency(@PathParam("cur_cf") String cur_cf, @PathParam("lag_cf") String lag_cf) { System.out.println("cur_cf "+cur_cf +" lag_cf "+lag_cf); return getCurrency(cur_cf,lag_cf.charAt(0)); } } Currency Dao Class @Named("currencyDao") @Scope(BeanDefinition.SCOPE_SINGLETON) public class CurrencyDaoImpl implements CurrencyDao { @PersistenceContext private EntityManager entityManager; /** * Service to get Currency Code Value * * @param cur_cf * @param lag_cf * @return entity. */ public BrefTcurl getCurrency(String cur_cf, char lag_cf) { return entityManager.find(BrefTcurl.class, new BrefTcurlId(lag_cf, cur_cf)); } } A: I think the servlet you have configured in web.xml is the wrong one. You need to use the one that is aware of spring and delegates to spring managed beans for processing the request. com.sun.jersey.spi.spring.container.servlet.SpringServlet
{ "language": "en", "url": "https://stackoverflow.com/questions/7532457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to save a .png image from AndroidPlot I have written a code which plots a Line Graph. This graph is plotted by using Android Plot.. How can i save this graph as .png image?? A: xyPlot.setDrawingCacheEnabled(true); int width = xyPlot.getWidth(); int height = xyPlot.getHeight(); xyPlot.measure(width, height); Bitmap bmp = Bitmap.createBitmap(xyPlot.getDrawingCache()); xyPlot.setDrawingCacheEnabled(false); FileOutputStream fos = new FileOutputStream(fullFileName, true); bmp.compress(CompressFormat.JPEG, 100, fos); A: You can get the drawing cache of any View as a bitmap with: Bitmap bitmap = view.getDrawingCache(); Then you can simply save the bitmap to a file with: FileOutputStream fos = c.openFileOutput(filename, Context.MODE_PRIVATE); bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.close(); This example will save the bitmap to the local storage which is only accessible by your app. For more information about saving files check out the docs: http://developer.android.com/guide/topics/data/data-storage.html A: Before call method Bitmap bitmap = view.getDrawingCache(); you have to call the method view.setDrawingCacheEnabled(true). Anyway it doesn't work on all Views, if your View extends SurfaceView the bitmap returned will be a black image. In that cases you have to use the method draw of your view (link to another post). P.S.: slayton if I could write comments I would comment your post but I haven't got enought reputation A: I found a solution in png format: plot = (XYPlot) findViewById(R.id.pot); plot.layout(0, 0, 400, 200); XYSeries series = new SimpleXYSeries(Arrays.asList(array1),Arrays.asList(array2),"series"); LineAndPointFormatter seriesFormat = new LineAndPointFormatter(); seriesFormat.setPointLabelFormatter(new PointLabelFormatter()); plot.addSeries(series, seriesFormat); plot.setDrawingCacheEnabled(true); FileOutputStream fos = new FileOutputStream("/sdcard/DCIM/img.png", true); plot.getDrawingCache().compress(CompressFormat.PNG, 100, fos); fos.close(); plot.setDrawingCacheEnabled(false);
{ "language": "en", "url": "https://stackoverflow.com/questions/7532458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to display data on a scroll in a Report Services report I am building a recipe book report (SQL Server Reporting Services 2008 R2) for client and they want the ingredients to look like they are on a scroll. But the scroll needs to adjust in length as different recipes have more or less ingredients. The "ingredient scroll" will just be a part of the recipe book report (sitting in the top right corner). The rest of the page will have other lists and photographs of the steps. If this is not possible, then I'm looking something that will create the same effect and look impressive. Any ideas? A: This might take some graphics editing.... Take a scroll image and cut off the top part. Put that graphic as the heading on the page. Then put the bottom part of the image as a footer. Then for the body background, use an image that looks like the middle of the page. So, the top scroll image and bottom scroll image become heading & footing and the body will dynamically expand based on how much data you have.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I set visiblity of GridColumn based off value of another GridColumn in the XtraGridControl designer? I can't seem to find an answer to this question that exists already. My problem is that I have information on an Employee being displayed in a XtraGridControl with the view set to CardView. In my Employee class I have a Terminated bool property that tells if the employee has been terminated or not. I also have a TerminationDate property that is only valid if the Employee has been Terminated (employee.Terminated == true). My question is: Is there a way to make the "Termination Date" column hidden if the value of the "Terminated" column is false in the XtraGridControl via the Designer, or do I need to code that? If I do need to code that, some advice on where to look would be helpful. I'm new to DevExpress. I'm using version 10.2 of the DevExpress controls, VisualStudio 2010 as my IDE, for the purpose of the program I'm not using a Database as the DataSource I'm using a generic List. Thanks in advance. Edit: I should note that I want to do this for an individual card, not disable the Column for all rows. A: I managed to get this to work but not by using anything that the GridControl or the View helped with. Just to close the question with an answer. I made the DateTime that holds the termination date a nullable DateTime (DateTime?) and then turned on the option in the View to hide columns with null values which hides the Termination Date, this results in the look that I was attempting to achieve.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JasperReport and text fields Good day boys and girls; I wanted to know if possible, pass a text field iReport with another textfield containing. I'm trying but not working. When print the second field as a text and not interpreted as such E.G. "\"Name of the pet is :\" + $F{pet}.getName()" A: I'm not sure what you're trying to do with the slashes, but perhaps this is what you are looking for? "Name of the pet is :" + $F{pet}
{ "language": "en", "url": "https://stackoverflow.com/questions/7532480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send mail using PHP as fast as possible for mobile device api? I'm trying to implement a fast way to send mails from a php script which is a mobile API for mobile devices which access the API via GPRS, Edge or 3G. It should be as fast as possible so that the user doesn't have to wait to long for the http response. I figured, I implement a separate daemon which sends then the email using a separate SMTP Server. The PHP script opens a unix domain socket to that daemon and transfers the necessary info like from, to, subject and body. What do you thing about that approach? Is there a faster way to go? A: Your idea would (or something like it) would work, but it precludes the possibility of providing feedback if there's a problem sending the email. But if you're OK with that... Writing the conversation with the SMTP server from scratch might be harder than you think (I've done it). Using existing solutions (and there are many for sending mail from PHP, including the built-in one) would probably not be that much slower. And if you're doing it in a different thread, it's not as important that it be as fast as possible. You can either queue them up and run them sequentially from one thread, or fork a new thread for each one to send.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Solr to store data for retrieval Vs. MySQL I'm building a system where I use Solr for search over my content, and MySQL to store the content. The rationale is that MySQL is a good persistent storage solution, and I can join data with other tables and have more versatile queries. On the other hand, I'm looking for very high performance in my reads. Would it be better to use Solr to both search and store the data, and retrieve the data items directly from Solr, rather than getting an index from Solr and then performing a Select on MySQL? I would still technically need to goto MySQL to grab related data, but perhaps I could store that in Solr as well. More to the point - is Solr a reasonable data storage solution in this context? (Would still store in MySQL for persistence in either case). A: It depends on what you need from the results. You can certainly store documents in Solr with extra fields, and I believe you can declare some fields as part of the document, but not part of the index. Depending on what you need from a search result, you may be able to get all you need frm the extra fields to satisfy the search. If that is the case, you can skip the secondary lookup to MySQL. Also consider how current you need the data to be. Is it sufficient to fetch data from the Solr index, given that it may not be in sync with the latest changes from MySQL? Or do you need to fetch from MySQL to ensure you have the latest data?
{ "language": "en", "url": "https://stackoverflow.com/questions/7532488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a good SimpleSAMLphp SLO example? One of our clients is requesting that we implement Single Logout (SLO) through SAML. Their side of the SAML service is the Identity Provider, while ours is the Service Provider. Single-Signon (SSO) works by validating the user's credentials with the client's IdP, then redirecting the user to a login page on yet another platform, with a token that lets them log straight in. That platform knows absolutely nothing about SAML, and in particular doesn't share the SimpleSAMLphp session state. Logout needs to happen two ways, though: * *If the user hits the logout button on our platform, need to log them out of our site, and hit the IdP's SLO service. *If the user hits the logout button on the client's side, or on another service provider's side, the client IdP will hit our SP's SLO service, which then needs to log them out of our real platform before redirecting the user back to the SP's logout response page. I'm able to convince our platform to redirect the user to an arbitrary page on logout, so I think the first part can be achieved by a page that uses SimpleSAML_Auth_Simple::getLogoutURL(). Such a page might also work when hit from the IdP side, but the SAML specs are complicated enough that I can't be sure until we try it. However, the SP configuration in config/authsources.php doesn't accept a SingleLogoutService parameter; the metadata as produced by /www/module.php/saml/sp/metadata.php/entityid still lists /www/module.php/saml/sp/saml2-logout.php/entityid as the SingleLogoutService location. If that page is necessary for clearing the SimpleSAMLphp session, that's fine, but I need to know how to slip in the extra redirects required for logging the user out of our platform. I've tried searching for examples, but all I get is API references. It would also be nice to know how I can test logout without attempting to set up my own IdP; is there a service like the openidp.feide.no that handles SLO as well as SSO? A: SLO Issue Imagine this scheme: Plattform -- SP1 ----- IdP ----- SP2----- App Plattform and Apps are connected with simpleSAMLphp SP, that also forms a federation with a IdP. You must find the normal log out function of Platffom, app1 and app2 and rewrite it: normal_app_logout() { // code of the normal logout .... .... // new code require_once('<path-to-ssp>/simplesamlphp/lib/_autoload.php'); //load the _autoload.php $auth = new SimpleSAML_Auth_Simple('default-sp'); // or the auth source you using at your SP $auth->logout(); <--- call to the SLO } This will end local session, the SP session connected to this application, the IdP session and the SP sessions of the SPs connected to the IdP but... what happen to the others apps session? They will still be active. You thought about an active call to end it but I think is better if you also override the "is_logged_in()" function that many app implement. You must override this function and only return true if exists also a valid SP session active using the function $auth->isAuthenticated() Recently I implemented this functionality on the Wordpess SAML plugin, check the code IdP Issue Use Onelogin free trial , you can register your SP there and use its IdP. Follow this guide to configure your SAML connectors But I think that you better may try to build a IdP by yourself. There is a nice documentation and the steps are easy. Use "example-userpass" authsource if you dont want to waste time configuring a database/ldap. Also you can set your actual simplesamlphp instance as SP & IdP but i think that if you are learning simplesamlphp better dont mix. A: public function logout() { $timeNotOnOrAfter = new \DateTime(); $timeNow = new \DateTime(); $timeNotOnOrAfter->add(new DateInterval('PT' . 2 . 'M')); $context = new \LightSaml\Model\Context\SerializationContext(); $request = new \LightSaml\Model\Protocol\LogoutRequest(); $request ->setID(\LightSaml\Helper::generateID()) ->setIssueInstant($timeNow) ->setDestination($this->_helper->getSloServiceUrl()) ->setNotOnOrAfter($timeNotOnOrAfter) ->setIssuer(new \LightSaml\Model\Assertion\Issuer($this->_helper->getSpEntityId())); $certificate = \LightSaml\Credential\X509Certificate::fromFile($this->_helper->getSpCertFile()); $privateKey = \LightSaml\Credential\KeyHelper::createPrivateKey($this->_helper->getSpPemFile(), '', true); $request->setSignature(new \LightSaml\Model\XmlDSig\SignatureWriter($certificate, $privateKey)); $serializationContext = new \LightSaml\Model\Context\SerializationContext(); $request->serialize($serializationContext->getDocument(), $serializationContext); $serializationContext->getDocument()->formatOutput = true; $xml = $serializationContext->getDocument()->saveXML(); Mage::log($xml); $bindingFactory = new \LightSaml\Binding\BindingFactory(); $redirectBinding = $bindingFactory->create(\LightSaml\SamlConstants::BINDING_SAML2_HTTP_REDIRECT); $messageContext = new \LightSaml\Context\Profile\MessageContext(); $messageContext->setMessage($request); return $redirectBinding->send($messageContext); } Finally do: $httpResponse = $this->logout(); $this->_redirectUrl($httpResponse->getTargetUrl());
{ "language": "en", "url": "https://stackoverflow.com/questions/7532490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: htaccess redirect to mobile website. Keep the same trailing path I have my website automtically redirecting to a mobile version if the user has an iphone or ipod with .htaccess. But I would like to keep the same link structure. For example: http://www.domain.com/status/?variable=12345678 Currently redirects to: http://iphone.domain.com/ The end of the link is lost. So in the end I would like it to keep the end of the url and go to http://iphone.domain.com/status/?variable=12345678 A: Something along the lines of RewriteCond %{HTTP_HOST} ^www.domain.com RewriteRule ^(.*)$ http://iphone.domain.com/$1 should work. The $1 is the key. This will take http://www.domain.com/your-exact-path and change it to http://iphone.domain.com/your-exact-path You will of course still need to determine whether the user is accessing from a phone before using this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: unable to add a cookie included in JSP via jsp:include Cookies are not getting added to the browser when the code adding the cookie is part of a fragment of JSP (includes.jsp) included in the primary page (main.jsp) via JSP:INCLUDE. The code works fine when it is part of the primary page (main.jsp). However, I need to add the cookie via the fragment since that fragment is used in dozens of pages where I want the cookie to get added. Note: The jsp:include is part of the header section of main.jsp (the fragment also adds a number of javascript and css references) Here is the snippet: Cookie cookie = new Cookie ("test","test cookie"); cookie.setMaxAge(365 * 24 * 60 * 60); cookie.setPath("/"); response.addCookie(cookie2); The above works fine when it is part of the main.jsp but doesn't work when it is part of the fragment added to main.jsp via . it is almost as if the response object is being reset after the fragment is rendered. A: The <jsp:include> uses under the covers RequestDispatcher#include() and its docs say: ... The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored. ... (emphasis mine) Cookies are to be set in the response header. So it stops here. Consider the compile time variant <%@include%>, it get literally inlined in the main JSP's source. A: Source code: request.setAttribute(“res”, response); <jsp:include page=“url” /> Target code: HttpServletResponse res = (HttpServletResponse)request.getAttribute(“res”); //cookie create Cookie cookie = new Cookie(“test”, “test”); res.addCookie(cookie);
{ "language": "en", "url": "https://stackoverflow.com/questions/7532494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: facebook - user changes password and invalidates the access token Is any way to keep alive facebook access token also when user changes his password? Even with offline_access ? A: Here's a how-to guide for handling this case: https://developers.facebook.com/blog/post/500/ You should probably check the full Authentication document too A: No, this is put in place to protect users in the event their account gets hacked or an app starts spamming. They will need to re-authenticate with your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do i select a value from a column, based on a selection criteria on another column? How to select a value/name from a column, based on frequency(no. of repetitions) of a value in another column..in R? This is what my sample data is..: Col1 col2 Col3 Col4 Yuva 123 qwe XXYY Arun 234 asd XYXY Yuva 870 ghj XXYX Naan 890 qwe XYYX Shan 231 asd YXYX Yuva 453 qwe YYXY Naan 314 ghj YXYY Yuva 908 bnm YYYx Now i would like to know the function/statement which gives me pair of value from col1 and Col3 based on the number of times the value in col3 has occurred. i.e., what is the corresponding value in col1, when 'qwe' has occurred once(/twice/thrice). the expected(required) answer is: Upon giving I should get --------------------------- qwe =1 Naan qwe =2 Yuva qwe=3 ------(not available). similarly asd=1 Arun Shan ghj=1 Yuva Naan ghj = 2 -----(not available) and for bnm=1 Yuva. Please help me guys. A: The xtabs function returns a contingency table which supports matrix indexing: getCombs <- function(nam , cnt) names( which(xtabs( ~Col1+Col3, data=dat)[ ,nam] == cnt) ) > getCombs("ghj", 1) [1] "Naan" "Yuva" > getCombs("ghj", 3) character(0) If you need to have "not available" as the value, then just test the result for length()==0 and return that string if so. A: Maybe something like this: x <- read.table(textConnection("Col1\tcol2\tCol3\tCol4\nYuva\t123\tqwe\tXXYY\nArun\t234\tasd\tXYXY\nYuva\t870\tghj\tXXYX\nNaan\t890\tqwe\tXYYX\nShan\t231\tasd\tYXYX\nYuva\t453\tqwe\tYYXY\nNaan\t314\tghj\tYXYY\nYuva\t908\tbnm\tYYYx\n"), header=TRUE, sep="\t", stringsAsFactors=FALSE) selCol1 <- function(x, valCol3, occur) { s <- subset(x, Col3==valCol3) f <- as.factor(s$Col1) t <- table(f) idx <- which(t==occur) if(length(idx)==0) return(NA) else return(levels(f)[idx]) } selCol1(x,"qwe",1) selCol1(x,"qwe",2) selCol1(x,"qwe",3) selCol1(x,"ghj",1) selCol1(x,"ghj",2) selCol1(x,"bnm",1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7532497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LINQ to Entities Include() does not work The following LINQ to Entities query (using EF 4.1 Code-First), is supposed to create a list of viewmodels based on Campaigns and Users. I have eager-loaded Category property of each campaign so that each campaign should have its Category reference property filled with appropriate data. But it seems like this eager-loading is lost somewhere, thus I cannot access categories like: campViewModels[0].Campaign.Category. It's always null. var campViewModels = ctx.Campaigns .Include(c => c.Category) .Where(c => c.Title.Contains(searchText)).Join( ctx.Users, c => c.CampaignId, u => u.CampaignId, (c, u) => new {c, u}) .GroupBy(cu => cu.c) .Select(g => new CampaignViewModel { Campaign = g.Key, MemberCount=g.Count()}) .OrderByDescending(vm => vm.MemberCount) .Skip(pageIndex) .Take(pageSize) .ToList(); For workaround this problem, I have changed my viewmodel definition and to have CategoryText property and filled it in my query: Select(g => new CampaignViewModel { Campaign = g.Key, MemberCount=g.Count(), CategoryText = g.Key.Category.Title}) But I'm curious to find out what prevented the explicit loading of categories? A: Include is ignored when you project to a new type, use a join, or a group by
{ "language": "en", "url": "https://stackoverflow.com/questions/7532498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Inheriting methods with contexts in an activity I have a base class which has a bunch of buttons that are going to be used on all my activities as a general navigation bar. public abstract class GenericActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_menu); final Button buttonFinder = (Button) findViewById(R.id.buttonNavigationFinder); buttonFinder.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent IndexActivity = new Intent(GenericActivity.this, Finder.class); GenericActivity.this.startActivity(IndexActivity); } }); final Button buttonIndex = (Button) findViewById(R.id.buttonNavigationIndex); buttonIndex.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent IndexActivity = new Intent(GenericActivity.this, Index.class); GenericActivity.this.startActivity(IndexActivity); } }); final Button buttonStart = (Button) findViewById(R.id.buttonNavigationStart); buttonStart.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent IndexActivity = new Intent(GenericActivity.this, MainMenu.class); GenericActivity.this.startActivity(IndexActivity); } }); } } I then inherit this activity in another activity public class Index extends GenericActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.index); } } The XML file of the index layout have buttons with the same IDs as the base class. When I start the Index activity my emulator crashes. Help! EDIT: Stacktrace, but I cant seem to get the whole trace. Logcat shows "... 11 more" at the end http://pastebin.com/v64RyG2S A: Try this: remove setContentView(R.layout.main_menu); from GenericActivity. What main_menu.xml has? and change these methods calls order on Index class: @Override public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.index); super.onCreate(savedInstanceState); } A: Ok, I suppose you want to show the same menu (main_menu.xml) on all your view. Correct?. Your all calling setContentView 2 times on the same activity... so in the best case the second layout overwrite the first. So, I have an idea: You could Override the method setContentView of GenericActivity and write something like that: Firstly, you have to reserve a space for Index activity View in your main_menu layout, for example: .... <LinearLayout android:id="@+id/childActivity" ...></LinearLayout> <Button android:id="@+id/buttonNavigationFinder" ...></Button> <Button android:id="@+id/buttonNavigationIndex" ...></Button> <Button android:id="@+id/buttonNavigationStart" ...></Button> .... Then you have to delete your onCreate or do that: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } And finally: public void setContentView(int resource){ super.setContentView(R.layout.main_menu); // ---> Attention it's main_menu <--- final Button buttonFinder = (Button) findViewById(R.id.buttonNavigationFinder); buttonFinder.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent IndexActivity = new Intent(GenericActivity.this, Finder.class); GenericActivity.this.startActivity(IndexActivity); } }); final Button buttonIndex = (Button) findViewById(R.id.buttonNavigationIndex); buttonIndex.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent IndexActivity = new Intent(GenericActivity.this, Index.class); GenericActivity.this.startActivity(IndexActivity); } }); final Button buttonStart = (Button) findViewById(R.id.buttonNavigationStart); buttonStart.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent IndexActivity = new Intent(GenericActivity.this, MainMenu.class); GenericActivity.this.startActivity(IndexActivity); } }); //And now you have to fill the space for the child Activity with Index (or others) Activity view LinearLayout childActivity = (LinearLayout) generalView.findViewById(R.id.childActivity); View activityView = View.inflate(this,resource,null); //--> Now it's resource <-- childActivity.add(activityView); } It's an idea, I hope it's help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Colon separated values in database I have database results in the following format: s:6:hobbit the s is "string" and the value is the count of characters in the third section. What is this called? Colon separated values? Is the only way to deal with it, in PHP, through regex? Specifically, I'm trying to get the value hobbit. But obviously when I access the db to get anything I get the whole value s:6:hobbit. Am I doomed to using regex to work with results like this? A: Looks like the output from serialize(). (Hint: unserialize()*) Alternatively, you can explode() on : with limit=3. This is important as the string itself (everything from the second : forward) may contain colons. Also, why are these values in the DB in the first place? *) EDIT It seems that serialize() would have encoded the string as s:6:"hobbit" (quoted) so the explode() could prove to be the way to do this. A: list($tmp, $tmp, $string) = explode(':', $dbString); echo $string; Demo: http://codepad.org/z91CztFm
{ "language": "en", "url": "https://stackoverflow.com/questions/7532500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails Mongrel server won't load anything anymore For a long time, I've been using Mongrel to run my rails app. Unfortunately, yesterday, it decided to stop working. Here's what happens when I try to start up localhost to see my app: root@whatever> RAILS_ENV=production script/server This has always started the Mongrel server, listening to port 3000. I access it by going to localhost:3000. Rails 2.3.5 application starting on http://0.0.0.0:3000 no page on localhost:3000 will load. It just says "loading..." forever. The strange part is that it will successfully load about two pages before it decides to never load anything again. If I restart my computer, it may or may not let me load a page or two, but it always just stops loading anything shortly thereafter. Might the server just be incredibly slow, and I only think that it won't load anything? Even still, how would I ascertain that and then fix it? Naturally, this has made it practically impossible for me to get anything done! Any help is appreciated. If it matters, I am running Rails 2.3.5, Ruby 1.8.7, Mongrel 1.1.5, on Ubuntu 10.04 LTS. A: I figured it out. In case anyone was ultra-curious, it had nothing to do with either Rails or Mongrel. The user account I was trying to log into had some random SQL query associated with it that was really huge. I don't know why it was there, but trying to log into a certain account was killing everything. The reason it would occasionally load pages was because that was when I would log in with a different account. Moral of the story: don't have massive SQL queries associated with random test accounts!
{ "language": "en", "url": "https://stackoverflow.com/questions/7532502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# - Finding all permutations of the letters in a string with some letters repeated I am having problems calculating permutations for strings containing multiple instances of a letter (e.g. "HRWSOROE" where 'O' and 'R' are in the string twice. The algorithm I am using public static class Extensions { public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source) { if (source == null) throw new ArgumentNullException("source"); return PermutationsImpl(source, Enumerable.Empty<T>()); } private static IEnumerable<IEnumerable<T>> PermutationsImpl<T>(IEnumerable<T> source, IEnumerable<T> prefix) { if (!source.Any()) yield return prefix; foreach (var permutation in source.SelectMany(x => PermutationsImpl(source.Except(Yield(x)), prefix.Union(Yield(x))))) yield return permutation; } private static IEnumerable<T> Yield<T>(this T element) { yield return element; } } Seems to work, but ignores duplicate letters - so instead of calculating permutations on "HRWSOROE" the permutations are being calculated on "HRWSOE". If someone would be kind enough to review what I have and let me know what they think, I'd appreciate it. Thanks! A: The problem here seems to be the source.Except(Yield(x)) part in the LINQ line in PermutationsImpl(). It's comparing and removing all the values in the source which match the values in 'x'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }