text
stringlengths
8
267k
meta
dict
Q: Insert Unique Records, Update Duplicate I have two tables, TABLESource is where will i get the records to be inserted in TABLEDest, now TABLESource can contain duplicate fields: id code name 2 09 abc 3 10 uu 2 09 def 3 10 rr 2 09 gh and i have to insert first all the unique records in the TABLEDest, the id+code is primary key (unique) id code name 2 09 abc 3 10 uu now, in the end, if the TABLESource found duplicate id and name, it must update the TABLEDest with the latest records found in the TABLESource with the same primary key (id_name) id code name 2 09 gh 3 10 rr I have no clue how to do that. Please help me. THanks :) A: I would suggest iterating through your source table and for each row in the source: Psudo Code: //Get all source rows query = 'SELECT * FROM TABLEsource' rows = database.get(query) //Iterate through all source rows for each rows as row{ //Search dest table for a match checkQuery = 'SELECT * FROM TABLEDest WHERE id = '+row.id check = database.get(checkQuery) //If we do get a match if(check.rows > 0){ //Update the relevant row query = 'UPDATE TABLEDest SET name = '+row.name+' WHERE id = '+check.id database.query(query) }else{ //Otherwise, append a new row to the dest table query = 'INSERT INTO TABLEDest(id, code, name) ' +'VALUES('+row.id+'. '+row.code+', '+row.name+')' database.query(query) } } This is psudo code, so directly copying and pasting won't work, but it should be enough for you to use your favorite flavor of language to make it happen. A: Since you have no way to order the rows I choose to pick the min(name) as a value for the name column. insert into TABLEDest select id, code, min(name) from TABLESource group by id, code
{ "language": "en", "url": "https://stackoverflow.com/questions/7524243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it well-defined/legal to placement-new multiple times at the same address? (Note: this question was motivated by trying to come up with preprocessor hackery to generate a no-op allocation to answer this other question: Macro that accept new object ...so bear that in mind!) Here's a contrived class: class foo { private: int bar; public: foo(int bar) : bar (bar) { std::cout << "construct foo #" << bar << std::endl; } ~foo() { std::cout << "destruct foo #" << bar << std::endl; } }; ...which I will allocate like this: // Note: for alignment, don't use char* buffer with new char[sizeof(foo)] ! void* buffer = operator new(sizeof(foo)); foo* p1 = new (buffer) foo(1); foo* p2 = new (buffer) foo(2); /* p1->~foo(); */ /* not necessary per spec and problematic in gen. case */ p2->~foo(); On the gcc I've got around, I get the "expected" result: construct foo #1 construct foo #2 destruct foo #2 Which is great, but could the compiler/runtime reject this as an abuse and still be on the right side of the spec? How about with threading? If we don't actually care about the contents of this class (let's say it's just a dummy object anyway) will it at least not crash, such as in the even simpler application which motivated this with a POD int? A: foo* p1 = new (buffer) foo(1); foo* p2 = new (buffer) foo(2); p1->~foo(); p2->~foo(); You are destructing the same object twice, and that alone is undefined behavior. Your implementation may decide to order a pizza when you do that, and it would still be on the right side of the spec. Then there is the fact that your buffer may not be properly aligned to emplace an object of type foo, which is again non standard C++ (according to C++03, I think C++11 relaxes this). Update: Regarding the question specified in the title, Is it well-defined/legal to placement-new multiple times at the same address? Yes, is it well-defined to placement-new multiple times at the same address, provided that it points to raw memory. A: Peforming placement-new several times on the same block of memory is perfectly fine. Moreover, however strange it might sound, you are not even requred to destruct the object that already resides in that memory (if any). The standard explicitly allows that in 3.8/4 4 A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released;[...] In other words, it is your responsibility to take into account the consequences of not calling the destructor for some object. However, calling the destructor on the same object twice as you do in your code is not allowed. Once you created the second object in the same region of memory, you effectively ended the lifetime of the first object (even though you never called its destructor). Now you only need to destruct the second object. A: No - this doesn't look right. When you use placement new, the object will be constructed at the address you pass. In this example you're passing the same address (i.e. &buffer[0]) twice, so the second object is just obliterating the first object that's already been constructed at this location. EDIT: I don't think I understand what you're trying to do. If you have a general object type (that may have non-trivial ctor/dtor's that might allocate/deallocate resources) and you obliterate the first object by placement new'ing over the top of it without first explicitly calling it's destructor, this will at least be a memory leak.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: What is the easy way to set all empty string textbox ("") to null value in Csharp winform? Suppose I don't want to use if (string.IsNullOrEmpty(textbox1.Text)) { textbox1.Text = null; } for every textbox controls in form, is there a easier way to do it ? A: Simple way is Loop through every control, see the below code foreach (Control C in this.Controls) { if (C is TextBox) { if (C.Text == "") { C.Text = null; } } } A: It is one more way foreach(Control txt in this.Controls) { if(txt.GetType() == typeof(TextBox)) if(string.IsNullOrEmpty(txt.Text)) txt.Text = null; } Hope it helps A: You can iterate through the ControlCollection of the given form, e.g. frmMain.Controls Now this will be the basic Control object, so you would need a test to see if it is of type TextBox. .NET 2.0 - you'll have to check this manually .NET 3.0+ - use the .OfType<TextBox> extension method to give you only a list of IEnumerable<TextBox> Note that iterating through this from the form will only give you text boxes on that form. If you bind text boxes to a container it won't show up there. Safest bet would be to write a recursive function that walks through all the control collections and passes the reference to your test function to perform your test and update. A: Try this: foreach(Control c in this.Controls) { if (c.GetType().FullName == "System.Windows.Forms.TextBox") { TextBox t = (TextBox)c; t.Clear(); } } A: You can create a derived control from textbox control, and override its text property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Need confirmation for contact form to show in same place, not a separate page? For example, if they didn't enter an email address, then this opens in a new window, but I need it in the same window. Current code: // Error message displays if email is missing if (!$from){$errorMes3="ERROR: You didn't enter your email address. "; $error=1; } Also, success message needs to be in same box and redirect to same page, Current code: // display mail sent message else { echo (" <title>SendMail Notice: mail was successfully sent</title><body><br><br><br><br> <p style=\"font:11pt arial\" align=left>Your message has been successfully sent. <br><br><i>Thank you</i></p> </body></html>"); exit(0); A: I used a contact form where it was already integrated and that solved the problem. works great now! A: try with form action $_SERVER['PHP_SELF'] and for the error & success messages you need to check the validations on the same page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any downloader library like Android Asynchronous Http Client [Java] I have found Android Asynchronous Http Client library from google: http://loopj.com/android-async-http/ This is awesome lib for Android. But it's not have download function. Is there any lib which support async download function. A: You can use intentservice http://developer.android.com/reference/android/app/IntentService.html A: Just use an AsyncTask and in the doInBackground method, download your file. Try com.github.droidfu
{ "language": "en", "url": "https://stackoverflow.com/questions/7524259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Permission denied in tmp I just deployed a Rails 3 app with Ruby 1.9.2. I have been getting several errors. * *application.css wasn't compiled. so I set pre compilation in production.rb to false; *Then I got: cannot generate tempfile, so I did rake tmp:clear; *And now I get ActionView::Template::Error (Permission denied - /srv/www/appname/tmp/cache/assets): and I haven't been able to fix this one. Please help. A: Most likely you're running your app under apache passenger. You have to change the owner of config/environment.rb to somebody who has permissions to your app's folder. chown -R www-data:www-data /path/to/app A: * *Make the tmp folder of your project writable: chown -R group:user /path/to/rails/app/tmp chmod -R 777 /path/to/rails/app/tmp *In your console, run rake tmp:cache:clear *Restart your application. A: If the user:group running your web server is http:http and it's running on *nix, do this: sudo chown -R http:http /srv/www/appname/ Also, silly question, but does /tmp/cache/assets exist? And, if so, as @leonel points out, you may also need to change the permissions: chmod 777 /srv/www/appname/tmp/cache Be careful setting 777 permissions on anything. Only do this to verify a permissions issue, then reset to the most minimal permissions necessary. A: You probably didn't create your Rails application with the user running the server now. Can you paste the output of ls -alh /srv/www/appname/tmp/cache/assets and tell us the user running the webserver ? A: Now for those of us that are using windows - If you are an administrator and see this error ActionView::Template::Error (Permission denied @ utime_failed) C:/User/..../tmp/cache/assets/sprochets/v3.0/E5/E5PZx-mq8.cache Then it is Permission and Ownership setting issue on Windows. You can go to the tmp folder on your application and give yourself(User) permission to **Read, Write and Execute ** on the folder. Click [here][1] to view how to give permissions. Quick Fix. Open your terminal and run the following command as an administrator takeown /f <location of your app tmp folder> /r /d y Then Restart your server. A: I encountered this error recently. Apache was not able to write to tmp directory cannot generate tempfile /tmp/RackRewindableInput2xxxxxxxxxxxxxxxxx' /app-lib/lib/ruby/1.8/tempfile.rb:52:ininitialize' app-dir/vendor/gems/rack-1.0.1/lib/rack/rewindable_input.rb:73:in new' app-dir/vendor/gems/rack-1.0.1/lib/rack/rewindable_input.rb:73:inmake_rewindable' app-dir/vendor/gems/rack-1.0.1/lib/rack/rewindable_input.rb:26:in read' app-dir/vendor/gems/rack-1.0.1/lib/rack/request.rb:134:inPOST' I checked permission of tmp directory and it had permission to all groups to write to it. I changed owner of tmp directory and it didn't resolve the error either. The culprit was tmp directory was filled with too many large files, and looks like somehow apache didn't had enough space to write this new file. Cleared all temp and old files. It sorted out the issue. A: We need to grant permissions to access the required directory for the system root user sudo chmod 777 -R your_project_directory_to_be_access In your case you can use: sudo chmod 777 -R /srv/www/appname/tmp/ For security reasons, just keep in your mind: chmod 777 gives everybody read, write and execute rights which for most problems is definitively too much. A: I think a better solution without giving everyone manage rights to tmp folder is like that: sudo rake tmp:cache:clear This will clear the temp folder and when you run rails server again it won't give error. A: Most probably you gave permission to your app's main folder read and execute mode. However, in order to generate new files from your app, you also need to give write permission for required folder. For example: yUML uses tmp folder for generating files. I gave tmp folder write permission: chmod -R 777 /usr/share/nginx/html/yuml_product/tmp solved my problem. A: In my localhost it gave this error, and the command chmod 777 C:/Sites/project_name/tmp/cache/ solved my problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Issue re-deploying updated default parameters in SSRS report I have an SSRS (SQL Server 2008 R2) report with several parameters. I'm having an issue where one of the parameters is not consistently choosing its default value when the report is first loaded. Specifically, it works fine in BIDS but works intermittently (works on one server but not another) once deployed to IIS and viewed in IE. By intermittently, I mean it works on the server I deploy it to, but when I copy the RDS file to another server, the default behaviour for my parameter is broken. Details The parameter has a series of specified (constant) integer values specified in the Available Values section, which represent a selection of fixed reporting periods. The Default Values has a single specified value, which matches one of the Available Values. Options: data type integer, no null values, no multiple values, parameter visible, automatically determine when to refresh. Any ideas why I'm seeing this behaviour? A: That is true, once the report is deployed to the server then the parameters are controlled at the server level. Once item to note however is if you redeploy the report with changes to the default values THEY WILL NOT be changed on the server!!! The report must be deleted and deployed for the new defaults to take effect. If you do not wish to delete the report then change the defaults by hand on the Report Server. A: Another solution without having to delete the reports (the issue when you delete the report is the logs are also deleted) is to open the new deployed report with ReportBuilder (Modifier dans le Générateur de rapports). Just save the report and the defaults values will be changed. A: I've discovered my own answer to this question. I'm detailing it here for anyone else new-ish to SSRS who might be confused by the same behaviour. The parameters can be managed separately from the RDL file, and defaults can be overridden once the report is deployed to the server. To manage the parameters on the server: * *Click on the report name link at top left on the browser page. *Click on the Parameters tab at left. *Manage the parameters as needed (e.g. set the default value). *Click Apply. *Click the report name link (large bold text at top) to return to the report. A: lets say your report name is xyz.rdl if you have set default parameter and deployed it to server now, it will not change on the server. i suggest 3 options 1. change the parameter 'Has Default' value on the server, by right click manage on the report 2. delete the report on the server and redeploy it 3. deploy a dummy report or old version report with same name say 'xyz.rdl' which doesn't have this parameter, doing this will erase report parameters on the server, report stays in tact. then deploy your new version report with default parameter, now it should work. A: I had similar issue. When a report has been deployed to the Server "Without" Default, and you subsequently modify this report in Visual Studio and change the same parameter to have a default, the server will not pickup that the modify report has a default now. My workaround to this dilemma was to create a dummy parameter and put it to the top of the list. I then redeployed the report with the new dummy parameter and the same modified one with a default parameter. This time the server picked up that the parameter I was interested in as having a default value. I then proceeded to delete the dummy parameter in visual studio and redeployed the report. The parameter that I was interested in remained as having a default value. I prevented deleting the report and adding subscriptions to it if I had went that route in order to fix my dilemma. A: It takes a bit of work to correctly handle all the various scenarios, but it is (at least as of Sql Server 2012) possible to update the parameters from a script by loading the .rdl file as an xml file, and comparing it to the various settings available from the ReportingService2010.GetItemParameters method of the SSRS management web service Based on that comparison, you can then update the parameters on the SSRS server using the ReportingService2010.SetItemParameters method. Finally, there is a connect issue "Report parameter defaults not updated during deployment" that is a bit more limited in scope to allow just auto-updating parameter defaults. A: I have noticed this is only a problem when making updates to static parameter values (Value "1"). The expression parameter values seem to a good job of getting updated (Value "=iif(1=1, 1, 0)". Screenshot example included below. I would suggest using an expression. Or if it's a static value just type that in at the manager page. For example: //ssrsdev/Reports/manage/catalogitem/parameters/Accounts%20Receivables/Bill%20of%20Lading%20Comparison Also, I typically deploy my reports using the ReportServerTools powershell cmdlet, so I don't know if maybe their deployment does a better job with updating parameters. So you might try installing and deploying with that tool instead of from Visual Studio. Write-RsRestCatalogItem #------------------------------------------------------ # --1,FILES: Add # Upload file from disk to server #------------------------------------------------------ ## TARGET FOLDER $rsFolder= "/Accounts Receivables" #Datasets #Cost $rsReportPortalUri= "http://ssrsname/Reports/" $locDir= "C:\MyPath\Solution\Report Project\" Get-variable rsReportPortalUri; Get-variable rsFolder; get-variable locDir ## SOURCE ITEM $rsItem= "Bill of Lading Comparison.rdl" $locPath= $locDir + $rsItem Get-variable locPath ## Write-RsRestCatalogItem (1) Write-RsRestCatalogItem -Path $locPath -RsFolder $rsFolder -ReportPortalUri $rsReportPortalUri -RestApiVersion "v1.0" -Overwrite "true" -verbose Parameters - "Static" vs "Expression"
{ "language": "en", "url": "https://stackoverflow.com/questions/7524276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Using $_POST in While PHP Question I'm trying get some information via $_POST in PHP, basically at the moment i'm using this: $item_name1 = $_POST['item_name1']; $item_name2 = $_POST['item_name2']; $item_name3 = $_POST['item_name3']; $item_name4 = $_POST['item_name4']; I want to insert each of the item names in a table field with mysql so i'm trying to experiment with the while php loop so i dont have lots of $item_name variables: $number_of_items = $_POST['num_cart_items']; $i=1; while($i<=$number_of_items) { $test = $_POST['item_name'. $i'']; $i++; } The above code fails, its pretty tricky to explain but the code should find all the item_name $_POST and make it as a variable for mysql insertion. The $_POST['num_cart_items'] is the total number of items. The code is for a PayPal IPN listener for a shopping cart that is underway. Help appreciated. EDIT: I have this further up the document which i just realised: $req = 'cmd=_notify-validate'; foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } How can i insert $_POST['item_name1'], $_POST['item_name2'] as a variable for mysql insertion? A: Your loop is effectively overriding the $test variable on each iteration: $test = $_POST['item_name'. $i'']; If you want to put them in an array, change to $test[]. Also it contains the parse error as mentioned by brian_d. It sounds a little scary to have a variable num_cart_items that is sent with the form. Are you setting it with JavaScript? The user can manipulate it. You should not rely on it. I belive what you need is to make the form feilds as: <input type="text" name="item_name[]" /> Note the square brackets at the end of the name. This will create an array in the $_POST array: $_POST['item_name'] will contain the names of all the items. Then, how is your DB structured? I guess you want to insert them in one query as: INSERT INTO ORDERS VALUES (item_name_1, ...), (item_name_2, ...) If so you can make a string out of the array: $query = 'INSERT INTO ORDERS VALUES '; foreach($_POST['item_name'] as $item_name){ $query .= '('.stripslashes($item_name). /*put other column values*/ '),'; } $query = rtrim($query, ','); Note that the use of addslashes is not enough to protect you from SQL injection. A: $test = $_POST['item_name'. $i'']; is a syntax error. remove the end '' so it becomes: $test = $_POST['item_name'. $i];
{ "language": "en", "url": "https://stackoverflow.com/questions/7524277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does media queries work for all smart phones I am trying to develop a mobile application, which should run on all smartphones, tablets and some feature phones. I have used CSS3 media queries before and tested in Android and iOS, where it works like a charm. But what about Nokia and Bada OS, does this work ? A: You can take a look at the indispensable Mobile compatibility chart from Peter-Paul Koch. Media Queries are pretty well supported, as long as the browser is Opera, Firefox or uses the Webkit engine (virtually all modern mobile browsers do). You might have some trouble getting it to work on older Blackberries and Windows Mobile 7 and lower though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: adding elements to including file via XInclude Can I somehow add elements to included file using XPointer or XPath or anything else? Main file <doc xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="field.xml" /> </doc> field.xml <field> <title>address</title> <type>string</type> </field> I want to add 'size' element to field.xml while including so the resulting file should look like <doc xmlns:xi="http://www.w3.org/2001/XInclude"> <field> <title>address</title> <type>string</type> <size>64</size> <size>51</size> </field> </doc> A: Problem solved I've used next trick to solve the problem: <doc xmlns:xi="http://www.w3.org/2001/XInclude"> <field> <xi:include href="field.xml#xpointer(/field/child::*)" /> <size>64</size> <size>51</size> </field> </doc> I've included from 'field.xml' all child elements that belong to parent 'field'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get information about events from Google calendar on Java, Android? I need get information about events from calendar of my Android device, but I don't know how to do it. Give me an example please or give me a advice. A: You should use oAuth : http://code.google.com/intl/fr-FR/apis/accounts/docs/OAuth2ForDevices.html You can also use the Java tool: http://code.google.com/intl/fr-FR/apis/calendar/data/2.0/developers_guide_java.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7524285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert multiple photos into a Tumblr post and turn it into an image slideshow I'm trying to have it so I can add x amount of photos to a Tumblr post and then turn it into a custom image slideshow using jQuery cycle. Is there any way to add x amount of photos to a post and have it spit the images out in a consistent manner? I added 6 and eventually it just points to an iframe that loads their custom slideshow. I don't want to resort to having to edit custom HTML in a post though. A: Photosets give you Photo blocks that you can treat like regular Photo blocks. Just had to add those blocks and have it display in an unordered lists. Docs A: Elaborating on that answer... Once you have the photo sets being treated as a list of photos, it would be easy to hookup a jQuery plugin to turn them into a slideshow (try nivo or flex slider)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why are predicate and class distinct in rdf? In RDF, a class is distinguished from a predicate or attribute. What is the benefit of doing this versus just having one thing, a class, that can appear as subject, predicate or object in any triple? Edit: for example: 1 book has chapters 2 book1 is book 3 chapter1 is chapter 4a book1 chapter chapter1 In this example, chapter is both an object (in statement 3) and a predicate (in statement 4a). Some people claim that this is not a good idea. The meaning of these statements is quite obvious - a book has chapters, book1 is a book, chapter1 is a chapter, book1 has a chapter called chapter1. An alternative suggested is to replace 4 above with 4b: 4b book1 has chapter1 However, this requires more effort to parse/reason: if book has chapter, book has author, book has publisher, then a statement like book1 has foo requires a lot more work to figure out (we have to find that foo is, say, an author to figure out that book1's author is foo). Better still, I can avoid statement 3 above, since statement 4 tells me that chapter1 is a chapter. This pattern appears commonly in graphs containing both data and metadata. Are there any disadvantages in using 1,2,4a versus 1,2,3,4b? The only problem I see is that this violates the distinction between a property and a class (subject/object), but how does that affect us practically? A: Your example (books and chapters) only appears to make sense because of the loose and flexible way we use language, and our human interpretation (and your use of a possessive as the example) So if I said Book - Chapter - Chapter1 then that only appears to make sense because mentally we map the noun Chapter to the verb phrase "has Chapter", because we understand how books and chapters work. Machines consuming RDF do not understand this! But if I said Book - Person - John, what are we to make of this? Is John the author, the reader, one of the characters, or what? This is why we need to specify an unambiguous predicate, e.g. Book - hasAuthor - John Book - readBy - John A: I don't entirely understand your question here. The RDF data model is based upon three kinds of terms: * *URIs (aka Named Resources) - These may appear in any position in the Triple *Blank Nodes (aka Anonymous Resources) - These may appear as the Subject/Object of a Triple *Literals - These may appear only as the Object of a Triple When you start talking about classes you are no longer talking pure RDF as you are brining in a schema language like RDFS or OWL which define the notion of classes. The main reason for using these higher level schema languages is that it allows you to define restrictions and relationships more clearly and perhaps use some reasoning over those. Regardless of whether something is a Class the only restrictions on where it can appear in a triple are the term type. So for example I could write the following: @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix ex: <http://example.org/> . ex:Thing a rdfs:Class . ex:this ex:Thing ex:that . That's perfectly legal RDF it just doesn't necessarily actually express data that makes any sense to anyone!
{ "language": "en", "url": "https://stackoverflow.com/questions/7524293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to solve this problem with calendar alarm? I am trying to make alarm ring when the time of calendar event is reached. I use to set AlertDialog when the alarm time is reached. But event when the application is closed, i need to notify the user through Alert Dialog. I have started the intent to the AlarmReceiver which extends BroadCastReceiver.My code is here in this link. AlarmReceiver.java: http://pastebin.com/0ch5hjp9 Alert.java: http://pastebin.com/bJAPAUV2 I am not getting alarm since i use to call alertdialog intent. I am getting following exception when i reach the AlertDialog intent: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.android.todoapplication/android.todoapplication.Alert}; have you declared this activity in your AndroidManifest.xml? A: make sure that you also set contentView to activity using setContentView() method. atleast an empty linearLayout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Merging two dataset I have one "big" TOracleDataSet which I can't change 'cause it's using in many different parts of huge project. I want to add just one record to this dataset for using in another grid. The solve way I see it is create another one oracle data set which will combine wanted record and another ones from "big" dataset. In other words, "small" dataset includes "big" dataset. A: Try this maybe? TxQuery Project This was a commercial project at one time, but the auther was convinced to release it opensource. TxQuery component is a TDataSet descendant component that can be used to query one or more TDataSet descendant components using SQL statements. It is implemented in Delphi 100% source code, no DLL required, because it implements its own SQL syntax parser and SQL engine. That quote was taken from the page of the current maintainer, I believe, Chau Chee Yang . Either this or maybe TClientDataset might be your best options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pyQt signals/slots with QtDesigner I'm trying to write a program that will interact with QGraphicsView. I want to gather mouse and keyboard events when the happen in the QGraphicsView. For example, if the user clicks on the QGraphicsView widget I will get the mouse position, something like that. I can hard code it rather easily, but I want to use QtDesigner because the UI will be changing frequently. This is the code that I have for the gui.py. A simple widget with a QGraphicsView in it. from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_graphicsViewWidget(object): def setupUi(self, graphicsViewWidget): graphicsViewWidget.setObjectName(_fromUtf8("graphicsViewWidget")) graphicsViewWidget.resize(400, 300) graphicsViewWidget.setMouseTracking(True) self.graphicsView = QtGui.QGraphicsView(graphicsViewWidget) self.graphicsView.setGeometry(QtCore.QRect(70, 40, 256, 192)) self.graphicsView.setObjectName(_fromUtf8("graphicsView")) self.retranslateUi(graphicsViewWidget) QtCore.QMetaObject.connectSlotsByName(graphicsViewWidget) def retranslateUi(self, graphicsViewWidget): graphicsViewWidget.setWindowTitle(QtGui.QApplication.translate("graphicsViewWidget", "Form", None, QtGui.QApplication.UnicodeUTF8)) The code for the program: #!/usr/bin/python -d import sys from PyQt4 import QtCore, QtGui from gui import Ui_graphicsViewWidget class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_graphicsViewWidget() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.graphicsView, QtCore.SIGNAL("moved"), self.test) def mouseMoveEvent(self, event): print "Mouse Pointer is currently hovering at: ", event.pos() self.emit(QtCore.SIGNAL("moved"), event) def test(self, event): print('in test') if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_()) When I run this code, it gives me the opposite of what I want. I get the mouse position everywhere except for inside the QGraphicsView. I'm sure it's a problem with my QObject.connect. But every time I go back and read about signals and slots it makes sense but I can't get it. Please help, I've been banging my head for the past few days now. I'm sorry if this as been asked before but I've been through all the threads on this topic and I can't get anywhere. Thanks A: The signal must come from the QGraphicsView object that was defined in the ui. You can create a class derived from QGraphicsView like this from PyQt4.QtCore import * from PyQt4.QtGui import * class MyView(QGraphicsView): moved = pyqtSignal(QMouseEvent) def __init__(self, parent = None): super(MyView, self).__init__(parent) def mouseMoveEvent(self, event): # call the base method to be sure the events are forwarded to the scene super(MyView, self).mouseMoveEvent(event) print "Mouse Pointer is currently hovering at: ", event.pos() self.moved.emit(event) Then, in the designer: * *right-click on the QGraphicsView then Promote to *write the class name in the Promoted Class Name field (e.g. "MyView"), *write the file name where that class is in the Header file field but without the .py extension, *click on the Add button and then on the Promote button. And you can regenerate your file gui.py with pyuic4.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I redirect everything to a single controller? I have three specific routes: routes.MapRoute( "Home Page", "", new { controller = "Home", action = "Index" } ); routes.MapRoute( "Admin Section", "AdminSection/{action}/{id}", new { controller = "AdminSection", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( "Listings", "{controller}/{action}/{id}", new { controller = "Listings", action = "Index", id = UrlParameter.Optional } ); Basically, the first two routes work as planned, however, I want everything that isn't specifically in a route to be redirected to the listings controller. I am still quite new to routing and have been trying to Google this for the past hour without any luck - I know exactly what is going on here, but, I don't know how to fix it. I have used RouteDebugger, and I can see that it is hitting the route, but, the issue is that it will only go to the Listings controller if a controller is not specified - but, obviously there will always be something there. I have tried a few different combinations - I thought I was on to a winner by removing the {controller} part of the URL and still defining the default value, but, I am not having much luck. Does anyone know what I need to do? A: How about this: routes.MapRoute("Listings", "{action}/{id}", new { controller = "Listings", action = "Index", id = UrlParameter.Optional }); site.com/test : It'll go to action: test, controller: listing, id = blank A: Edit: As I understand it you want a catch-all route. http://richarddingwall.name/2008/08/09/three-common-aspnet-mvc-url-routing-issues/ routes.MapRoute("Listings", "{*url}", new { controller = "Listings", action = "Index" } ); Original: I can't test this at the moment but routes.MapRoute( "Listings", "{anythingOtherThanController}/{action}/{id}", new { controller = "Listings", action = "Index", id = UrlParameter.Optional } ); This should work. In your Listings controller, just accept a string parameter "anythingOtherThanController" and it will get bound to it. The main problem here is that /some/action will be mapped to the same action as /another/action. So I'm not sure what you're trying to do here :) A: Provide a default route and provide controller name as listings controller. Keep this route mapping at the bottom of all the mappings. routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Listings", action = "Index", id = UrlParameter.Optional } ); Sorry I got sequence mixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Big Omega Notation. Am I doing this right? If I have some algorithm that runs at best n time and at worst n^2 time, is it fair to say that the algorithm is Big Omega (n)? Does this mean that the algorithm will run at least n (time)? I am just not sure if I have the right idea here. Thanks. A: For Big Oh, you will state the worst time as the time it takes, in your case O(n^2). For Big Omega, you state the smallest time, in this case f(n). Also see this guide to Big O and this discussion of Big O and Big Omega. A: Yes. If the runtime f(n) is asymptotically bounded below by g(n) = n, then f(n) is BigOmega(n). Edit: Most of the time, algorithms are analyzed in terms of their worst-case behavior -- which corresponds to "Big O" notation. In your case, the runtime is O(n^2). But for those rare occasions when you need to talk about a lower bound, or best case behavior, "Big Omega" notation is used. And in your case, the runtime is at least n, so it is correct to describe it as BigOmega(n).
{ "language": "en", "url": "https://stackoverflow.com/questions/7524318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Manipulate the form field values before rendering in django admin I have to actually reset the values of the fields of a model Form, every time the form is rendered. So, lets say everytime a user fills the form, I store the values to a different table and next time when the form is rendered the values are reset to specified data. Again, when the user saves the form, the values are added to the different table and so no. This is quite weird but I need to implement this. So, how am I supposed to reset the values of a model form before the form is displayed. Definitely, the model belonging to that form is updated with the new values everytime. But I need to reset them when rendered again for edit. Let me pinpoint what I actually need. I need to override the field values during edit. So if a model was saved with field A having value 'value1'. I need to change this field's value to 'specified value' during edit. So even if the user then changes it to value 2 and saves it. During edit, I again want to have the value set to 'specified value' in the rendered form. It is independent of the values in the database A: You can set form values using initial value: form = MyForm(initial={'field1': value1, 'field2': value2, 'field3': value3})
{ "language": "en", "url": "https://stackoverflow.com/questions/7524323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Threading: Pause Main Thread until Sub Thread is closed. My problem is simple. I have an application, in which I create and call a sub thread. My sub thread launches a notepad, where a user inputs some values and then closes it. My application then takes the information from the notepad for additional processing. The problem is that my main thread doesn't wait for the sub thread to end (notepad to be closed), to perform the additional processing. I could have used a form to gather these inputs, but I wish to have a program that is minimalistic. Today, the inputs are from a notepad. Tommorow, it may be from MS Office or OpenOffice. Can someone please provide some guidance? Regards. A: I think there's a simpler approach here. The Process class has an Exited event that you can sign up for: var process = new Process(); process.StartInfo = new ProcessStartInfo("notepad.exe"); process.EnableRaisingEvents = true; process.Exited += (o, e) => { Console.WriteLine("Closed"); }; process.Start(); A: The command you need is Thread.Join A: In the code for the helper thread: using ( Process p = Process.Start(...your parameters here...) ) { // waits for the user to close the document p.WaitForExit(); // TODO: postprocessing of the edited document } In your Main method: static void Main(string[] args) { ... Thread helperThread = // TODO: create thread helperThread.Start(); // TODO: do other things ... // Wait for the helper thread to exit helperThread.Join(); } You have to wait for the started process to exit (Process.WaitForExit) and wait for the thread to exit as well (Thread.Join). That said, you don't have to use a separate thread, you can start the process in the main thread. Editing of the document runs in parallel anyway. Just use WaitForExit when you need the output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ternary Search Tree in C, Pointer to a Pointer to a struct problem I'm trying to build a ternary search tree for a school project. As far as I can tell, my code looks okay. But, the leaf nodes of the original root function are not being initialized when I use malloc. So every string comparison beyond the first one (whatever the root's string is) wind up empty (not null, but ""). I'm not passing any pointers as function arguments, so I can't figure out what the problem is. Please help! I suspect the problem is somewhere in this part of the code. I really have racked my brain and searched and cannot figure out what my problem is. More code is available if you want. I have checked and root->right points to an entirely different location than current->right on the first pass. That's my real problem. I figure it must be an error in declaration or something, but I just can't figure it out. node_t* buildTree(FILE *file) { // check for at least one input // set this input as the root of the tree // if there is no input, print error message and return char start[MAX_TOKEN_LENGTH]; fscanf(file, "%s", start); printf("Root: %s\n", start); node_t *root = malloc(sizeof(node_t)); root->counter = 1; root->depth = 0; root->right = NULL; root->middle = NULL; root->left = NULL; printf("Allocated.\n"); int n = 0; while(n < strlen(start)) { root->string[n] = start[n]; n++; } printf("Root stored as: %s\n", root->string); char word[MAX_TOKEN_LENGTH]; while(fscanf(file, "%s", word) != EOF) { printf("Read a word: %s\n", word); // Reset depth and sort location // Start sorting from the root element int depth = 0; node_t *current = root; // Continue sorting into the tree until a null node is encountered. // Increment the depth each pass while (current->string != NULL) { printf("Comparing %s with %s, result is %d\n", word, current->string, strcmp(word, current->string)); if ( ( word[0] == current->string[0] ) && ( strcmp (word, current->string) != 0 ) ) { printf("Middle node\n"); if (current->middle == NULL) { printf("Middle node is empty; creating new leaf.\n"); current->middle = malloc(sizeof(node_t)); int n = 0; while (n < strlen(word)) { current->middle->string[n] = word[n]; n++; } current->middle->counter = 0; current->middle->depth = ++depth; current->middle->left = NULL; current->middle->middle = NULL; current->middle->right = NULL; break; } A: You have: while (n > strlen(word)) it should be while (n < strlen(word))
{ "language": "en", "url": "https://stackoverflow.com/questions/7524325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need to read the previous node's child values to format the current node's value using xsl? I need to use the formats tag while displaying the contents of rowdata, in the rowdata tags. the xml is follows: "temp.xml" <?xml version="1.0" encoding="iso-8859-1"?> <?xml-stylesheet type="text/xsl" href="Temp.xsl"?> <ALL_DATA> <TITLES> <VALUE1>Title1</VALUE1> <VALUE2>Title2</VALUE2> <FVALUE1>Title3</FVALUE1> </TITLES> <FORMATS> <VALUE1>I5</VALUE1> <VALUE2>I3</VALUE2> <FVALUE1>F1.1</FVALUE1> </FORMATS> <MY_DATA> <ROWDATA> <VALUE1>5</VALUE1> <VALUE2>33</VALUE2> <FVALUE1>2.11</FVALUE1> </ROWDATA> <ROWDATA> <VALUE1>34</VALUE1> <VALUE2>12</VALUE2> <FVALUE1>239.81</FVALUE1> </ROWDATA> </MY_DATA> </ALL_DATA> and i tried xsl is: "temp.xsl" <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <xsl:template name="MY_TEMPLATE" match="/"> <html> <body> <table border="1"> <TR border="1"> <xsl:for-each select="/ALL_DATA/TITLES/*"> <th border="1"> <xsl:value-of select="."/> </th> </xsl:for-each> </TR> <xsl:for-each select="/ALL_DATA/MY_DATA/ROWDATA"> <TR> <xsl:for-each select="*"> <TD width ="130"> <xsl:value-of select="."/>:-: <xsl:variable name="cur_node_name" select="name(.)"/> <xsl:for-each select="/ALL_DATA/FORMATS[name(.)]"> <!--<xsl:template match="$cur_node_name"> --> <xsl:value-of select="."/> <!--</xsl:template>--> </xsl:for-each> </TD> </xsl:for-each> </TR> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> I am sorry to post entire content. I feel i can get some help. In above xml, i want to use formats/value1 while displaying the Mydata/rowdata/value1. The above Xsl iterates the titles block and display the titles in <th>. and then the second for-each block will iterates through rowdata, and its child items. In displaying child items, i need to use formats tags to display rowdata's childs. The above xsl is giving output for 3rd tag FValue1 as : "2.11:-: I5 I3 F1.1" ; But my expectation is : "2.11:-: F1.1". If i get this solution, i can do the rest. I know just by modifying inner for loop, that can be possible. but could not get that Please help if any one have suggestion how to. thanks. A: If you sample data isn't oversimplified your xslt could drop the for-each altogether and look like this: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" indent="yes"/> <xsl:template match="/"> <html> <body> <table border="1"> <xsl:apply-templates select="TITLES" /> <xsl:apply-templates /> </table> </body> </html> </xsl:template> <xsl:template match="TITLES"> <tr> <th><xsl:value-of select="./VALUE1" /></th> <th><xsl:value-of select="./VALUE2" /></th> <th><xsl:value-of select="./FVALUE1" /></th> </tr> </xsl:template> <xsl:template match="ROWDATA"> <tr> <td> <xsl:value-of select="./VALUE1" />:-:<xsl:value-of select="//FORMATS/VALUE1" /> </td> <td> <xsl:value-of select="./VALUE2" />:-:<xsl:value-of select="//FORMATS/VALUE2" /> </td> <td> <xsl:value-of select="./FVALUE1" />:-:<xsl:value-of select="//FORMATS/FVALUE1" /> </td> </tr> </xsl:template> <xsl:template match="MY_DATA"> <xsl:apply-templates /> </xsl:template> </xsl:stylesheet>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is their any way out to make the cylinder guage fusion chart horizontally aligned? I am using the cylinder gauge fusion chart shown in this example link http://www.fusioncharts.com/widgets/Gallery/Cylinder1.html , can we make this cylinder look horizontal by any means, the xml attributes are specified in the following link http://www.fusioncharts.com/flex/docs/charts/contents/ChartSS/Cylinder_XML.html A: FusionWidgets does not support display of the Cylinder Gauge horizontally with any XML configurations, as of now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I can't get this simple regex to work correctly I'm doing this in Javascript Here's my string: 09.22.2011-23.21-west-day Here's what I'd like to pull out of it: 23.21 Here's my expression: /-[0-9]*\.[0-9]*/ I get -23.21 so I'd have to run a a replace method after this to remove the "-". Is there a way to leave out the "-" with this regex or not? I never really perfected my regex skills because I usually use PHP which has the nice () capture groups. A: Javascript has capture groups too: var time = "09.22.2011-23.21-west-day".match(/-(\d{2}\.\d{2})/)[1] Gives you 23.21 * *You can use \d as a shorthand for [0-9] *If you know how many digits it's supposed to have, use {n} or {m,n} quantifiers. It will reduce the chance of it matching the wrong thing. A: You can use () in JavaScript too! s = '09.22.2011-23.21-west-day'; rx = s.match('-([0-9]*\.[0-9]*)') alert(rx[1]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7524335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ListView android:empty in code When creating a custom ListView in XML, you can add the android:id/empty tag to the ID to make that view show when the ListView is empty; as mentioned in this Android documentation. I'm just wondering, does anyone know how to do the equivalent dynamically in code? UPDATE This is what I have: public class CustomList extends ListView { public CustomList(Context context) { // some initialization TextView text = new TextView(context); // some parameters like text size, color, and font are set here setEmptyView(text); } } The setEmptyView seems ineffective, in fact is just causes everything to be gone when the ListView goes empty. A: Very simple. Use FrameLayout. Frame layouts are one of the simplest and most efficient types of layouts used by Android developers to organize view controls. They are used less often than some other layouts, simply because they are generally used to display only one view, or views which overlap. The frame layout is often used as a container layout, as it generally only has a single child view (often another layout, used to organize more than one view). For example : <FrameLayout android:id="@+id/list_and_empty_message_container" android:layout_height="wrap_content" android:layout_width="fill_parent" android:orientation="vertical"> <!-- List view --> <ListView android:id="@+id/main_list_view" android:background="@android:color/transparent" android:layout_width="fill_parent" android:layout_height="wrap_content" android:cacheColorHint="#00000000" android:layout_gravity="top" android:divider="#D7C3F8" android:dividerHeight="2dip" /> <TextView android:text="No info Found." android:id="@+id/list_empty_txt" android:layout_height="wrap_content" android:textSize="16.1sp" android:textStyle="bold" android:typeface="monospace" android:layout_marginLeft="5dip" android:layout_gravity="center_vertical" android:gravity="center" android:textColor="#000000" android:layout_width="fill_parent" android:visibility="gone" /> </FrameLayout> And count your data adapter. If that is empty set textview as visible, else set visibility to gone. Put below code in your onCreate(), TextView emptyText = (TextView) findViewById(R.id.list_empty_txt);; if(Your_data_array.size() <= 0) emptyText.setVisibility(View.VISIBLE); else emptyText.setVisibility(View.GONE); It will work. * ___________Updated__________* Take a look in ListActivity class, there is a method that sets empty message if your data source is empty. public void onContentChanged() { super.onContentChanged(); View emptyView = findViewById(com.android.internal.R.id.empty); mList = (ListView)findViewById(com.android.internal.R.id.list); if (mList == null) { throw new RuntimeException( "Your content must have a ListView whose id attribute is " + "'android.R.id.list'"); } //Take a look here if (emptyView != null) { mList.setEmptyView(emptyView); } mList.setOnItemClickListener(mOnClickListener); if (mFinishedStart) { setListAdapter(mAdapter); } mHandler.post(mRequestFocus); mFinishedStart = true; } I will help you to solve your problem. Happy coding :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do Groovy Scripts interact with propertyMissing? I writing a DSL that executes as a Script; it has various classes for various bits of syntax. e.g., for the "foo" keyword that takes a closure, I have a FooSyntax class and evaluate the closure "with" an instance of that syntax. This works fine, e.g. bar = thing {} // make a thing baz = foo { mykeyword bar } passes the thing called bar to an invocation of FooSyntax#mykeyword. I'm trying to add some better error messages for when there is an unknown variable reference. This manifests as a MissingPropertyException so my current approach is to add a propertyMissing method to FooSyntax. This works indeed for variables that are missing. Unfortunately, it breaks the example above: bar becomes a missing property instead of falling through to the Binding. Why does adding a propertyMissing cause the Binding not to be consulted? (Does this have to do with the Closure's resolve strategy?) How can I fix this? You can play with this with a sample script at https://gist.github.com/1237768 A: I shall delegate my answer to the gist on which I commented. Basically, you should not be using the with() method to execute the closure against the FooSyntax delegate. For future reference, the standard approach is: def foo(Closure cl) { def f = new FooSyntax() def c = cl.clone() c.delegate = f c.call() } You can fine tune the behaviour by changing the resolution strategy on the closure like so: c.resolveStrategy = Closure.DELEGATE_FIRST but in this case you want the default Closure.OWNER_FIRST to ensure the binding is queried first. A: Since bar was not being declared (just assigned), it was hitting the property missing because there wasn't an already defined bar in the script or syntax classes. In your example, I think you want to implement a methodMissing. In your scenario you are trying to call Foo.myKeyword with a non-Thing type. So that is really a missing method and not a missing property. I've changed your script, changing propertyMissing to methodMissing and adding def for foo and also defined bar as a String. class Thing { } class FooSyntax { def myKeyword(Thing t) { println "Hello Foo " + t.toString(); } def methodMissing(String name, args) { println "no method named ${name} for ${args} exists" } } class ScriptSyntax { def foo(Closure cl) { def f = new FooSyntax(); f.with cl } def thing() { new Thing() } def dispatchKeyword(String methodName, Object args) { invokeMethod(methodName, args) } } def runner(String text) { def source = new GroovyCodeSource(text, "inlineScript", "inline.groovy") def script = new GroovyClassLoader().parseClass(source).newInstance(binding) as Script def dsl = new ScriptSyntax() script.metaClass.methodMissing = { name, args -> dsl.dispatchKeyword(name, args) } script.run() } runner("""def bar = thing() def baz = "not a thing" foo { myKeyword bar } foo { myKeyword baz }""") Output: Hello Foo Thing@1038de7 no method named myKeyword for [not a thing] exists
{ "language": "en", "url": "https://stackoverflow.com/questions/7524340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MySQL - Index to speed up queries with aggregate functions As I understand, an index on a typical database table will provide a more efficient row look up. Does a similar construct exist for making queries with aggregate functions more efficient? As an example, let's say I have a table like below with a large number of rows Employees employeeId | office | salary SELECT office, MAX(salary) FROM Employees GROUP BY office I want to efficiently retrieve the MAX() salary for employees from each office. In this case, I don't mind the additional insert/update overhead because I will be making this query fairly often and not writing to the table very often. My engine is MyISAM on MySQL A: Use EXPLAIN to see the query execution plan. Then add an index and check if the query execution plan improves. You could also use profiling: mysql> SET profiling=ON; mysql> SELECT… mysql> SET profiling=OFF; mysql> SHOW PROFILES; mysql> SHOW PROFILE FOR QUERY 1; Partitioning might also improve the performance of your query. A: Found this looking for another issue but here should be a solution to the given problem: MySQL docs state that group by optimization works if you use MAX() or MIN() as the only aggregate functions in your query. In that case, your group by fields need to be the leftmost index part. In your case, an index (office, salary) should do the trick. Here the docs: https://dev.mysql.com/doc/refman/5.5/en/group-by-optimization.html A: Composite index office + salary is the best you can do (if you don't want to just store the maximum precalculated in another table).
{ "language": "en", "url": "https://stackoverflow.com/questions/7524342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# List hides properties? Possible Duplicate: How does List<T> make IsReadOnly private when IsReadOnly is an interface member? Okay, this is driving me nuts. List<T> implements IList<T>. However, IList<int> list = new List<int>(); bool b = list.IsReadOnly; bool c = ((List<int>)list).IsReadOnly; // Error The error is: 'System.Collections.Generic.List' does not contain a definition for 'IsReadOnly' and no extension method 'IsReadOnly' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?) How can this be? Doesn't this violate the very rule that we tell everyone, about not hiding members? What is the implementation detail here? A: Because the implementation is via an explicit interface implementation. Meaning that it's defined as bool IList<T>.IsReadOnly { get; set; //etc } http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx And that is why it's not off of List. A: List<T> implements IList<T> explicitly so you have to cast the object to the interface before being able to access IsReadOnly . From MSDN: A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface A: If you look at the List class, you'll see this: bool IList.IsReadOnly { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; } All that's really relevant is that IsReadOnly is declared using the explicit implementation which means that property can only be seen if the object is declared as that of IList. A: Explicit interface implementation, something like: bool IList<T>.IsReadOnly { get; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Magento category dropdown menu - sub menu to be in 2 columns I using Magento Community Edition v1.5. By default all sub categories appear one after the other (1 column) under main category on mouse over e.g Main category is Apparel, Sub category will display Shirts, Pants etc in 1 column. I would like to display sub-categories in 2 or 3 columns on mouse over main category. Doesn't allow me to post sample screenshort but I hope my question is clear. Thank you. A: check this extension may be this can fulfil your requirments http://web-experiment.info/webandpeople-custom-menu-extension.html cheers!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7524345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails Multi-tenant & Spring Security Core plugins I am using Grails multi-tenant plugin with single-tenant mode. I have used spring security core plugin for authentication. I have used domain name resolver. User table is not common in default database. Every tenant db has it's own user tables. It works fine except with the following 2 issues. * *When the client(tenant) user tries to login, sometime it hits the default database and say 'User Not found'. If I try after refreshing the page(entering the url and press CTRL+F5), it logins correctly. *I have a common user across the tenants with different access permissions. First I open my application in a browser with one tenant URL, login with the credentials and logged successfully. Next I open another tab in the same browser, enter the second url and login credentials. Here I am able to login to the application but I get the permissions of the 1st tenant. If I logout and refresh the page as mentioned or if I refresh the page before login and try, it works fine. When I debugged, I found that before resolving the tenant, spring security hits the database with the previous db session. How can I resolve this? A: When the request hits my login page, I get the tenantId and keep it in the session Integer tenantId = tenantResolver?.getTenantFromRequest(request) if (session.tenantId == null) { session.tenantId = tenantId } To get the logged in user details, I override the 'loadUserByUsername' method by implementing GrailsUserDetailsService and called within the transaction. UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { def requst = SecurityRequestHolder.request def httpSession = requst.getSession(false) Integer tenant = httpSession.tenantId TenantUtils.doWithTenant (tenant) { User.withTransaction { status -> User user = User.findByUsername(username) } } } Now my issue is solved. A: You have to make sure that the multi-tenant servlet filter is registered before the Spring security filter. I'm not sure how to do this without recompiling the plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mongoose / mongodb date save castError I am getting this error when just getting a document from the database and then immediately saving it. It is accepted on the initial insert though, and looks like the date fields are empty even though they are required. { stack: [Getter/Setter], message: 'Cast to date failed for value "[object Object]"', name: 'CastError', type: 'date', value: { millisecond: 0, second: 0, minute: 0, hour: 0, day: 21, week: 38, month: 8, year: 2011 } } This is the schema and query code that fails: var Event = new Schema({ id : { type: String, index: true } , msg : { type: String, lowercase: true, trim: true } , triggerOn : { type: Date, required: true } , createdOn : { type: Date, required: true } , triggered : { type: Boolean, required: true } }); exports.pullAndUpdateTest = function(){ var Model = mongoose.model('Event'); Model.find({ triggered: false }, function (err, docs) { if (err){ console.log(err); return; } docs.forEach(function(doc, index, array){ //date both appear to be null here console.log(doc.triggerOn); //=> null / prints blank console.log(doc.createdOn); //=> null / prints blank doc.triggered = true; doc.save(function(err){ console.log(err)}); }); }); } A: This will occur if you have datejs required anywhere in your application (or use any module that, in turn, requires datejs). A: Date.js is a very cool library, however the default implementation will create a mess in Node.js applications when working with MongoDB. I'd recommend you to use safe_datejs. You will be able to use Date.js function but you're gonna have to convert the Date values to a Date.js object before calling any of the Date.js magical functions. Example: var safe_datejs = require('safe_datejs'); var today = new Date(); var unsafeToday = today.AsDateJs(); // Converting to Date.js object var unsafeTomorrow = unsafeToday.clone().add({days:1}); // Work with Date.js a little var tomorrow = unsafeTomorrow.AsRegularDate(); //converted back safe to be used with MongoDB To change culture specific attributes, use safe_datejs.DateType.CultureInfo More info: https://github.com/firebaseco/safe_datejs A: Have you defined your model with mongoose? var Model = mongoose.model('Event', Event);
{ "language": "en", "url": "https://stackoverflow.com/questions/7524349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the best way to log Core Data NSManagedObject IDs on creation? I've dealt with a couple errors recently in which I will get an exception that mentions a managed object by URI. The URI is somewhat helpful. It looks kind of like x-coredata://blahblahblahblahblah/EntityName/p22. At least I can tell what type of entity the problem occurred on, but I have not as yet been able to track it down to a particular object. So far I've been able to debug the problems without figuring that out. I imagine I could track it down. I could probably open up the database and do SQL queries until I found something that matched up to something in the URL. However that seems like kind of a lot of trouble, and also not very efficient if I have to debug a problem that happens on a beta tester's or deployed user's device. So I think it would be nice to log the object ID URI when the object is created, along with some properties I can recognize the object by. Should be simple, right? Just right after I create an object in my code I do an NSLog something like NSLog(@"Created Foo instance: %@", [foo.objectID URIRepresentation]); Only problem is, the URIs I;m getting don't look like the above. They look more like x-coredata:///EntityName/blahblahblahblahblah. I realized I'm probably getting temporary IDs. So, how can I match that up with the permanent ID? If I could find out a hook where I can just put a log message saying "Object with temporary ID %@ reassigned permanent ID %@" that would be all I need. A: I question the value of this but it is possible via two methods in the NSManagedObject itself. First, set up a transient NSString either directly in the model or in the subclass. Then override the following methods: - (void)willSave { if (![[self objectID] isTemporaryID]) return; [self setTemporaryIDString:[[[self objectID] URIRepresentation] absoluteString]]; } - (void)didSave { if (![self temporaryIDString]) return; NSLog(@"%@ moved to %@", [self temporaryIDString], [[[self objectID] URIRepresentation] absoluteString]); [self setTemporaryIDString:nil]; } A: Core Data NSManagedObject has a property debugDescription, use it. NSManagedObject * customer = nil; NSLog(@"customer : %@", customer.debugDescription);
{ "language": "en", "url": "https://stackoverflow.com/questions/7524362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check string for substring with "Wild Character" Is it possible to check a string for a substring plus a wild character? I am checking a url for a substring and I know there is the substring function but I am wondering if you can use the * character? Below is my function so far. function press_getUrl(){ $valid = true; $current_url = $_SERVER['REQUEST_URI']; //This is where I am checking for a substring plus whatever is after. if ($current_url == "/search/node/*"){$valid = false;} return $valid; } $pressValid = press_getUrl(); A: You don't need no wild characters for substring. function press_getUrl(){ return (strpos($_SERVER['REQUEST_URI'], "/search/node/") === 0); } However, I see no use for such a function at all. what you're trying to get? It would make sense for me if it was at least function press_check_url($check){ return (strpos($_SERVER['REQUEST_URI'], $check) === 0); } and then called if (press_check_url("/search/node/"))... but I am not sure of the use of this function. also a note on the name. your function return no urls. so, don't use "get" in it's name. and don't mix naming conventions. A: This code checks if string starts with /search/node/: if (strpos($current_url, "/search/node/") === 0){$valid = false;} A: No, you cannot. Use strpos() or similar for that example. If you want to do more complex matching (wildcards in the middle of strings, et cetera), you can use regular expressions. A: You just search for position of /search/node, if position != 0, this statements fails if (0 === strpos($current_url, "/search/node/")) return false; else return true;
{ "language": "en", "url": "https://stackoverflow.com/questions/7524374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check next string in the list Trying to figure out how to check the next string vs. the current string in a loop (pseudo code): string currentName = string.Empty; for(int i=0; i < SomeList.Count; i++) { currentName = SomeList[i].Name; //do some other logic here if(string.Compare(SomeList[i].Name, SomeList[i+1].Name) == 0) // do something } this does not seem to work: if(string.Compare(SomeList[i].Name, SomeList[i+1].Name) I want to see if the current string is the same as what the next string in the loop before it gets to the next iteration in the loop. A: You are close. You will get an IndexOutOfRangeException when you get to the last element because you are attempting to check the following element (inherently, there is none). Just change for(int i=0; i < SomeList.Count(); i++) to for(int i=0; i < SomeList.Count() - 1; i++) A: It's probably throwing an IndexOutOfRangeException, isn't it? You have to watch your boundary case at the upper end: if (i != SomeList.Count - 1 && string.Compare(SomeList[i].Name, SomeList[i+1].Name) == 0) { // Do something } A: I would suggest that you bump the index counter to start at 1, and do the comparison to SomeList[i-1], SomeList[i] so that you don't get an IndexOutOfRangeException. Also, this is case sensitive matching, call the ToUpper() method to ensure to do case insensitive matching.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DB2: How to print few columns with conversion along with all other columns without having to write all the names of the columns? I have a table having 10 columns, with id, f_name, l_name ..... low_range, high_range, ... I want to write a query which will print all my table, but just this low_range and high_range to be converted in hex. I know two things: 1. We can write all the column names and replacing the low_range with hex(low_range) and high_range with high_range. but this asks me two to write all the column names, which seems a bit unfair. 2. We can write a query like: select t.*, hex(low_range), hex(high_range) from table t But it will give all the column names first and then the required fields in hex also after them, which I don't want to as there is a repetition of information. Is there any other clean way to achieve this thing. PS: I am new to databases. A: In short, no. The two ways you list are the only two ways to specify column output order, so you can either: * *select t.* and then append your custom fields to the end (or the beginning) OR *List each field individually eg select t.field1, t.field2, hex(t.field3), t.field4... The two methods you describe are the only ways to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Axis2 : How AxisServlet is invoking the skelton part? I am developing webservices using Apache Axis2 (1.5) version . I have developed a war file for webservice client . And Deployed my Webservice in (.aar) format into axis2.war services directory. This is working fine , but i could not understand the flow how my servlet (client ) is invoking the stub and in turn calling the skelton . I have seen AxisServlet is responsible for this . Could anybody please tell me , how this invoking happens A: It is a bit complicated one. Axis2servlet is considered as the transport receiver and this picture shows flow in abstract[1]. This article[2] and the referenced links also provides some information about that. You can read those articles and have some debugging your selves to understand that properly. [1] http://i.stack.imgur.com/C7t54.png [2] http://wso2.org/library/articles/extending-axis2
{ "language": "en", "url": "https://stackoverflow.com/questions/7524400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OutOfMemoryError : When receiving XML response of 2.3 MB Following is simple method that connects to web service and receives the XML response from server which is about 2.3MB and I'm getting OutOfMemoryError (I've referred this) but not being able to find my way, stuck badly public synchronized String getUpdates(boolean news) throws Exception { String response = null; HttpPost httppost; DefaultHttpClient httpclient; ResponseHandler <String> res=new BasicResponseHandler(); List<NameValuePair> nameValuePairs; httppost = new HttpPost(context.getString(R.string.SYNCURL)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setContentCharset(params, "UTF-8"); String lastupdate = null; SharedPreferences preferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); lastupdate = preferences.getString(LAST_UPDATE, DatabaseHelper.updateDate); if(news) lastupdate = preferences.getString(LAST_UPDATE_NEWS, lastupdate); httpclient = new DefaultHttpClient(params); nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("reqDTTM", lastupdate)); if(news)nameValuePairs.add(new BasicNameValuePair("doAction", "news")); if(!preferences.getString(LAST_UPDATE, "").equalsIgnoreCase(DatabaseHelper.updateDate)) { String timezon = UDFHelper.getTimeZon(context); nameValuePairs.add(new BasicNameValuePair("tz", timezon)); } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost, res); return response; } Here it causes problem trying to retrieve large text in String response : response = httpclient.execute(httppost, res); I'm storing the response in String. Is that a problem? What is alternative solution of that? Here is LogCat 09-23 10:07:31.654: INFO/ActivityManager(59): Displayed activity uk.co.dodec.rcgpapp/.SplashScreen: 1267 ms (total 1267 ms) 09-23 10:07:35.854: INFO/dalvikvm-heap(334): Grow heap (frag case) to 3.213MB for 262160-byte allocation 09-23 10:07:38.203: INFO/dalvikvm-heap(334): Grow heap (frag case) to 3.586MB for 524304-byte allocation 09-23 10:07:42.753: INFO/dalvikvm-heap(334): Grow heap (frag case) to 4.336MB for 1048592-byte allocation 09-23 10:07:52.024: INFO/dalvikvm-heap(334): Grow heap (frag case) to 5.836MB for 2097168-byte allocation 09-23 10:08:09.844: INFO/dalvikvm-heap(334): Grow heap (frag case) to 8.836MB for 4194320-byte allocation 09-23 10:08:09.864: INFO/ActivityManager(59): Process com.android.mms (pid 227) has died. 09-23 10:08:45.984: INFO/dalvikvm-heap(334): Forcing collection of SoftReferences for 8388624-byte allocation 09-23 10:08:46.033: ERROR/dalvikvm-heap(334): Out of memory on a 8388624-byte allocation. 09-23 10:08:46.033: INFO/dalvikvm(334): "AsyncTask #1" prio=5 tid=7 RUNNABLE 09-23 10:08:46.033: INFO/dalvikvm(334): | group="main" sCount=0 dsCount=0 s=N obj=0x43e54fd8 self=0x224d58 09-23 10:08:46.033: INFO/dalvikvm(334): | sysTid=340 nice=10 sched=0/0 cgrp=bg_non_interactive handle=2248344 09-23 10:08:46.033: INFO/dalvikvm(334): | schedstat=( 1248172861 2043417240 1093 ) 09-23 10:08:46.033: INFO/dalvikvm(334): at org.apache.http.util.CharArrayBuffer.expand(CharArrayBuffer.java:~59) 09-23 10:08:46.033: INFO/dalvikvm(334): at org.apache.http.util.CharArrayBuffer.append(CharArrayBuffer.java:77) 09-23 10:08:46.033: INFO/dalvikvm(334): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:136) 09-23 10:08:46.033: INFO/dalvikvm(334): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146) 09-23 10:08:46.033: INFO/dalvikvm(334): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:76) 09-23 10:08:46.033: INFO/dalvikvm(334): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59) 09-23 10:08:46.033: INFO/dalvikvm(334): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657) 09-23 10:08:46.033: INFO/dalvikvm(334): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627) 09-23 10:08:46.033: INFO/dalvikvm(334): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616) 09-23 10:08:46.033: INFO/dalvikvm(334): at uk.co.dodec.rcgpapp.helper.HttpHelper.getUpdates(HttpHelper.java:172) 09-23 10:08:46.033: INFO/dalvikvm(334): at uk.co.dodec.rcgpapp.SplashScreen.getUpdate(SplashScreen.java:155) 09-23 10:08:46.033: INFO/dalvikvm(334): at uk.co.dodec.rcgpapp.SplashScreen$getUpdates.doInBackground(SplashScreen.java:126) 09-23 10:08:46.033: INFO/dalvikvm(334): at uk.co.dodec.rcgpapp.SplashScreen$getUpdates.doInBackground(SplashScreen.java:1) 09-23 10:08:46.043: INFO/dalvikvm(334): at android.os.AsyncTask$2.call(AsyncTask.java:185) 09-23 10:08:46.043: INFO/dalvikvm(334): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 09-23 10:08:46.043: INFO/dalvikvm(334): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 09-23 10:08:46.043: INFO/dalvikvm(334): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 09-23 10:08:46.043: INFO/dalvikvm(334): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 09-23 10:08:46.043: INFO/dalvikvm(334): at java.lang.Thread.run(Thread.java:1096) 09-23 10:10:37.353: WARN/dalvikvm(334): threadid=7: thread exiting with uncaught exception (group=0x4001d800) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): FATAL EXCEPTION: AsyncTask #1 09-23 10:10:37.375: ERROR/AndroidRuntime(334): java.lang.RuntimeException: An error occured while executing doInBackground() 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at android.os.AsyncTask$3.done(AsyncTask.java:200) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at java.lang.Thread.run(Thread.java:1096) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): Caused by: java.lang.OutOfMemoryError 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at org.apache.http.util.CharArrayBuffer.expand(CharArrayBuffer.java:59) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at org.apache.http.util.CharArrayBuffer.append(CharArrayBuffer.java:77) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:136) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:76) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at uk.co.dodec.rcgpapp.helper.HttpHelper.getUpdates(HttpHelper.java:172) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at uk.co.dodec.rcgpapp.SplashScreen.getUpdate(SplashScreen.java:155) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at uk.co.dodec.rcgpapp.SplashScreen$getUpdates.doInBackground(SplashScreen.java:126) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at uk.co.dodec.rcgpapp.SplashScreen$getUpdates.doInBackground(SplashScreen.java:1) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at android.os.AsyncTask$2.call(AsyncTask.java:185) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 09-23 10:10:37.375: ERROR/AndroidRuntime(334): ... 4 more 09-23 10:10:37.393: WARN/ActivityManager(59): Force finishing activity uk.co.dodec.rcgpapp/.SplashScreen I've tried following not worked HttpResponse r = httpclient.execute(httppost); HttpEntity entity = r.getEntity(); InputStream in = new ByteArrayInputStream(EntityUtils.toByteArray(entity)); File fl = new File(Environment.getDataDirectory().toString() + "/data/" + context.getPackageName() + "/" + FOLDER_NAME); if(!fl.exists()) fl.mkdir(); String PATH = Environment.getDataDirectory().toString() + "/data/" + context.getPackageName() + "/" + FOLDER_NAME + "/" + "update.xml"; FileOutputStream f = new FileOutputStream(PATH); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = in.read(buffer)) > 0) { f.write(buffer, 0, len1); } f.close(); A: That is indeed a problem: don't do that. You should write the response to a file or parse the stream but definitely don't try generating a 2.3 MB string. Write a response handler that returns the HttpEntity behind the response, then get the InputStream using the getContent method, then save that to a file and then process the file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why Ruby array[array.length, count] returns []? Possible Duplicate: Is there some kind of unseen Array termination in Ruby? Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com) a = %w[a b c] a[3, 1] # => [] a[4, 1] # => nil Could anyone explain why a[3, 1] returns []? Why not nil instead? Thank you. A: Well, looks like Ruby core documentation only mark this as "special case". According to The Ruby Programming Language(O'Reilly,2008), the comment on this case is: a[arr_len, len] #=> [], empty array right at the end a[arr_len + 1, len] #=> nil, nonthing beyond that No further explanation is given. So I think you should just remember the "special case".
{ "language": "en", "url": "https://stackoverflow.com/questions/7524404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Button keeps force closing on me? My imageview thing keeps closing on me. XML code: this is my code that places the button <Button android:id="@+id/sound" android:src="@drawable/test" android:layout_width="fill_parent" android:layout_height="fill_parent" /> Java code: where I have the the code for the button and it says image1.setOnClickListener(this); is that is force closing it in the logcat. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); main = new LinearLayout(this); main.setBackgroundColor(Color.BLACK); main.setLayoutParams(new LinearLayout.LayoutParams(320,480)); viewA = new TextView(this); viewA.setBackgroundColor(Color.WHITE); viewA.setTextColor(Color.BLACK); viewA.setTextSize(15); viewA.setLayoutParams(new LinearLayout.LayoutParams(320,180)); main.addView(viewA); setContentView(main); Button image1 = (Button) findViewById(R.id.sound); image1.setOnClickListener(this); } public void onClick(View v) { switch(v.getId()){ } } My entire code: if you need to see it so you can tell whats going on package dev.mrunknow.slidedirection; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.MotionEvent; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import android.view.View; public class SlideDirection extends Activity implements View.OnClickListener{ /** Called when the activity is first created. */ private LinearLayout main; private TextView viewA; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); main = new LinearLayout(this); main.setBackgroundColor(Color.BLACK); main.setLayoutParams(new LinearLayout.LayoutParams(320,480)); viewA = new TextView(this); viewA.setBackgroundColor(Color.WHITE); viewA.setTextColor(Color.BLACK); viewA.setTextSize(15); viewA.setLayoutParams(new LinearLayout.LayoutParams(320,180)); main.addView(viewA); setContentView(main); Button image1 = (Button) findViewById(R.id.sound); image1.setOnClickListener(SlideDirection.this); } public void onClick(View v) { switch(v.getId()){ } } float x_start = 0, y_start = 0, x_end = 0, y_end = 0; @Override public boolean onTouchEvent(MotionEvent event) { viewA.setText(""); viewA.setLayoutParams(new LinearLayout.LayoutParams(320,80)); viewA.setTextSize(40); int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN) { x_start = event.getX(); y_start = event.getY(); } if(action == MotionEvent.ACTION_UP) { x_end = event.getX(); y_end = event.getY(); if((x_start - x_end) > 75 && (y_start - y_end) < -75) { viewA.setText("LEFT"); Toast.makeText(this, "Left Works!", Toast.LENGTH_SHORT).show(); } if((x_start - x_end) < -75 && (y_start - y_end) < -75) { viewA.setText("RIGHT"); Toast.makeText(this, "Right Works!", Toast.LENGTH_SHORT).show(); } } return true; } } A: Why you taking risk by extending at the same time implementing OnClickListener.. why not to make an inner class like this. class click implements OnCLickListener{ @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stubdo your stuff } } and instead of image1.setOnClickListener(SlideDirection.this); add image1.setOnClickListener(new click()); A: public void onClick(View v) { if(v==image1) { //your logic } } A: please make change in onCreate() method like below and it work fine. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); main = new LinearLayout(this); main.setBackgroundColor(Color.BLACK); main.setLayoutParams(new LinearLayout.LayoutParams(320,480)); viewA = new TextView(this); viewA.setBackgroundColor(Color.WHITE); viewA.setTextColor(Color.BLACK); viewA.setTextSize(15); viewA.setLayoutParams(new LinearLayout.LayoutParams(320,180)); // add button programmatically not from xml the change that i have suggest you image1 = new Button(this); image1.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon)); image1.setLayoutParams(new LinearLayout.LayoutParams(320,180)); main.addView(viewA); main.addView(image1); setContentView(main); // Button image1 = (Button)findViewById(R.id.sound); image1.setOnClickListener(this); } A: As you are creating your activity view dynamically, and you have added no Button into your activit's view, so it will always return null and as a result, exception will be raised and your application would crash...
{ "language": "en", "url": "https://stackoverflow.com/questions/7524405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to retrieve the particular X th position of node using xpath? This is my Xml Document. <w:document> <w:body> <w:p>para1</w:p> <w:p>para2</w:p> <w:p>para3</w:p> <w:p>para4</w:p> <w:p>para5</w:p> <w:p>para6</w:p> <w:p>para7</w:p> <w:p>para8</w:p> <w:p>para9</w:p> <w:p>para10</w:p> </w:body> </w:document> Now, i want to retrieve the text of 7th .ie,Para7. How do i get it? A: You can index into an XPath expression using [] brackets. For example, you might use //w:p[7] to access the 7th element. Note that XPath indexing is 1-based indexing not 0-based indexing. A: Use: /*/*/*[7]/text() If you have registered the namespaces correctly with your XPath engine's API, you can use: /w:document/w:body/w:p[7]/text() Note: Be aware that there are problems using the [] operator together with the // pseudo-operator: in this specific simple case the expression //w:p[7] selects the wanted element, however in general it selects every w:p element that is the 7th (in document order) w:p child of its parent. So, when evaluated against this document: <w:document xmlns:w="w:w"> <w:body> <a> <w:p>para1</w:p> <w:p>para2</w:p> <w:p>para3</w:p> </a> <b> <w:p>para4</w:p> <w:p>para5</w:p> <w:p>para6</w:p> <w:p>para7</w:p> <w:p>para8</w:p> <w:p>para9</w:p> </b> <w:p>para10</w:p> </w:body> </w:document> the expression //w:p[7] selects nothing. However, when evaluated against this document: <w:document xmlns:w="w:w"> <w:body> <a> <w:p>para1</w:p> <w:p>para2</w:p> <w:p>para3</w:p> <w:p>para4</w:p> <w:p>para5</w:p> <w:p>para6</w:p> <w:p>para7</w:p> <w:p>para8</w:p> </a> <b> <w:p>para9</w:p> <w:p>para10</w:p> <w:p>para11</w:p> <w:p>para12</w:p> <w:p>para13</w:p> <w:p>para14</w:p> <w:p>para15</w:p> </b> </w:body> </w:document> the same expression selects: <w:p xmlns:w="w:w">para7</w:p> <w:p xmlns:w="w:w">para15</w:p>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detecting when FLVPlayback source is bad or not found I'm totally at a loss as to how to detect if my instance of FLVPlayback component has been handed a source that either doesn't exist or it can't play for one reason or another. I've attached handlers to every event I can think of... specifically... videoPlayer.addEventListener(VideoEvent.COMPLETE, vidEnd); videoPlayer.addEventListener(VideoEvent.READY, vidStart); videoPlayer.addEventListener(VideoEvent.PLAYHEAD_UPDATE, vidMoved); videoPlayer.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); videoPlayer.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); But none of those fire when the clip is missing or corrupted. I also tried this: try{ videoPlayer.source = "http://localhost:18888/" + folder + "/" + nextUrl; }catch(e:VideoError){ trace("http://localhost:18888/" + folder + "/" + nextUrl + " couldn't be found"); playNextItem(); } But that doesn't work either. I'm totally stumped. What's the correct way to do this? TIA A: If you can, don't use FLVPlayback, because it does too many "magic" things behind the scenes and is a bit buggy. It's basically just a wrapper around the VideoPlayer class. If you have to use FLVPlayback, you can access the VideoPlayer being wrapped with FLVPlayback.getVideoPlayer, then listen to VideoState.STATE_CHANGE and monitor VideoPlayer.state. If it's VideoState.CONNECTION_ERROR, it means your video feed cannot be loaded or played.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I escape HTML entities in XML so that they are displayed literally on a web page? I have an XML descriptor file containing attribute specifications such as: <attribute name="abc" description="xyz e.g. &lt;br&gt; with a new line"> ... </attribute> These XML descriptors are parsed by a groovy script to produce HTML documentation (among other things) along the lines of: <table> <tr><th>Name</th><th>Description</th></tr> <tr><td>abc</td><td>xyz e.g. <br>with a new line</td></tr> </table> My question is what do I have to put in the XML to display HTML entities as character literals? e.g. A less than sign, such as: <table> <tr><th>Name</th><th>Description</th></tr> <tr><td>abc</td><td>You must supply a &lt;port number&gt;</td></tr> </table> (The groovy script does no processing on the XML description - just prints it into the HTML file.) A: Escape the ampersands in the HTML entities so you get the following: <attribute name="abc" description="You must supply a &amp;lt;port number&amp;gt;"> ... </attribute> The attribute value will then be seen by the Groovy script as: You must supply a &lt;port number&gt; A: You can simply replace '&' to '&amp;' to work around it. Here is the code: <div id="d"></div> <script type='text/javascript'> var str = "<table><tr><th>Name</th><th>Description</th></tr><tr><td>abc</td><td>You must supply a &amp;lt;port number &amp;gt;</td></tr></table>"; document.getElementById('d').innerHTML = str; </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: joomla 1.7 - how to create rss feed for my content? is it possible to create the feed for joomla website? what is the way?? the joomla doc page dont hv the related page yet http://docs.joomla.org/How_to_create_component_feeds what i mean is creating the rss using the contents of my joomla webiste but not displaying other's rss feed in my joomla website i saw that joomla administration panel have something call rss content, but it is only used for displaying rss feed, but not creating , am i right? thx A: This will work for Joomla 1.6, Joomla 1.7, and Joomla 2.5 RSS feeds are only available for the following: -- A Category -- Featured Articles CATEGORY FEED In the Joomla Admin you can get any category ID in the Category Manager, you can construct the feed url yourself even if it has no menu item on your website: RSS: http://YOUR_SITE/index.php?option=com_content&view=category&id=YOUR_CATEGORY ID&format=feed&type=rss ATOM: http://YOUR_SITE/index.php?option=com_content&view=category&id=YOUR_CATEGORY ID&format=feed&type=atom FEATURED ARTICLE FEED RSS: http://YOUR_SITE/index.php?option=com_content&view=featured&format=feed&type=rss ATOM: http://YOUR_SITE/index.php?option=com_content&view=featured&format=feed&type=atom MAKING A FEED FROM A CATEGORY BLOG MENU ITEM USING SEF LINKS You can also simply navigate to a category blog or featured blog menu item that is already created and has friendly URL's which show just the SEF alias' copy it and add ?format=feed&type=rss or ?format=feed&type=atom. Here is an example: http://YOUR_SITE/ALIAS/?format=feed&type=rss http://YOUR_SITE/ALIAS/?format=feed&type=atom FULL TEXT OR INTRO TEXT? In each menu item configuration you have "Integration Options" in the right panel that allow you to decide if you want that item to show the full text or just the intro text as well as show/hide the "read More.." link. Also, you can set a global setting for Full/Intor text from the Article Manager. In the admin, simply navigate to the Article Manager and click on the "Options" icon in the upper right of the screen and go to the "Integration" tab. A: If you are just trying to have an RSS feed from your articles in your Joomla installation, that is done automatically for you. Joomla generates a RSS feed for every menu item that links to a category and for the items with the menu item type "frontpage" (or "featured" in case of Joomla 1.6/1.7) The link to the RSS feed is already in the header of those pages and can be used directly. If you developed your own component, you have to write your own RSS view for that component. I'd say the best way would be to look at the RSS view of com_content for that. A: Bij default the RSS syndication creates a master category, you can find in your category manager. What i did: create a menu, give it one item: a category blog and then choose RSS as category. Publish this menu with a menu module. Then click the rss menu item and you will retrieve the rssfeed url, and then go back to module manager and give yor module a non existing position like yagrooble or whatever. Your RSS is hidden but the link still works!
{ "language": "en", "url": "https://stackoverflow.com/questions/7524417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Programmatically alignment? I've attached one image. In that image one checkbox and spinner are in undefined position. I'm using Absolute layout but also, i can't fix that to wherever. So, i need to set those by programmatically. Is this possible? Anyone help me. Thanks in Advance. A: Praveen It would be helpful if you put up your XML file. Any way absolute layout class has been deprecated try using frame layout or RelativeLayout. Absolute layouts are less flexible and harder to maintain than other types of layouts without absolute positioning.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Questions regarding C3P0 Pooled Data Source I tried to use Pooled Data source to log information regarding database connection pool i.e, Max pool size, current no. of connections in use, busy connection etc. I am using C3P0Registry to get pooled data source. PooledDataSource dataSource =null; try{ C3P0Registry.getNumPooledDataSources(); //I am sure that I am using only one data source Iterator<Set> connectionIterator = C3P0Registry.getPooledDataSources().iterator(); dataSource = (PooledDataSource)connectionIterator.next(); }catch (Exception e) { } and then i am logging required information as: Logger.write(LoggerConstant.DEBUG, " Connections in use: "+dataSource.getNumConnectionsAllUsers()+" , Busy Connections: "+dataSource.getNumBusyConnectionsAllUsers() +" , Idle Connections: "+ dataSource.getNumIdleConnectionsAllUsers()+" , Unclosed Orphaned Connections: "+ dataSource.getNumUnclosedOrphanedConnectionsAllUsers(), methodName); I want to know that if its a correct way to achieve my goal?. Plus i am having confusions regarding What does dataSource.getNumConnectionsAllUsers() and other function (i am using) exactly return. There is no description available in javadoc. Is there any description or may be tutorial available online from where i can learn more about these particular functions? Environment: Java, Hibernate, C3P0, MySQL A: try read PooledDataSource java doc. http://www.mchange.com/projects/c3p0/apidocs/com/mchange/v2/c3p0/PooledDataSource.html PooledDataSource.getXXXXUser() is correct way of monitor and manage data source The functionality in this interface will be only be of interest if * *for administrative reasons you like to keep close track of the number and status of all Connections your application is using; *to work around problems encountered while managing a DataSource whose clients are poorly coded applications that leak Connections, but which you are not permitted to fix; *to work around problems that may occur if an underlying jdbc driver / DBMS system is unreliable. . also There is description on method names available in javadoc. see Method Names ... section Many methods in this interface have three variants: * *< method-name> DefaultUser() *< method-name> (String username, String password) *< method-name> AllUsers() The first variant makes use of the pool maintained for the default user -- Connections created by calls to the no argument getConnection(), the second variant lets you keeps track of pools created by calling getConnection( username, password ), and the third variant provides aggregate information or performs operation on all pools.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Lazy loading reference implementation Being impressed by Guava's computing map feature, I'm searching for a sort of "computing reference" - a lazy loading reference implementation that parallel's Guava's ease of use, by which I mean it handles all locking, loading, and exception handling under the hood, only exposing a get() method. After a brief search turned up nothing, I quickly rolled my own as a proof of concept: public abstract class ComputingRef<T> implements Callable<T> { private volatile T referent = null; private Lock lock = new ReentrantLock(); public T get() { T temp = referent; if (temp == null) { lock.lock(); try { temp = referent; if (temp == null) { try { referent = temp = call(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new RuntimeException(e); } } } } finally { lock.unlock(); } } return temp; } } This ComputingRef could be anonymously extended to implement call(), which functions as the factory method: ComputingRef<MyObject> lazySingletonRef = new ComputingRef<MyObject>() { @Override public MyObject call() { //fetch MyObject from database and return } }; I'm not satisfied that this implementation is optimal, but it demonstrates what I'm after. I later found this example from the T2 Framework, which appears to be more complex. Now my questions are: * *How can my above code be improved? *How does it compare to the T2 example, and what advantages are offered by that example's greater complexity? *Are there other implementations of a lazy loading reference that I've missed in my search? EDIT: Updated my implementation to use a local variable as suggested by @irreputable's answer - please upvote it if you find the above example useful. A: See Suppliers.memoize(Supplier) to lazily initialize a value. A: It's the good old double-checked locking idiom. You should add a local variable for performance. In your impl, you have 2 volatile reads in the fast path (when referent is set). Check http://en.wikipedia.org/wiki/Double-checked_locking A: Anyway, here's how I would do it (and then I'd worry about performance later): public abstract class ComputingRef<T> implements Callable<T> { private final AtomicReference<T> ref = new AtomicReference<T>(); public T get() { if (ref.get() == null) { try { final T newValue = call(); if (ref.compareAndSet(null, newValue)) { return newValue; } } catch (final Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } } return ref.get(); } } The only 'snag' with this approach is that there is a race condition that could result multiple instantiations of the referent object (esp. if the ComputingRef is shared across a large number of threads that all hit get() at the same time). If instantiating the referent class is so expensive or you want to avoid multiple-instantiation at all costs, then I'd go with your double-checked locking as well. You also have to make sure that the referent object cleans up after itself. Otherwise, if the compareAndSet() fails, then make sure to perform any necessary cleanup. (Note that if the referent needs to be a singleton, then I'd use the initialization on demand holder idiom instead.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: sha1 Hash Not working? C# I am just messing around with simple hashing because I am new to the idea, and I have the following: public string Password {get;set;} public static string Hash(string password) { return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "sha1"); } public bool Authenticate(AccountDataContext context) { var password = context.UserAccounts.FirstOrDefault(p => p.UserAccountUID == UserAccountUID).Password; var hash = Hash(Password); return password.Equals(hash); } NOTE This is not production code, so I am not worried about how secure this currently is... Right now, when I originally hash the password when a user registers such as the following var password = "Password"; var hashedPassword = UserAccount.Hash(password) Then I am storing this with the user. When I am authenticating my user I would call the Authenticate() method, and I thought it would return the same hash, because it is passing the same value into the Hash() method, but they are coming out differently. Any ideas why the Hash function would return two different hashes for the same string? A: I'm not completley sure in this case but usuall you don't only hash the password but the password and some additional random noise you save beside (often called salt-value). This is done to make this all more secure than the password alone. If you only store the pwd then an attacker could just hash dictionaries and find a lot accepted passwords. I guess the same is happening here behind the scenes. Have you considered Hashing the password yourself (System.Security) instead of using the FormAuthentication-Service? Have a look at the SHA1Managed.ComputeHash-method for this. Basically you just encode your string with UnicodeEncoding.GetBytes- or whatever you want - into a byte-array and call this method to get a hashed byte-array. Than you can transform this with Convert.ToBase64String to get a string back - this is WITHOUT this salt I talked about so you might read into this before moving into production. A: The hashed result will be the same during multiple calls to the function. You might want to call String.Trim() prior to hashing to ensure there is no white space anywhere in the string prior to being hashed. Also shouldn't the snippet you posted read: public bool Authenticate(AccountDataContext context) { var password = context.UserAccounts.FirstOrDefault(p => p.UserAccountUID == UserAccountUID).Password; var hash = Hash(password); //lower case password, not Password. return password.Equals(hash); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get animated zooming and pan with openlayers? Like website:http://www.tomtom.com/livetraffic/ When I try pan or zoom on the above site, feels very good similar to Google map, it's very smoothly for this user experience. my question is how I can implement this effect with openlayers respectively for pan and zoom? I could not find them in openlayers examples at least. thanks for you attention. following is part of my source code, maybe it works but not smoothly as I think var map, layer; function init() { var options = { projection: "EPSG:900913", maxExtent: new OpenLayers.Bounds(18.203001, 47.078001, 399.909001, 261.796001), scales: [2400, 1200, 600, 300, 150], units: "m", panDuration: 100, controls: [new OpenLayers.Control.Navigation( {dragPanOptions: {enableKinetic: true}} )] var tile = new SimpleTileCache("map", "tilecache/8f/", { 'format': 'image/png', transitionEffect: 'resize' }); map.addLayers([tile]); A: For panning, that’s what’s called kinetic dragging, see: http://dev.openlayers.org/examples/kinetic.html A: Effect is called as transitionEffect You can implement this effect to your code by changing layers property. I suppose you have a WMS or TMS layer. var tiled_resize_effect = new OpenLayers.Layer.WMS( "WMS tiled resize", "http://vmap0.tiles.osgeo.org/wms/vmap0?", {layers: 'basic'}, {transitionEffect: 'resize'} ); Check these examples WMS Transition Google Transition Best Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7524431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Prolog: In a list, finding the element after a given element I recently began programming in Prolog and am currently trying to create rules that find the element after a given element in a list. For example, I want find(2,X,[1,2,3,4]). to result in 3. My attempt so far: find(X,Y,[X,Y|Tail]):- !. find(X,Y,[_|Tail]):- find(X,Y,Tail). A: Let's use if_/3 and (=)/3 (a.k.a. equal_truth/3), as defined by @false in this answer! So here comes the new, logically pure find/3: find(E0,E1,[X|Xs]) :- member_next_prev_list(E0,E1,X,Xs). member_next_prev_list(E0,E1,X0,[X1|Xs]) :- if_(X0=E0, X1=E1, member_next_prev_list(E0,E1,X1,Xs)). Let's run the queries mentioned by the OP / by other answers / by some comments: ?- find(a,X,[a,a,b]). X = a. % succeeds deterministically ?- find(a,X,[a,Y,b]). X = Y. % succeeds deterministically ?- find(a,b,[a,a,b]). false. % fails ?- find(a,X,[a,a,b,c]). X = a. % succeeds deterministically ?- find(b,X,[a,a,b,c]). X = c. % succeeds deterministically Now to something a little more general: ?- find(X,Y,[a,a,b,c]). X = a, Y = a ; X = b, Y = c ; false. What about the most general query? As the code is pure, we get logically sound answers: ?- find(X,Y,List). List = [ X,Y|_Z] ; List = [_A, X,Y|_Z], dif(_A,X) ; List = [_A,_B, X,Y|_Z], dif(_A,X), dif(_B,X) ; List = [_A,_B,_C, X,Y|_Z], dif(_A,X), dif(_B,X), dif(_C,X) ; List = [_A,_B,_C,_D,X,Y|_Z], dif(_A,X), dif(_B,X), dif(_C,X), dif(_D,X) ... Edit 2015-05-06 Here's a more concise variant, unimaginatively called findB/3: findB(E0,E1,[X0,X1|Xs]) :- if_(X0=E0, X1=E1, findB(E0,E1,[X1|Xs])). Like find/3, findB/3 is efficient in the sense of not leaving useless choicepoints behind, but it has higher memory use. findC/3 tries to reduce the memory use by hoisting the common expression [X1|Xs]: findC(E0,E1,[X0|XXs]) :- XXs = [X1|_], if_(X0=E0, X1=E1, findC(E0,E1,XXs)). A: Here's a version w/o the cut: find(X,Y,[X,Y|_]). find(X,Y,[Z|Tail]) :- X\=Z, find(X,Y,Tail). A: Here is a pure version: find(X,Y, [X,Y|_]). find(X,Y, [X0,Y0|Xs]) :- dif(X+X0,Y+Y0), find(X,Y, [Y0|Xs]). I'd rather would like to have a deterministic version, and also a pure DCG version would be cool!
{ "language": "en", "url": "https://stackoverflow.com/questions/7524433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What's stored queries in Lotus Notes? Using Design Synopsis, I found 'Stored Queries' element type but I can not find any ways to view, edit or delete these 'stored queries'. What's it? How to take control of this type of design element? A: Stored Queries are saved view searches. You can see this in action by opening a view in the database, and then perform a view search. The search bar should appear allowing you to type in a search. You should be able to select a "More" twistie on the right, the View search bar should expand down, presenting a few more options. There you'll see a number of parameters and filters for searching. There should also be 2 buttons "Save Search" and "Load Search". This is what design synopsis is referring to, the saved searches for views, but they're called "Stored Queries" by design synopsis. Selecting "Load Search" should also give you the option to "Delete Saved Search". Here is some doco on how to use it. The instructions are compatible from R6.5 thru to 8.5.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UIBarButtonItem referencing the custom view to later editing I hope this is a simple question, I have a UIBarButtonItem which I initialized using a UILabel as a custom view, the button is living inside toolbar. What I want to do is being able to change the text from the label that is inside the UIBarButtonItem, here is my code: NSDate *lastUpdateDate = [AWSyncEntity getLastUpdatedDateByEntityName:@"Patient" inManagedObjectContext:self.managedObjectContext]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];//liberar [dateFormat setDateFormat:@"MM/dd/yyyy hh:mm a"]; UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 180, 44.01)]; //liberar myLabel.font = [UIFont boldSystemFontOfSize:10]; myLabel.textColor = [UIColor whiteColor]; myLabel.backgroundColor = [UIColor clearColor]; myLabel.text = [NSString stringWithFormat:@"Actualizado: %@", [dateFormat stringFromDate:lastUpdateDate]]; UIBarButtonItem *btn2 = [[UIBarButtonItem alloc] initWithCustomView:myLabel]; //liberar UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; //liberar self.toolbarItems = [NSArray arrayWithObjects:flexibleSpace,btn2, flexibleSpace, nil]; [self.navigationController setToolbarHidden:NO animated:YES]; UIBarButtonItem *mybtn = (UIBarButtonItem *)[self.toolbarItems objectAtIndex:2]; //I was thinking this would be possible... //UILabel *mylbl = (UILabel *) [mybtn view]; [flexibleSpace release]; [btn2 release]; [myLabel release]; [dateFormat release]; I have no idea how to gain reference to the inner view of the button again, any clues? I was thinking on doing something like this: (but it is not working). //I was thinking this would be possible... //UILabel *mylbl = (UILabel *) [mybtn view]; A: The label is the customView of bar button, UILabel *mylbl = (UILabel *)[mybtn customView]; A: UILabel *myLbl = (UILabel *) [mybtn customView]; that should do it but I haven't tested it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where to save project related text files? For testing and debugging purposes, I just hard-coded the file paths for the text files that would be used by my application, e.g. const string CONFIG_FILE_PATH = @"C:\myconfigfile.txt"; But I don't think it's a good idea to leave it as it is in the Beta/Release version. So I am wondering, what would be the best location for saving these configuration files that will be used / read by the application? Any suggestions? Many Thanks. A: Why not save the strings in the Settings section of your project? GRight click on your project in Solution Explorer, select Properties, go to the Settings section and add a new string with your file path. Then, in your code, you can access it like this: using ProjectName.Properties; var path = Settings.Default.MySetting; To change the setting: Settings.Default.MySetting = newPath; Settings.Default.Save(); A: In the same folder as the executable. But you should consider using a Settings class (you can read more here). Visual Studio can automatically create a strongly typed wrapper around a section in the app.config file. The settings are stored in the same file as the executable, but can be overridden (and saved from the application) in a matching file in the user profile for each user. A: Another option: If the test config file is intended to sit along side your executable, you can "Add" "Existing Item..." to your project and then change its properties to "Copy always" or "Copy if newer". During debugging, the executable should be able to find the copy of the config in its current working directory. This isn't such a useful solution when there's a lot of testing to do. A: For settings I would certainly use the app.config file. This is proposed by Microsoft and apart from that it is pretty much the easiest way to handle application settings anyway. For other files I'd recommend either the applications local or roaming settings path, depending on weather you only need the data local or not. For compact, local databases I tend to use this approach. The application directory, as suggested by Albin, is a bad idea. You cannot be sure that the user is actually allowed to write to that directory and/or files in that directory (i.e. the app was pre-installed by an admin with elevated rights). To get the location of the local paths use ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal) and for the roaming path ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming) More information on Windows User Profiles (the actual paths in different versions of Windows for example, you can find here: http://msdn.microsoft.com/en-us/library/aa372123.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7524437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I find out how many objects are in a list basically what the title says. I want to be able to find out how many objects a list contains. Maybe my Google-fu is failing me or my terminology is wrong. A: len(s) Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary). >>> l = [1, 2, 3] >>> len(l) 3 A: Check out the len built-in function: len(someList) http://docs.python.org/library/functions.html#len A: a = ['1', '2', '3'] print len(a) This wiil print: 3
{ "language": "en", "url": "https://stackoverflow.com/questions/7524439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble loading project references during build within wpf user control library As an example of a build time assembly load issue, consider the following class library code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Data.Sql; namespace ClassLibrary1 { public class Class1 { SqlDatabase database; } } And the following class code in a wpf user control library: using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClassLibrary1; namespace WpfControlLibrary1 { class Class1 { } } The WpfControlLibrary1 has a project reference to ClassLibrary1, but using ClassLibrary1; reference fails. A different project type can load ClassLibrary1 just fine, and if the Enterprise Library 5.0 SqlDatabase declaration is commented out, the wpf library can load ClassLibrary1. Any ideas on what this issue is or how to track it down? Thanks! A: One possible cause is that WpfControlLibrary1 is targeting .NET Client Profile, but one of the other libraries (e.g. Enterprise Library) is targeting the full profile. You can check the "Target framework" setting in the project properties dialog, in the "Application" tab. You can see more details about the .NET Client Profile at http://msdn.microsoft.com/en-us/library/cc656912.aspx, or about changing the target at http://msdn.microsoft.com/en-us/library/bb398202.aspx.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: cakePHP - project was working on localhost but not on website I have some project in cakePHP which was working on localhost but when I deployed it on internet its not working ... I feel theere is some issue with .htaccess.. Please help. Thanks in advance content of my htaccess <IfModule mod_rewrite.c> RewriteEngine on RewriteRule favicon\.ico$ favicon.ico [NC,L] RewriteRule (img|css|js|files|stats)/(.*)$ $1/$2 [NC,L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?url=$1 [QSA,L] </IfModule> A: I assume this is a shared hosting environment. I would recommend deploying without .htaccess rewriting support and see if things work. You can find the configuration in app/config/core.php. /** * To configure CakePHP *not* to use mod_rewrite and to * use CakePHP pretty URLs, remove these .htaccess * files: * * /.htaccess * /app/.htaccess * /app/webroot/.htaccess * * And uncomment the App.baseUrl below: */ Configure::write('App.baseUrl', env('SCRIPT_NAME'));
{ "language": "en", "url": "https://stackoverflow.com/questions/7524443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split a column value into two columns in a SELECT? I have a string value in a varchar column. It is a string that has two parts. Splitting it before it hits the database is not an option. The column's values look like this: one_column: 'part1 part2' 'part1 part2' So what I want is a a result set that looks like: col1,col2: part1,part2 part1,part2 How can I do this in a SELECT statement? I found a pgsql function to split the string into an array but I do not know how to get it into two columns. A: select split_part(one_column, ' ', 1) AS part1, split_part(one_column, ' ', 2) AS part2 ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7524445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: issue with threading and facebook single sign on I am using Facebook iOS SDK to do the single sign on. Now when the app first launch I have a modal view controller showing the login page with 2 buttons, login with twitter and Facebook. When I press on login the Facebook dialog box shows up.. and it says that I have authenticated the app. So I click on OK. Then it goes back to the login view controller and when dismissing it, I got this: *** Terminating app due to uncaught exception 'NSRangeException', reason: '<MKMapView: 0x2d1720; frame = (1.2941e-09 0; 4.70638e-36 1.66881e-07); transform = [1.6714e-07, 4.70638e-36, 1.67031e-07, 4.70647e-36, 0, 0]; alpha = 0; opaque = NO; layer = (null)> initWithCoder:: MKMapView must be initialized on the main thread.' *** Call stack at first throw: This does not happen if I log out from facebook first, so then I have to enter my username and password and then login. How is this possible? A: U missing a line mapView = [[MKMapView alloc]init]; When it comes back to your view after facebook login put this where first your application function is called ie ViewDidLoad.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Naming constants which are part of a formula For my C++ class, the instructor said he will give a score of zero to any program submitted with magic numbers. He said, even for formulas such as calculating the area of a circle (where it is common knowledge that 3.14159 is the value of Pi, we should either use a const variable or a #define directive to represent Pi and then use that in the formula). With that said, I'm doing a financial calculation where I am determining the amount of a bill before tax. A snipet from the function is: mealCostBeforeTax = billAmount / (1.0 + taxRate_); The taxRate_ is an argument passed to the function as a decimal percent (e.g. 0.08). So in order to determine the amount before the tax, I have to add 1 to the taxRate making it 1.08. My question is, since to the instructor 1.0 is a magic number. What is an appropriate name for that value? This leads also to another question. When I am using formulas, is there a resource or a direction I can be pointed with help in understanding what certain constants in functions are called, or what they represent. For example, when converting a temperature from Celsius to Fahrenheit, the formula is Tf=(9/5)*Tc+32. How does one find out what 9/5 represents as well as the 32. I would assume that 32 is the freezing point of water on the Fahrenheit scale, but that is just a guess. The 9/5 I would imagine is some kind of ratio between the scales, but these are guesses. Sorry for the wall of text. But I really wanted to write a thorough question so that hopefully others may find it useful. A: All in all, I think calling the 1.0 in this formula a magic number is a little extreme. Not every literal number is necessarily a magic number. The point is to make your code readable such that the person looking at it won't have to guess why you picked that number out of thin air. In this case, I think the solution would be to wrap the calculation in a function instead of trying to come up with a #define for the 1. God help me if I ever see another program where you have a statement like #define one 1 because a programmer is following the letter of the magic number rule and not the intent. float getPreTaxCost(float totalCost, float taxRate); { return totalAmount / (1.0 + taxRate); } Especially for common formulas like converting F to C, this just makes sense. As a rule of thumb, if there is an obvious name for a constant/define that is used in a calculation definitely use it instead of a naked number in the code. However, don't force the issue to extremes. I'd confirm this assumption with your prof, of course.. They can be pretty pedantic to the point of absurdity because they live in the theory and not the real world and often demand adherence to strict rules because they are rules forgetting the reason behind them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the rationale for small stack even when memory is available? Recently, I was asked in an interview, why would you have a smaller stack when the available memory has no limit? Why would you have it in 1KB range even when you might have 4GB physical memory? Is this a standard design practice? A: The other answers are good; I just thought I'd point out an important misunderstanding inherent in the question. How much physical memory you have is completely irrelevant. Having more physical memory is just an optimization; it prevents having to use disk as storage. The precious resource consumed by a stack is address space, not physical memory. The bits of the stack that aren't being used right now are not even going to reside in physical memory; they'll be paged out to disk. But as soon as they are committed, they are consuming virtual address space. A: The smaller your stacks, the more of them you can have. A 1kB stack is pretty useless, as I can't think of an architecture that has pages that small. A more typical size is 128kB-1MB. Since each thread has its own stack, the number of stacks you can have is an upper limit on the number of threads you can have. Some people complain about the fact that they can't create more than 2000 threads in a standard 2GB address space of a 32-bit Windows process, so it's not surprising that some people would want even smaller stacks to allow even more threads. Also, consider that if a stack has to be completely reserved ahead of time, it is carving a chunk out of your address space that can't be returned until the stack isn't used anymore (i.e. the thread exits). That chunk of reserved address space then limits the size of a contiguous allocation you can make. A: I don't know the "real" answer, but my guess is: * *It's committed on-demand. *Do you really need it? If the system uses 1 MiB for a stack, then a typical system with 1024 threads would be using 1 GiB of memory for (mostly) nothing... which may not be what you want, especially since you don't really need it. A: One reason is, even though memory is huge these days, it is still not unlimited. A 32-bit process is normally limited to 4GB of address space (yes, you can use PAE to increase that, but that requires support from the OS and a return to a segmented memory model.) Each thread uses up some of that memory for its stack, and if a stack is megabytes in size -- whether it's paged in or not -- it's taking up a significant part of the app's address space. The smaller the stack, the more threads you can squeeze into the app, and the more memory you have available for everything else. Ideally, you want a stack just large enough to handle all possible control flows through the thread, but small enough that you don't have wasted address space. A: There are two things here. First, the limit on the stack size will put the limit on number of processes/threads in the system. And then too, the limit is not because of the size of physical memory but because of the limit on addressable virtual memory. Secondly, rarely processes/threads need more stack size then that, and if they do, they can ask for it (libraries handle this seamlessly). So, when starting a new process/thread, it makes sense to give them a small stack space. A: Other answers here already mention the core concept, that the most significant consumed resource of a stack is address space (since its implementation requires chunks of contiguous address space) and that the default space consumed on windows for each thread is not insignificant. However the full story is extremely nuanced (and can and will change over time) over many layers and levels. This article by Mark Russinovich as part of his "Pushing the limits of Windows" series goes into extremely detailed levels of analysis. The work is in no way an introductory article though, and most people would not consider it the sort of thing that would be expected to be known in a job interview unless perhaps you were interviewing for a job in that particular field. A: Maybe because everytime you call a function the OS has to allocate memory to be the stack of that function. Because functions can chain, several function calls will incur more stack allocations. A large default stack size, like 4GiB, would be impractical. But that's just my guess...
{ "language": "en", "url": "https://stackoverflow.com/questions/7524453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SMPP BIND ERROR: 0x0000000D in EasySMPP I am implementing the SMPP client using EasySMPP for .NET The application is compiling fine but there was no successful outcome and I am getting this weird error SMPP BIND ERROR: 0x0000000D What can be done for this, please help. A: The error code of 0x0000000D is unfortunately a rather generic "Bind Failed". To find out what the error codes mean check section 5.1.3, command_status, of the SMPP specification you linked to. Common causes for getting a "Bind Failed" response are: * *Your supplier only allows certain IP addresses to connect *Trying to connect to wrong hostname/port combination *Wrong username/password To troubleshoot, you could try running Wireshark on your client and take a look at the SMPP PDUs being passed backwards and forwards, if you post the capture on here I'm happy to take a look. Or you could give your supplier a call, they may be able to see something helpful in their server logs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does TFS 2010 support Optimistic locking? Does anyone know that whether TFS 2010 support optimistic locking or only pessimistic locking? A: Yes, TFS 2010 supports optimistic locking. Files are not exclusively locked; multiple users can have the same file checked out simultaneously. Conflicts are resolved through merging files upon check-in. However, if the file is "non-mergable" (images, audio, etc), it will be exclusively locked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Moving ASP.NET 1.1 site to IIS 7 I am trying to move an asp.net 1.1 site that is currently hosted on a dying server with IIS 6 to a new server with IIS 7. I've setup everything with IIS to get the asp.net 1.1 app pool and classic mode and all that good stuff. When I access the site though, I keep getting Parser Error Could not load type 'XXX.Type <%@ Page Language="vb" AutoEventWireup="false" Codebehind="default.aspx.vb" Inherits="XXX.Type" EnableViewState="False" %> I don't have access to the source code. What should I do to get this running? I appreciate any help. A: Looks like you're missing dll in a bin folder for the XXX.Type class which default.aspx.vb inherits from
{ "language": "en", "url": "https://stackoverflow.com/questions/7524465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Struts2 Spring Hibernate Jar file conflict I am developing a sample application in Struts2+Spring+Hibernate .. When i add jar for struts2 , Spring and Hibernate in my lib folder.. Its not running. Its because of jar files conflict.. Is there anyway to select correct jar files for these technologies ???? If i upgrade a jar with new version, it makes error.. Is there anyway to tell what are all the jar files should i include(update) when i change(update) a jar file. If i add struts2-core-2.2.3.1.jar and xwork-core-2.1.6-jdk14.jar in simple struts2 application.. Struts tags are not working. Thanks in advance A: I got similar problem I solved it using JarJar. http://code.google.com/p/jarjar/ using this you can repackage the jars. What you have to do is to repackage all the hibernate and its supporting jars in to one jar. Similarly you can repackage Struts with its supporting versions of jars. For example commos-logging is used hibernate and Struts but different version you can solve the problem by JarJar..
{ "language": "en", "url": "https://stackoverflow.com/questions/7524466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python binary tree serializing problem I have a binary tree class as below: class BTree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def __unicode__(self): return "%s" % self.data and I have another tree serializing method listed as below: class JTree(object): def __init__(self, id, children=None): self.id = id if children is None: children=[] self.children = children def encode_tree(obj): if not isinstance(obj, JTree): raise TypeError("%r is not JSON serializable" % (o,)) return obj.__dict__ then I populate the Binary Tree data as below: bt = BTree("1") bt.left =BTree("2") bt.right=BTree("3") so if I serialize the data, I can get the following result: tree = JTree(bt.data, [JTree(bt.left.data), JTree(bt.right.data)]) print json.dumps(tree, default=encode_tree) {"id": "1", "children": [{"id": "2", "children": []}, {"id": "3", "children": []}]} The problem is that I can't figure out how to program a piece of code to generate the result. Which means I want to have a generator or recursive function to run the code: JTree(bt.data, [JTree(bt.left.data), JTree(bt.right.data)]) Can somebody give me an idea? Thanks A: It seems to me that you want a simple recursive function like: def convert_to_jtree(bt): return JTree(bt.data, [convert_to_jtree(bt.left) if bt.left else None, convert_to_jtree(bt.right) if bt.right else None]) or something very similar. A: The json module can only serialize dicts, lists, strings, numbers, booleans and None. Instead of using custom classes for this, consider using plain-ol dicts. Alternately, you can subclass json.JsonEncoder and override the default method so that it returns one of those types for your custom class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Adding Navigator Support for a custom programming Language in Netbeans API I'v added support for a custom programming Language as described in Netbeans (using ver 7.0) I want to add Navigator Support for that too but i can't find a gud place/ gud example to start with [link]]1 But i want it to display in such a way that when we click on navigator nodes, it shud goto the corresponding place in editor.. eg: if in my language, suppose value1 is there and value1 has to be displayed in nav tree under val_imp..Plz tell me hw to do this too..:-( And once itz shown, whenever i click on the nodes, i wanna go to the corresponding place where value1 is there in editor.. [PS:I'm new to NetBeans APIs but gud with java..] Thanks in Advance... Rahul Chandran
{ "language": "en", "url": "https://stackoverflow.com/questions/7524472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to handle home button event on Android Actually, in my app, I want to call a function when the user clicks the home button. Can anyone suggest to me how that can be done? A: Okay, this was supposed to be a hard question. But here is a way to crack it. Override the below method in your Activity, @Override public void onAttachedToWindow() { super.onAttachedToWindow(); this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); } And now handle the key event like this, @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_HOME) { Log.i("Home Button","Clicked"); } if(keyCode==KeyEvent.KEYCODE_BACK) { finish(); } return false; }; A: Android does not allow to override the home button, its restriction that android does not allow to let you override the home button A: The only way to handle the home button action is by creating a home replacement activity. This is an activity with action 'main' and category 'home'. This is for security issues, to prevent applications from locking users. A: If you just want to to run some code when the home button is pressed, the you can place that code in onPause() since this method will always be called before the home screen is launched. Insert this code inside your activity. @Override protected void onPause() { // your code here, // Note: should not be anything that takes too long time to execute super.onPause(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does "let () = " mean in Ocaml? There are codes like let () = print_string "something" in fn in some OCaml codes. What does this mean? Is there special meaning on "()"? or Is it same meaning as print_string "something"; fn A: Jeffrey's answer is absolutely correct, but one more point: if you write fx "something"; fn And you messed up the result type of fx "something" the compiler will emit a Warning, that might get lost during compilation. On the other hand if you write: let () = fx "something" in fn The compiler will type check that the result of fx "something" can be matched against (), i.e. that it is really of type unit. Thus if you messed up an error is produced, which is usually more secure. There also is the possibility to write let _ = fx "something" in fn which will only get the precedence effect that Jeffrey mentioned, but not do any type checking, since _ can be matched against values of any type. A: There's nothing special about () in this let expression, it's just a pattern. All let expressions look like let pattern = expression in other-expression. Here the pattern will always match, because print_string returns unit, and () is the only value of that type. In this way, it's just another way of combining two expressions into one when the first one is really more of a statement (returns unit). So you're right, the construct has pretty much the same meaning as using the ; operator. The only real difference is in the precedence. If, for example, you write if x < 3 then print_string "something"; f x you would find that f x is always called. The precedence of ; is too low to pull the second expression under the control of the if. That's the reason many people (including me) get into the habit of using let () = expression. If you write the above as if x < 3 then let () = print_string "something" in f x the f x is only called when x is less than 3, which is usually what I want. In essence, the precedence of let is much higher than ;. Of course there are may other ways to get this effect, but the nice thing about using let is that you don't have to add anything later on in the code (like a closing parenthesis or an end). If you're adding the print_string as a debugging statement, this is a handy way of keeping the changes local to the one spot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Variables in Classes I stumbled across a very wired error in php: class A { public $var = "test"; public function __construct() { $this->var = "test2"; $b = new B; $b->method(); } } class B extends A { public function method() { $c = new C; $c->method(); } } class C extends B { public function method() { echo $this->var; } } $a = new A; I get the output "test", but I do not know why, cause the variable var should be overwritten in Class A. If I output $var in Class A it says "test2", if I output it in Class B it says "test"… A: The code on your question won't work because of the circular references (eg: $b = new B in A's constructor), which will cause PHP to run out of memory. You really shouldn't be instantiating children classes in a parent class. That being said, by what you are describing, it sounds like you are defining a constructor in B, which overrides the parent constructor. In PHP children classes don't implicitly call the parent constructor (unlike in languages like Java). So, it just inherits the original value for $var (ie: "test"), which is never changed. If you are overriding __construct() in B, you'll have to explicitly call the parent constructor, like: class B extends A { public function __construct() { parent::__construct(); } } And that should give you "test2" when you do something like: $b = new B; echo $b->var; See this demo: http://ideone.com/Q9Bp8 What is the best way to have 3 classes, where the third and second can access variables of the first class? The answer is, it depends on what you are doing. It sounds like you are not understanding how OOP works, which is a bigger problem. In general you only use inheritance when the children classes could reuse code from the parent class, and/or there is some sort of is-a or has-a relationship. If your classes don't fit this model, just make the 3 classes independent, and hold a reference to the first class in your other classes. For example: class A { public $n = 0; public function change($n) { $this->n = $n; } } class B { public function __construct($a) { $this->my_a = $a; } public function get() { return $this->my_a->n; } } $a = new A(); $b = new B($a): echo $b->get(); // 0 $a->change(10); echo $b->get(); // 10 See this demo: http://codepad.org/xL1Dzs0W
{ "language": "en", "url": "https://stackoverflow.com/questions/7524496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create Java Map of fixed-length array values? I have a program which needs to store a couple of simple int values and associate each with a String key. Currently I initialize this member like so: private Map<String, int[]> imageSizes = new HashMap<String, int[]>(); and then append to it with something like imageSizes.put("some key", new int[]{100, 200}); My question is this - is there a way to give these values a fixed length? I will only ever need 2 elements in each. Java doesn't like the syntax if I try to give the arrays a length in the member definition. Furthermore, is there any benefit to restricting the array length in this case, or am I just being overzealous in my optimisation? A: You could wrap it in a simple, reuseable and self-documenting class: public class Size { private int width; private int height; public Size(int width, int height) { this.width = width; this.height = height; } public int getWidth() { return width; } public int getHeight() { return height; } // Add setters if necessary. } And use it as follows: Map<String, Size> sizes = new HashMap<String, Size>(); sizes.put("some key", new Size(100, 200)); // ... A: You could use a class the extends HashMap and provides this special functionality: public class ImageHashMap extends HashMap<String, int[]> { public void putArray(String key, int a, int b) { put(key, new int[]{a, b}); } } To call: ImageHashMap im = new ImageHashMap(); im.putArray("some key", 100, 200); A: new int[] is only legal in a construction where the array elements follow in braces and the compiler can count how many. In the Map, the amount of memory used for the values is just the size of the reference (32 or 64 bits), no matter how large the array is itself. So fixing the size of the array won't change the amount of memory used by the map. In C, you could declare a pointer and then allocate more or less memory to it (or forget to allocate any and crash); Java manages memory for you. A: In addition to Bohemian's solution, you might want to protect the original put method from HashMap like this: @Override public int[] put(String key, int[] value) { throw new UnsupportedOperationException("Sorry, operation not allowed."); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: random string in python I am trying to make a script that will generate a random string of text when i run it. I have got far but im having a problem with formatting. Here is the code im using import random alphabet = 'abcdefghijklmnopqrstuvwxyz' min = 5 max = 15 name = random.sample(alphabet,random.randint(min,max)) print name And when ever i end up with this ['i', 'c', 'x', 'n', 'y', 'b', 'g', 'r', 'h', 'p', 'w', 'o'] I am trying to format so it is one line of string so for example ['i', 'c', 'x', 'n', 'y', 'b', 'g', 'r', 'h', 'p', 'w', 'o'] = icxnybgrhpwo A: join() it: >>> name = ['i', 'c', 'x', 'n', 'y', 'b', 'g', 'r', 'h', 'p', 'w', 'o'] >>> ''.join(name) 'icxnybgrhpwo' A: import string import random def create_random(length=8): """ Create a random string of {length} length """ chars = string.letters + string.digits return ''.join(random.Random().sample(chars, length)) A: An easy way to print an alphabet : >>> import string >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' (source)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: tabactivity - content of all tabs gets overlapped at first I was testing TabActivity with a list in each tab. While running the app, the contents of the tabs gets overlapped like this. After i click on the tabs the overlapping gets cleared. Here is my code : testtabs.xml layout : <?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/list1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"> </ListView> <ListView android:id="@+id/list2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"> </ListView> </FrameLayout> </LinearLayout> </TabHost> And Test Activity public class TabbedActivity extends TabActivity { private static final String LIST1_TAB_TAG = "List1"; private static final String LIST2_TAB_TAG = "List2"; private ListView listView1; private ListView listView2; private TabHost tabHost; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.testtabs); tabHost = getTabHost(); // setup list view 1 listView1 = (ListView) findViewById(R.id.list1); // create some dummy strings to add to the list List<String> list1Strings = new ArrayList<String>(); list1Strings.add("List 11"); list1Strings.add("List 12"); list1Strings.add("List 13"); list1Strings.add("List 14"); listView1.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, list1Strings)); // setup list view 2 listView2 = (ListView) findViewById(R.id.list2); List<String> list2Strings = new ArrayList<String>(); list2Strings.add("Test2 List 21"); list2Strings.add("Testing 22"); list2Strings.add("More test 23"); list2Strings.add("Test Again 24"); listView2.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list2Strings)); // add views to tab host tabHost.addTab(tabHost.newTabSpec(LIST1_TAB_TAG).setIndicator(LIST1_TAB_TAG).setContent(new TabContentFactory() { public View createTabContent(String arg0) { return listView1; } })); tabHost.addTab(tabHost.newTabSpec(LIST2_TAB_TAG).setIndicator(LIST2_TAB_TAG).setContent(new TabContentFactory() { public View createTabContent(String arg0) { return listView2; } })); tabHost.setCurrentTab(0); } } A: You can remove both ListView from xml layout and just create them in java code. e.g. listView1 = new ListView(this); Everything will be Ok. A: Another solution I found is to add the following tag to both the listviews in the layout XML file: android:visibility="invisible" A: You are taking two ListView's in a FrameLayout that is the reason for your over-lapping. If you want that you should have one ListView below the other keep the ListView's inside the LinearLayout like this, <?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/list1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"> </ListView> <ListView android:id="@+id/list2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"> </ListView> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP: Difference between -> and :: Possible Duplicate: In PHP, whats the difference between :: and ->? In PHP, what is the main difference of while calling a function() inside a class with arrow -> and Scope Resolution Operator :: ? For more clearance, the difference between: $name = $foo->getName(); $name = $foo::getName(); What is the main profit of Scope Resolution Operator :: ? A: * *-> is called to access a method of an instance (or a variable of an instanciated object) *:: is used to access static functions of an uninstanced object A: $name = $foo->getName(); This will invoke a member or static function of the object $foo, while $name = $foo::getName(); will invoke a static function of the class of $foo. The 'profit', if you wanna call it that, of using :: is being able to access static members of a class without the need for an object instance of such class. That is, $name = ClassOfFoo::getName(); A: They are for different function types. -> is always used on an object for static and non-static methods (though I don't think it's good practice use -> for static methods). :: is only used for static methods and can be used on objects (as of PHP 5.3) and more importantly classes. <?php class aClass { static function aStaticMethod() {} function aNormalMethod() {} } $obj = new aClass(); $obj->aNormalMethod(); //allowed $obj->aStaticMethod(); //allowed $obj::aStaticMethod(); //allowed as of PHP 5.3 $class_name = get_class( $obj ); $class_name::aStaticMethod(); //long hand for $obj::aStaticMethod() aClass::aStaticMethod(); //allowed //aClass::aNormalMethod(); //not allowed //aClass->aStaticMethod(); //not allowed //aClass->aNormalMethod(); //not allowed
{ "language": "en", "url": "https://stackoverflow.com/questions/7524503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Android Layout decision and its implication on performance I have two layouts one is main and other is listview used when user clicks some button. Which is better in perfomance, to use two separate activity for both layouts or have to implement both in same activity. 2.And my main activity extends Activity but to display listview i need to extend ListActivity so if i extend ListActivity app is forceclosing , may be cause I'm tryin to load linear layout first. So what's solution ? A: There is no definite answer regarding performance. Having a simple activity perform two actions may impose some runtime overhead, while having two different activities will imply an increase in code size. If I were you I wouldn't bother about performance, and I would choose whatever solution is better design-wise (probably creating two activities, but you never can tell). Note that extending ListActivity is not needed in order to display a ListView in an activity, its just a convenience. If it weren't, then people would have lots of trouble trying to come with activities displaying more than a single ListView. A: I think, using a single activity for both the tasks will be better. You can perform the task of displaying and loading data in ListView in a separate thread avoiding the UI to stuck...
{ "language": "en", "url": "https://stackoverflow.com/questions/7524512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to implement synchronization with timers in C# I have a scenario where my C# class has two methods say DoThis() and DoThat() that are called independent of each other, in any order, by an external caller. The two methods need to be synchronized in the following way: * *After a call to DoThis(), wait at least t1 seconds before proceeding with DoThat() execution *After a call to DoThat(), wait at least t2 seconds before proceeding with DoThis() execution So essentially in pseudocode: static SomeCustomTimer Ta, Tb; static TimeSpan t1, t2; public static void DoThis() { if(Tb.IsRunning()) Tb.WaitForExpiry(); DoStuff(); Ta.Start(t1); } public static void DoThat() { if(Ta.IsRunning()) Ta.WaitForExpiry(); DoOtherStuff(); Tb.Start(t2); } DoStuff() and DoOtherStuff() are not long-running methods and do not share resources otherwise. Typically DoThis() and DoThat() will not be called concurrently. But I still need to protect against potential deadlocks. How can I best implement DoThis(), DoThat() in C#? EDIT My scenario right now is simple in that there aren't an arbitrary number of threads calling these functions. For purpose of simplification, there's a single caller thread calling these functions in an arbitrary sequence. So the two methods will not be called concurrently, instead the caller will call these methods one-by-one in any order. I don't have control over the caller thread's code so I want to enforce the delay between successive calls to DoThis(), DoThat(). A: This is pretty easy to solve with a timed latch. A latch is synchronization mechanism that is either opened or closed. When open threads are allowed to pass through. When closed threads cannot get through. A timed latch is one that will automatically reopen or reclose after a certain amount of time has elapsed. In this case we want a "normally opened" latch so the behavior is biased towards staying open. That means the latch will reopen automatically after the timeout, but close only if Close is explicitly called. Multiple calls to Close will reset the timer. static NormallyOpenTimedLatch LatchThis = new NormallyOpenTimedLatch(t2); static NormallyOpenTimedLatch LatchThat = new NormallyOpenTimedLatch(t1); static void DoThis() { LatchThis.Wait(); // Wait for it open. DoThisStuff(); LatchThat.Close(); } static void DoThat() { LatchThat.Wait(); // Wait for it open. DoThatStuff(); LatchThis.Close(); } And we can implement our timed latch like the following. public class NormallyOpenTimedLatch { private TimeSpan m_Timeout; private bool m_Open = true; private object m_LockObject = new object(); private DateTime m_TimeOfLastClose = DateTime.MinValue; public NormallyOpenTimedLatch(TimeSpan timeout) { m_Timeout = timeout; } public void Wait() { lock (m_LockObject) { while (!m_Open) { Monitor.Wait(m_LockObject); } } } public void Open() { lock (m_LockObject) { m_Open = true; Monitor.PulseAll(m_LockObject); } } public void Close() { lock (m_LockObject) { m_TimeOfLastClose = DateTime.UtcNow; if (m_Open) { new Timer(OnTimerCallback, null, (long)m_Timeout.TotalMilliseconds, Timeout.Infinite); } m_Open = false; } } private void OnTimerCallback(object state) { lock (m_LockObject) { TimeSpan span = DateTime.UtcNow - m_TimeOfLastClose; if (span > m_Timeout) { Open(); } else { TimeSpan interval = m_Timeout - span; new Timer(OnTimerCallback, null, (long)interval.TotalMilliseconds, Timeout.Infinite); } } } } A: Hm..What do you need in that case: One Thread calls DoThis some time in succession. Another can run DoThat at least t2 seconds after LAST calling of DoThat or the first one after last calling DoThat? I think, If your target platform is Win then It is better to use WaitableTimer (however, It is not realized in .NET but you can use It through API. You need to define those functions: [DllImport("kernel32.dll")] public static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName); [DllImport("kernel32.dll")] public static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref long pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume); [DllImport("kernel32", SetLastError = true, ExactSpelling = true)] public static extern Int32 WaitForSingleObject(IntPtr handle, int milliseconds); public static uint INFINITE = 0xFFFFFFFF; And then using It as follow: private IntPtr _timer = null; //Before first call of DoThis or DoThat you need to create timer: //_timer = CreateWaitableTimer (IntPtr.Zero, true, null); public static void DoThis() { //Waiting until timer signaled WaitForSingleObject (_timer, INFINITE); DoStuff(); long dueTime = 10000 * 1000 * seconds; //dueTime is in 100 nanoseconds //Timer will signal once after expiration of dueTime SetWaitableTimer (_timer, ref dueTime, 0, IntPtr.Zero, IntPtr.Zero, false); } public static void DoThis() { //Waiting until timer signaled WaitForSingleObject (_timer, INFINITE); DoOtherStuff(); long dueTime = 10000 * 1000 * seconds; //dueTime is in 100 nanoseconds //Timer will signal once after expiration of dueTime SetWaitableTimer (_timer, ref dueTime, 0, IntPtr.Zero, IntPtr.Zero, false); } And after using you may destroy timer by calling CloseHandle. A: Okay I'm trying out a possible solution to this problem using EventWaitHandle. Looking for comments / feedback. Can this work reliably? // Implementation of a manual event class with a DelayedSet method // DelayedSet will set the event after a delay period // TODO: Improve exception handling public sealed class DelayedManualEvent : EventWaitHandle { private SysTimer timer; // using SysTimer = System.Timers.Timer; public DelayedManualEvent() : base(true, EventResetMode.ManualReset) { timer = new SysTimer(); timer.AutoReset = false; timer.Elapsed +=new ElapsedEventHandler(OnTimeout); } public bool DelayedSet(TimeSpan delay) { bool result = false; try { double timeout = delay.TotalMilliseconds; if (timeout > 0 && timer != null && Reset()) { timer.Interval = timeout; timer.Start(); result = true; Trace.TraceInformation("DelayedManualEvent.DelayedSet Event will be signaled in {0}ms", delay); } } catch (Exception e) { Trace.TraceError("DelayedManualEvent.DelayedSet Exception {0}\n{1}", e.Message, e.StackTrace); } return result; } private void OnTimeout(object source, ElapsedEventArgs e) { if (timer != null) { timer.Stop(); Trace.TraceInformation("DelayedManualEvent.OnTimeout Event signaled at time {0}", e.SignalTime); } try { if (!Set()) { Trace.TraceError("DelayedManualEvent.OnTimeout Event set failed"); } } catch (Exception ex) { Trace.TraceError("DelayedManualEvent.OnTimeout Exception in signaling event\n{0}]\n{1}", ex.Message, ex.StackTrace); } } protected override void Dispose(bool disposing) { if (timer != null) { timer.Dispose(); } base.Dispose(disposing); } } The way I'm planning to use this: // Pseudocode static DelayedManualEvent delayedEvent = new DelayedManualEvent(); static TimeSpan t1, t2, maxTimeout; public static void DoThis() { if(!delayedEvent.WaitOne(maxTimeout)) return; DoStuff(); delayedEvent.DelayedSet(t1); } public static void DoThat() { if(!delayedEvent.WaitOne(maxTimeout)) return; DoOtherStuff(); delayedEvent.DelayedSet(t2); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SQL NOT IN needs double layers? I'm writing code to hit a tree structure which is persisted in a MySQL database, each node storing the ID of its parent or NULL if it's the root of the tree. In the course of querying it to try to get all leaf nodes, I noticed something odd. Namely, this query produces no results: SELECT * FROM tree_table WHERE node_id NOT IN(SELECT parent_node_id FROM tree_table) while this one produces the results I'm after: SELECT * FROM tree_table WHERE node_id NOT IN( SELECT node_id FROM tree_table WHERE node_id IN(SELECT parent_node_id FROM tree_table)) It seems to be the NOT that's giving me the trouble. Is this something about order of operations or similar that I'm misremembering? A: If SELECT parent_node_id FROM tree_table returns a single NULL amongst it's result set, then the rest of the query SELECT * FROM tree_table WHERE node_id NOT IN(SELECT parent_node_id FROM tree_table) will produce no results. See NOT IN clause and NULL values (one of many related questions)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change Master Page Content without loading page multiple times I have Master and Content Page.The Layout is like Header and Footer are in Master page and rest contents are in content/child page. Now I want to change the header and footer of master page dynamically.To do this,I have coded Page_load event of master page. But Actual problem comes that when Master page's header and footer changes,the page loads multiple times.. Is there any way to solve this problem.. I want to change header and footer of master page for specific time without refreshing content page. I have seen many post, but i did not find any accurate answer.. My code is : this is the page_load event of master page .. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DIVHeader.InnerHtml = obj.getHeaderHTMLFinal(); DIVFooter.InnerHtml = obj.getFooterHTMLFinal(); } } A: Where do you want to change the footer on the Master Page? You could wrap the header and footer in ContentPlaceholder controls and adjust them in client pages directly. You can also interact with the Master Page in client pages in code behind via the Page.Master property. A: Try to use an updatepanel. You can update the content of the panel without reload the whole page. If in your header or footer you do not have controls that triggers an update then you can manual trigger the update of the panel from code behind using conditional update. hope that helped.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I switch between existing activities? I am designing an app which is a kind of articles reader & manager and articles available in different languages. So when user reads a particular article in Russian there is a button to display the same article in English and vice versa. To do that I start new activity. What I have now is that if user presses "translate" button of the same article several times there will be heaps of duplicate activities. What I need to achieve is that when user first "translates" Russian article to English, then presses "translate" button in an English article, the app returns him to existing activity displaying Russian Article and does not start a new Activity. Here is a code which does not do what I need to illustrate my attempts. intent.putExtra("BookID", strBookID ); intent.putExtra("ChapterNum", mCurrChapterNum ); intent.putExtra("TextNum", mCurrTextNum ); try{ if (Central.LastBookID.equals("")) { //remember current article id Central.LastBookID=strBookID; Central.LastChapter=mCurrChapterNum; Central.LastText=mCurrTextNum; } else { if (Central.LastChapter.equals(mCurrChapterNum) && Central.LastText.equals(mCurrTextNum) ) intent.addFlags(Intent. FLAG_ACTIVITY_REORDER_TO_FRONT); } startActivity(intent); Please give me some advice, maybe it would be better to implement it differently? From what I managed to read, Android does not have any "Activity ID"s so that if I have 2 activities of the same class "A" in stack but with different parameters like (A1 A2), I could tell the system to bring to front activity A1 and make it (A2 A1) A: intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); using the above flag instead will finish the prevoius one and starts the new one. so no heap of Activities and no extra logic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: samsung galaxy ace and trying to pair my mobile with MOb-58 printer I have written Bluetooth program in android it working fine. But when I am trying to run my apk in samsung galaxy ace and trying to pair my mobile with MOb-58 printer it will ask 4 to 5 times the same password for pairing. A: The problem may be in your connectivity. You may running the code of connectivity until it gets connected. Instead of that you can make a method and put the connectivity code there. And after that just call the Outputstream to print the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: has_many :through usage, simple, beginner question I am writing a simple accounting system for managing costs. The structure is like this: Invoice - can have many products Product - can have many costs, also can act_as_tree LineItem - Product LineItem LineItem Product LineItem Product LineItem LineItem I had this set up as a has_many and belongs_to for the three classes but think that the following is more appropriate (based upon reading Rails 3 Way - any shortcomings are my lack of understanding; just trying to give context) Class Invoice < ActiveRecord::Base has_many :products has_many :line_items, :through => :products end Class Product < ActiveRecord::Base belongs_to :invoice belongs_to :line_item end class LineItem < ActiveRecord::Base has_many :products has_many :invoices, :through => :invoices end But I don't this is working correctly. if I do the following: >@i=Invoice.find(1) >@i.products # this works >@i.line_items # doesn't work, unidentified method line_items This is the first time I'm using has_many :through. Is this set up correctly for my data model? Also, is it possible to use it in conjunction with acts_as_tree - I'd like to be able to say: >@i.line_items and get back all the line items for that specific invoice. Possible? thx for help A: First a question: What is your relation between Product and LineItem: Has 1 product many line items or is 1 and the same line item referenced in many products? The rest of this answer is based on the assumption that every product should have multiple line items. I think your models should be defined like that: # No change Class Invoice < ActiveRecord::Base has_many :products has_many :line_items, :through => :products end # Changed the relation to :line_items Class Product < ActiveRecord::Base belongs_to :invoice has_many :line_items end class LineItem < ActiveRecord::Base belongs_to :products # The following then does not make sense ##has_many :invoices, :through => :invoices end A: why did you choose this structure? in such cases i usually do Class Invoice < ActiveRecord::Base has_many :line_items has_many :products, :through => :line_items end Class Product < ActiveRecord::Base has_many :line_items # if you need has_many :products, :through => :line_items end class LineItem < ActiveRecord::Base belongs_to :products belongs_to :invoice end this fullfills following requirements: Invoice and Product have a Many2Many relationship The relationship between an Invoice and a Product is a LineItem, which provides further information like price, amount, applied taxes, etc. You can create a LineItem by adding a Product: invoice = Invoice.create invoice.products << Product.find_by_name('awesome') A: Your Invoice should only have line items! These can be a tree structure but you should not have products directly referenced from your invoice (what if a product price changes: this would affect existing invoices!) So, to fix your structure: invoice line_item # references a product, but has its own fields (price!) line_item line_item Each line_item should reference one product using belong_to. It's your join model between invoices and products: class Invoice has_many :line_items end class LineItem belongs_to :invoice belongs_to :product acts_as_tree # (implies has_many :line_items with the parent invoice_id, etc.) end class Product has_many :line_items end This is basically all you need to build an invoice. You can think of the tree structure as being independent from the Invoice:LineItem:Product relationship. It can work as a flat list, or enhanced to become a tree. If your products normally contain other products and you need to know which children to add to the invoice when the parent product is added (as line items), you'll need to tree your products too: class Product has_many :line_items acts_as_tree end This tree structure is independent of the tree structure in line items. Remember: products can change, and this shouldn't affect existing line items in your invoices.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Routes syntax in rails 3 from rails 2 to 3 I want to change the following route syntax so that it's compatible with Rails 3.0 map.namespace(:admin, :path_prefix => 'refinery') do |admin| admin.resources :dashboard admin.disable_upgrade_message 'disable_upgrade_message', :controller => 'dashboard', :action => 'disable_upgrade_message' end A: I will give it a try. The code is taken from examples of Fernandez: The Rails 3 Way namespace :refinery, :controller :admins do resources :dashboard match 'disable_upgrade_message' => 'dashboard#disable_upgrade_message' end Just one note: Your controller should be named DashboardsController, and the routes should then be resources :dashboards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the state of JToggleButton Say I have a JToggleButton but = new JToggleButton("OK") ; Now I need the state of but when it is clicked. I mean I need to know if it's clicked or not. A: You can also use the itemListener's itemStateChanged method like follow: JToggleButton jtb = new JToggleButton("Press Me"); jtb.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { if(ev.getStateChange()==ItemEvent.SELECTED){ System.out.println("button is selected"); } else if(ev.getStateChange()==ItemEvent.DESELECTED){ System.out.println("button is not selected"); } } }); and of you want to know the state of jtb latter on use isSelected() method System.out.println(jtb.isSelected()); if(jtb.isSelected()){ System.out.println("button is selected"); } else { System.out.println("button is not selected"); } A: To respond to clicks, add an ActionListener to the JToggleButton. To find it's state, just like a JRadioButton, call it's isSelected() method. For e.g., import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import javax.swing.JToggleButton; public class ToggleTest { public static void main(String[] args) { JToggleButton toggleBtn = new JToggleButton("Toggle Me!"); toggleBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JToggleButton tBtn = (JToggleButton)e.getSource(); if (tBtn.isSelected()) { System.out.println("button selected"); } else { System.out.println("button not selected"); } } }); JOptionPane.showMessageDialog(null, toggleBtn); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: How to write a number on a TShape Component? I have a TShape Component. I need to load it dynamically and I need to place a number on that TShape. If anyone knows the way - please suggest it to me. Thanks Rakesh A: You can use the Canvas property of the TShape component to draw the number, to access this protected property you must create descendent class of TShape and publish that property or just use a interposer class. type TShape = class(ExtCtrls.TShape); //interposer class TForm1 = class(TForm) Shape1: TShape; Button1: TButton; procedure Button1Click(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin Shape1.Canvas.Font.Name :='Arial';// set the font Shape1.Canvas.Font.Size :=20;//set the size of the font Shape1.Canvas.Font.Color:=clBlue;//set the color of the text Shape1.Canvas.TextOut(10,10,'1999'); end; A: Place a TLabel above it and make its background transparent (Transparent = True). Edit text alignment if needed (Alignment := taCenter)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JqueryUI with ContentFlow coverflow javascript. Variable Error in Firefox but works in Safari I am using ContentFLow, a javascript coverflow for images, here and I am integrating jQueryUI for Themes and icons/buttons. I am specifically integrating a Play/Pause button for a slideshow and I have it working in Safari with the following code but I get an error in FireBug in Firefox, and the code fails. The FireBug error: play_slide is not defined [Break On This Error] var p = play_slide; Here is my ContentFlow Code for the play/pause function: if (conf.showControlls) { var c = document.createElement('div'); var p = play_slide; } /* toggle slideshow on and off */ flow.toggleSlideshow = function(force) { if (this._slideshow_locked) var t = "stop"; else var t = "play"; if (force) { switch (force) { case "stop": case "play": var t = force; break; } } switch (t) { case "stop": if (p) { p.removeClassName('play'); p.addClassName('pause'); p.setAttribute('title', "pause"); } this._slideshow_locked = false; this._startSlideshow(); break; case "play": if (p) { p.removeClassName('pause'); p.addClassName('play'); p.setAttribute('title', "play"); } this._slideshow_locked = true; this._stopSlideshow(); break; } }; /* add controll elements */ if (c) { p.addEvent('click', flow.toggleSlideshow.bind(flow), ''); Here is my JqueryUI code for the Play button, and to change the icon from pLay to Pause $(function() { $("#play_slide").button({ text: false, icons: { primary: "ui-icon-play" } }).click(function() { var options; if ($(this).text() === "play") { options = { label: "pause", icons: { primary: "ui-icon-pause" } }; } else { options = { label: "play", icons: { primary: "ui-icon-play" } }; } $(this).button("option", options); $(this).toggleSlideshow(); }); }); Not sure why it works in Safari and not Firefox but I obviously need some help with var p = play_slide; Any help for this novice will be appreciated! Mike A: I answered my own question. After some trial and error, changing var p to: var p = document.getElementById("play_slide"); and remove this: $(this).toggleSlideshow();
{ "language": "en", "url": "https://stackoverflow.com/questions/7524541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Displaying scrollable widget in Android We are using Ajax call to fetch a list of strings and display using a widget on JSP page developed for android web application. We are facing the issue as strings are displayed limited to the widget’s size and not scrollable in the android emulator. However, the same code works fine in Internet explorer on desktop. The css used for the above widget is: jquery-ui-1.8.13.custom.css Class in the above css specific to widget display: .ui-autocomplete { position: absolute; cursor: default; max-height: 100px; overflow-y: auto; /* prevent horizontal scrollbar */ overflow-x: hidden; /* add padding to account for vertical scrollbar */ padding-right: 20px; } The overflow-y: auto enables the vertical scrollbar in IE but the same doesn’t on Android Emulator. Any help or pointers to enable the above functionality in android would be great A: The Android browser has a bug that causes overflow:auto to be treated as overflow:hidden. http://code.google.com/p/android/issues/detail?id=2911 I'm not aware of a workaround for this; you might want to reformat the page for mobile.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: convert a string in to time format in c suppose I have a string "2011-08-21 21:48:45 +1200",and another one with the same format, I want to compare these 2 strings to find out which one is the early one or later one, is there a easy way to convert a string to time format rather than compare them by characters? Thanks A: use getdate or strptime().
{ "language": "en", "url": "https://stackoverflow.com/questions/7524543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: getAsyncKeyState not recognizing key input So I decided that I wanted to write a little keylogger tonight, just to learn about getAsyncKeyState. I'm trying to get my log to write to a file but the file's contents either show up blank or throw a random memory address at me (0x28fef0 before). I've heard that getAsyncKeyState doesn't function well with Windows 7 x64, is it true? This is pretty aggravating, I was hoping to actually be able to get this running tonight. while(1) { Sleep(20); for(DWORD_PTR key = 8; key <= 190; key++) { if (GetAsyncKeyState(key) == HC_ACTION) checkKey(key); } } Function definition void checkKey(DWORD_PTR key) { ofstream out; out.open("log.txt"); if (key==8) out << "[del]"; if (key==13) out << "n"; if (key==32) out << " "; if (key==VK_CAPITAL) out << "[CAPS]"; if (key==VK_TAB) out << "[TAB]"; if (key==VK_SHIFT) out << "[SHIFT]"; if (key==VK_CONTROL) out << "[CTRL]"; if (key==VK_PAUSE) out << "[PAUSE]"; if (key==VK_ESCAPE) out << "[ESC]"; if (key==VK_END) out << "[END]"; if (key==VK_HOME) out << "[HOME]"; if (key==VK_LEFT) out << "[LEFT]"; if (key==VK_UP) out << "[UP]"; if (key==VK_RIGHT) out << "[RIGHT]"; if (key==VK_DOWN) out << "[DOWN]"; if (key==VK_SNAPSHOT) out << "[PRINT]"; if (key==VK_NUMLOCK) out << "[NUM LOCK]"; if (key==190 || key==110) out << "."; if (key >=96 && key <= 105) { key -= 48; out << &key; // had ampersand } if (key >=48 && key <= 59) out << &key; // amp'd if (key !=VK_LBUTTON || key !=VK_RBUTTON) { if (key >=65 && key <=90) { if (GetKeyState(VK_CAPITAL)) out << &key; // amp;d else { key = key +32; out << &key; // amp'd } } } } I'm seriously stumped by this issue and any help would be greatly appreciated. Why would a function like this work differently on a 64 bit system? Considering it's the only box I've got I can't run it on a 32 bit to check whether or not it's an isolated issue. Because I'm assuming that it's related to getAsyncKeyState and not my code (which compiles and creates a blank log file) I only included those two code snippets. A: Well, firstly you don't want to be using GetAsyncKeyState if you are writing a key logger; GetAsyncKeyState gets the state of the key at the immediate moment you call the function. You need to be listening in on the Windows messages, for things like WM_KEYDOWN, WM_KEYUP, or depending on the purpose of the logger WM_CHAR, WM_UNICHAR etc... A: You're using the function incorrectly. Reading the documentation before requesting help is usually a good idea... I'll just quote MSDN here: If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior; for more information, see the Remarks. That last part also means it's completely useless for a key logger. PS: Consider using GetKeyNameText for translating virtual key codes into meaningful names. A: For monitoring input, something like a keyboard hook is probably the way to go (look up SetWindowsHookEx with WH_KEYBOARD_LL on MSDN). As noted elsewhere, you're not using GetAsyncKeyState correctly here. As for why you're seeing an address appear: out << &key; // amp'd This is several places in your code: key is a DWORD_PTR, so &key is a pointer - this is likely where the addresses are coming from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best way to embed a user's tweets and mentions into a website? I need to embed a specific user's recent tweets onto the home page of a website. The website is built in ASP.NET. I've looked at the Twitter REST API and have tried using the user_timeline. It works but does not include mentions for the user. I want to include mentions but the only way to do it seems to be by using APIs that require authentication. I would prefer not to use authentication as it seems it would start to make things more complicated. I also do not want to get the current user to authenticate. What is the best way to achieve this? A: Use the GET search API instead. Search for statuses containing the user's @username, but in this case it will not return mentions from private/locked accounts since there's no authentication. For example, if you want to search mentions for @stackexchange, call this. GET http://search.twitter.com/search.json?q=@stackexchange A: You could do a search for @username using the REST Search api. There's a good chance that would work :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: adobe air webcam problem I have been developing a simple desktop app using adobe air, html and javascript to save data to sqlite (not as, no flash builder, no flex). Is there a way that i can capture an image from my webcam and save it using these technologies ? If not what else can be done to achieve the result? Thanks in advance. A: This can be done, but it is absolutely not performance-friendly :) You will get enormous string-objects (bigger images = bigger strings). But I will tell you how I did it once. First, you have to get the BitmapData from your webcam. This can be done by creating a BitmapData-object and using its draw()-function, as shown below: var bmpd:BitmapData = new BitmapData(webcam.width, webcam.height); bmpd.draw(webcam); With this BitmapData, you can then call for getPixels(), which will return a ByteArray. var ba:ByteArray = bmpd.getPixels(); This ByteArray is now ready for serialization. Since you are storing, it is best you store it as a string. This is most commonly done by Base64. You can use this class to implement the base64-encoding, as shown below: var baseString:String = Base64.encodeByteArray(ba); The above string can be stored in your sqlite and is a string-representation of your image. The bigger the image, the longer the conversion will take. To get the image back from your sqlite, you can use the decodeByteArray()-method of the Base64-class I gave you, in combination with a loader-object. Example is shown below. var baseString = StringFromYourSQLite; var ba:ByteArray = Base64.decodeToByteArray(baseString); var imageLoader:Loader = new Loader(); imageLoader.loadBytes(ba); stage.addChild(imageLoader); And this is how you can store and retrieve images from your database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to release the system libraries allocations in iphone(Frame work related) i m facing big problem with system libraries allocations. i didn't get any leaks from my application still so much allocations.i attached various screen shoots. in my application using custom picker which get all images from assert library.which are pick from picker showing images on scroll view. its screen shot when my app with 35 images on scroll view.if again i pick images from custom picker allocation increased.i am seeing object details its all related to frame Work allocations.not from my application see the allocation object list response library is DYLD. its my leaks screen shot how can we release these allocations? please help me out ? A: make sure your application has no leaked objects and they will also disappear in instruments. For sure its pointing to a system library but it is always a result of your bugs. Select one of them and open the right view. Probably it will show you the right code stack and the allocated line of code. The other thing you can do: run the static analyzer Product->Analyze it will find all (at least most) your leaks ;) A: Just because you have no leaks doesn’t mean you are managing memory correctly. What you have is what I call memory bloat — you are retaining it longer than you need to. (A leak is allocated memory with no references. Bloat is allocated memory that has a reference but should have none.) http://www.friday.com/bbum/2010/10/17/when-is-a-leak-not-a-leak-using-heapshot-analysis-to-find-undesirable-memory-growth/ will give you some good strategies for using Instruments to find them. (This is a very credible source, so far as I know he still works at Apple.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Now able to get Id property for flex components I am not able to get the Id property for flex components in my flex application(swf file) using Test Object Inspector in Rft Tool. How can i get them? A: You can't. Flex mxml component ids are only used as a hash within the containing parent. They're only used for referencing objects and are discarded at compile time. A: If you have an id property for your flex component then there are a couple of ways to find out the id property of your desired control. Make sure you have embeded your .swf file inside an html wrapper(as suggetsed by RFT) and displaying it in an enabled IE browser. Hover over the component, say a button(and you should see automation name as well as id value). Else you can do a simple script call to get the id of desired component: System.out.println(desired_object().getProperty(".id"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7524563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# get excel data in exponential format Excel had controlled over the formatting as explained under here In my sample data (alphanumeric) in excel: - P000213590-A 312700133751-- > display as 3.127E+11 In my sample code: - DataTable dt = new DataTable("PartUpload"); DataColumn column; column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.AllowDBNull = true; column.ColumnName = "Part Original"; dt.Columns.Add(column); column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.AllowDBNull = true; column.ColumnName = "Part_ToString"; dt.Columns.Add(column); column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.AllowDBNull = true; column.ColumnName = "Part_TryParse"; dt.Columns.Add(column); string connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\seahc1\Desktop\test1.xls;Extended Properties=ImportMixedTypes=Text;Excel 8.0;HDR=Yes;IMEX=1"; OleDbConnection objConn = new OleDbConnection(connStr); objConn.Open(); OleDbDataAdapter adap = new OleDbDataAdapter(@"SELECT Part as [Part Original]FROM [Sheet1$]", connStr); adap.Fill(dt); foreach (DataRow row in dt.Rows) { row["Part_ToString"] = row["Part Original"].ToString(); double doubleConverResult; bool result = double.TryParse(row["Part Original"].ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out doubleConverResult); if (result) { row["Part_TryParse"] = doubleConverResult.ToString(); } } Part_ToString = with exponential = "3.1270013375e+011" Part_TryParse = round to nearest=312700133750 I debug and found that adap.Fill(dt) fill the datatable with data in exponential. How can I get the exact value through the C# programs because I do not want the end user to format their excel spreadsheet. Please advice, Thanks. A: I see what Crystal means. Create an Excel document and put 312700133751 number into a cell. The formatting of the cell must be "General". Excel will display 3.127E+11 instead of 312700133751. The problem is that, when you read the file with the OleDbConnection driver, the DataTable will be filled with the "3.1270013505e+011" string value (even when Excel has the "General" formatting). The problem is that 3.1270013505e+011 equals 312700133750, not 312700133751 (notice the last digit, is a zero instead of a one). This is the issue! That the OleDbConnection is "truncating" the decimals of the number up to 10 digits, which is leaving one extra digit out of the conversion. I haven't found a solution either...
{ "language": "en", "url": "https://stackoverflow.com/questions/7524573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use underscore.js reduce method? anyone got any examples on how to use the reduce method in underscore. A: They have it... http://underscorejs.org/#reduce Right there - at the official Underscore.js site. A: Here are two javascript examples, quite similar to underscore. These find the mathematical mean and the standard deviation in an array of numbers. You often see reduce working with thousands or millions of items in arrays related to populatons or statistics. Math.mean= function(array){ return array.reduce(function(a, b){return a+b;})/array.length; } Math.stDeviation= function(array){ var mean= Math.mean(array), dev= array.map(function(itm){return (itm-mean)*(itm-mean);}); return Math.sqrt(dev.reduce(function(a, b){return a+b;})/array.length); } var A2= [6.2, 5, 4.5, 6, 6, 6.9, 6.4, 7.5]; alert ('mean: '+Math.mean(A2)+'; deviation: '+Math.stDeviation(A2)) /* returned value: (String) mean: 6.0625; deviation: 0.899913190257816 */
{ "language": "en", "url": "https://stackoverflow.com/questions/7524575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery: How to calculate the maximal attribute value of all matched elements? Consider the following HTML: <div class="a" x="6"></div> <div class="a" x="9"></div> <div class="a" x="2"></div> ... <div class="a" x="8"></div> How would you find the maximal x value of all .a elements ? Assume that all x values are positive integers. A: Just loop over them: var maximum = null; $('.a').each(function() { var value = parseFloat($(this).attr('x')); maximum = (value > maximum) ? value : maximum; }); A: I got another version: var numbers = $(".a").map(function(){ return parseFloat(this.getAttribute('x')) || -Infinity; }).toArray(); $("#max").html(Math.max.apply(Math, numbers)); This uses the map function to extract the values of the x-Attributes, converts the object into an array and provides the array elements as function parameters to Math.max The Math.max trick was stolen from http://ejohn.org/blog/fast-javascript-maxmin/ UPDATE add "|| -Infinity" to process the case correctly, when no attribute is present. See fiddle of @kubedan A: Coming back to this with modern javascript: let maxA = $(".a").get().reduce(function (result, item) { return Math.max(result, $(item).attr("x")); }, 0); A: var max = null; $('.a').each(function() { var x = +($(this).attr('x')); if (max === null || x > max) max = x; } alert(max === null ? "No matching elements found" : "The maximum is " + max); Note the unary + operator to convert the attribute to a number. You may want to add some error checking to ensure it actually is a number - and that the attribute exists at all. You could change the selector to only select elements with the class and the attribute: $('.a[x]'). A: var max =0; $('.a').each(function(){ if(parseFloat($(this).attr('x'))>max) { max = parseFloat($(this).attr('x')) ; } }); alert(max); A: You could also use Array.sort in jQuery, as explained here then use $('.a:last') to get the selected element. A: I was doing some tests regarding this topic, and if performance matters, a old but gold simple for would be better than jQuery.map(), Math.apply() and also Array.sort(): var items = $(".a"); for (var i = 0; i < items.length; i++) { var val = items.eq(i).prop('x'); if (val > max) max = val; } Here are the jsperf tests: http://jsperf.com/max-value-by-data-attribute. Nothing really drastic, but interesting anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How do I get the information from a meta tag with JavaScript? The information I need is in a meta tag. How can I access the "content" data of the meta tag when property="video"? HTML: <meta property="video" content="http://video.com/video33353.mp4" /> A: document.querySelector('meta[property="video"]').content this way you can get the content of the meta. A: Way - [ 1 ] function getMetaContent(property, name){ return document.head.querySelector("["+property+"="+name+"]").content; } console.log(getMetaContent('name', 'csrf-token')); You may get error: Uncaught TypeError: Cannot read property 'getAttribute' of null Way - [ 2 ] function getMetaContent(name){ return document.getElementsByTagName('meta')[name].getAttribute("content"); } console.log(getMetaContent('csrf-token')); You may get error: Uncaught TypeError: Cannot read property 'getAttribute' of null Way - [ 3 ] function getMetaContent(name){ name = document.getElementsByTagName('meta')[name]; if(name != undefined){ name = name.getAttribute("content"); if(name != undefined){ return name; } } return null; } console.log(getMetaContent('csrf-token')); Instead getting error, you get null, that is good. A: Simple one, right? document.head.querySelector("meta[property=video]").content A: The other answers should probably do the trick, but this one is simpler and does not require jQuery: document.head.querySelector("[property~=video][content]").content; The original question used an RDFa tag with a property="" attribute. For the normal HTML <meta name="" …> tags you could use something like: document.querySelector('meta[name="description"]').content A: My variant of the function: const getMetaValue = (name) => { const element = document.querySelector(`meta[name="${name}"]`) return element?.getAttribute('content') } A: There is an easier way: document.getElementsByName('name of metatag')[0].getAttribute('content') A: function getMetaContentByName(name,content){ var content = (content==null)?'content':content; return document.querySelector("meta[name='"+name+"']").getAttribute(content); } Used in this way: getMetaContentByName("video"); The example on this page: getMetaContentByName("twitter:domain"); A: This code works for me <meta name="text" property="text" content="This is text" /> <meta name="video" property="text" content="http://video.com/video33353.mp4" /> JS var x = document.getElementsByTagName("META"); var txt = ""; var i; for (i = 0; i < x.length; i++) { if (x[i].name=="video") { alert(x[i].content); } } Example fiddle: http://jsfiddle.net/muthupandiant/ogfLwdwt/ A: Here's a function that will return the content of any meta tag and will memoize the result, avoiding unnecessary querying of the DOM. var getMetaContent = (function(){ var metas = {}; var metaGetter = function(metaName){ var theMetaContent, wasDOMQueried = true;; if (metas[metaName]) { theMetaContent = metas[metaName]; wasDOMQueried = false; } else { Array.prototype.forEach.call(document.getElementsByTagName("meta"), function(el) { if (el.name === metaName) theMetaContent = el.content; metas[metaName] = theMetaContent; }); } console.log("Q:wasDOMQueried? A:" + wasDOMQueried); return theMetaContent; } return metaGetter; })(); getMetaContent("description"); /* getMetaContent console.logs the content of the description metatag. If invoked a second time it confirms that the DOM was only queried once */ And here's an extended version that also queries for open graph tags, and uses Array#some: var getMetaContent = (function(){ var metas = {}; var metaGetter = function(metaName){ wasDOMQueried = true; if (metas[metaName]) { wasDOMQueried = false; } else { Array.prototype.some.call(document.getElementsByTagName("meta"), function(el) { if(el.name === metaName){ metas[metaName] = el.content; return true; } if(el.getAttribute("property") === metaName){ metas[metaName] = el.content; return true; } else{ metas[metaName] = "meta tag not found"; } }); } console.info("Q:wasDOMQueried? A:" + wasDOMQueried); console.info(metas); return metas[metaName]; } return metaGetter; })(); getMetaContent("video"); // "http://video.com/video33353.mp4" A: function getDescription() { var info = document.getElementsByTagName('meta'); return [].filter.call(info, function (val) { if(val.name === 'description') return val; })[0].content; } update version: function getDesc() { var desc = document.head.querySelector('meta[name=description]'); return desc ? desc.content : undefined; } A: copy all meta values to a cache-object: /* <meta name="video" content="some-video"> */ const meta = Array.from(document.querySelectorAll('meta[name]')).reduce((acc, meta) => ( Object.assign(acc, { [meta.name]: meta.content })), {}); console.log(meta.video); A: If you use JQuery, you can use: $("meta[property='video']").attr('content'); A: You can use this: function getMeta(metaName) { const metas = document.getElementsByTagName('meta'); for (let i = 0; i < metas.length; i++) { if (metas[i].getAttribute('name') === metaName) { return metas[i].getAttribute('content'); } } return ''; } console.log(getMeta('video')); A: In Jquery you can achieve this with: $("meta[property='video']"); In JavaScript you can achieve this with: document.getElementsByTagName('meta').item(property='video'); A: One liner here document.querySelector("meta[property='og:image']").getAttribute("content"); A: If you are interessted in a more far-reaching solution to get all meta tags you could use this piece of code function getAllMetas() { var metas = document.getElementsByTagName('meta'); var summary = []; Array.from(metas) .forEach((meta) => { var tempsum = {}; var attributes = meta.getAttributeNames(); attributes.forEach(function(attribute) { tempsum[attribute] = meta.getAttribute(attribute); }); summary.push(tempsum); }); return summary; } // usage console.log(getAllMetas()); A: The simple way preferred We can use direct one line to get meta description or keyword or any meta tag in head section as this code: document.head.getElementsByTagName('meta')['description'].getAttribute('content'); Just change ['description'] to keywords or element of meta name rang This is an example: using document.head to get meta names values A: I personally prefer to just get them in one object hash, then I can access them anywhere. This could easily be set to an injectable variable and then everything could have it and it only grabbed once. By wrapping the function this can also be done as a one liner. var meta = (function () { var m = document.querySelectorAll("meta"), r = {}; for (var i = 0; i < m.length; i += 1) { r[m[i].getAttribute("name")] = m[i].getAttribute("content") } return r; })(); A: FYI according to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta global attributes are valid which means the id attribute can be used with getElementById. A: Using meta root and then getting and setting any of its properties: let meta = document.getElementsByTagName('meta') console.log(meta.video.content) > "http://video.com/video33353.mp4" meta.video.content = "https://www.example.com/newlink" A: The problem with complex websites and metadata is that meta tags not always have the itemprop attribute. And in some case they have itemprop only but not a name attribute. With this script you can get all the Meta with an itemprop attribute and print its content. const allMeta = document.getElementsByTagName("meta"); for (let i = 0; i < allMeta .length; i++) { if( allMeta [i].getAttribute("itemprop") != null){ console.log( allMeta [i].getAttribute("itemprop")+":"+allMeta [i].getAttribute('content') ); } } A: if the meta tag is: <meta name="url" content="www.google.com" /> JQuery will be: const url = $('meta[name="url"]').attr('content'); // url = 'www.google.com' JavaScript will be: (It will return whole HTML) const metaHtml = document.getElementsByTagName('meta').url // metaHtml = '<meta name="url" content="www.google.com" />' A: document.head.querySelector('meta[property=video]').content; A: <html> <head> <meta property="video" content="http://video.com/video33353.mp4" /> <meta name="video" content="http://video.com/video33353.mp4" /> </head> <body> <script> var meta = document.getElementsByTagName("meta"); size = meta.length; for(var i=0; i<size; i++) { if (meta[i].getAttribute("property") === "video") { alert(meta[i].getAttribute("content")); } } meta = document.getElementsByTagName("meta")["video"].getAttribute("content"); alert(meta); </script> </body> </html> Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7524585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "225" }
Q: Is it possible to inject JavaScript that reads 'strings'? I've heard of 'injecting' JavaScript, but I'm not fully sure on what it does, or how you do it. But I'm wondering if you can inject it into a site in order to read the 'strings' or 'forms'? For example: Say there's a site that has a field for entering a name. Is there a way to inject JavaScript to make it fill the field with 'James' each time it finds a field requiring a name? Or would there be a better way to do this? A: I use this function for userscripts function ex(function_contents){ var exec_script = document.createElement('script'); exec_script.type = 'text/javascript'; exec_script.textContent = "(" + function_contents.toString() + ")()"; document.getElementsByTagName('head')[0].appendChild(exec_script); } called with ex(function(){ document.write("HELLO!"); }); A: seems you are looking for content_script or bookmarklet
{ "language": "en", "url": "https://stackoverflow.com/questions/7524587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android: reuse a RelativeLayout in XML by inflating it at run time? Edition of question It is already in a separate xml (tablet_shortterm_column.xml) see above. Anyway, it seems logcat complains that rlo_shortterm_col already has a parent, so it won't allow an another ptr_rlo_rght_middle.addView(rlo_shortterm_col ). Makes no sense. I spent so many hours on thsi problem and still can't solve it. Can someone please give me a hand? Thanks in advance. I have an xml file (tablet_shortterm_column.xml) that contains a RelativeLayout that I need to re-use, again and again. Sometimes many times on the same screen stacked one after the other horizontally. I am attempting to insert one into an existing RelativeLayout (ie. one inside the other.) //exerpts public class TabletMain extends Activity { setContentView(R.layout.tablet_main); public RelativeLayout ptr_rlo_rght_middle; ptr_rlo_rght_middle = (RelativeLayout) findViewById(R.id.rlo_rght_middle); //rlo_rght_middle is in tablet_main.xml LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View llo_tmp = (View) inflater.inflate(R.layout.tablet_shortterm_column,null); RelativeLayout rlo_tmp = (RelativeLayout) llo_tmp.findViewById(R.id.rlo_shortterm_col); // rlo_shortterm_col is the object I want to reuse it a RelativeLayout and is inside // tablet_shortterm_column.xml RelativeLayout.LayoutParams rlo_layoutparams; rlo_layoutparams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); rlo_layoutparams.addRule(RelativeLayout.RIGHT_OF, R.id.llo_rght_middle_col1); // llo_rght_middle_col1 is a RelativeLayout inside tablet_main.xml, // I want to put another RelativeLayout view right next to it. rlo_tmp.setLayoutParams(rlo_layoutparams); ptr_rlo_rght_middle.addView(rlo_tmp); //Application crashes right on this line. } //end Activity //********************* content of tablet_shortterm_column.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout android:id="@+id/rlo_shortterm_col" android:layout_width="180dp" android:layout_height="fill_parent" android:background="#436699" android:orientation="vertical" android:layout_margin="3px" android:weightSum="1" > <!-- android:background="#32CD32" android:layout_height="365dp" android:layout_margin="30px" --> <Button android:id="@+id/btn_shortterm_col" android:layout_alignParentTop="true" android:text="Tuesday Afternoon" android:layout_margin="15px" android:textSize="12px" android:textColor="#FFFFFF" android:layout_width="wrap_content" android:layout_gravity="center_horizontal" android:background="#296699" android:layout_height="wrap_content" android:layout_centerHorizontal="true" > <!--android:background="#32CD32" --> </Button> <ImageView android:id="@+id/iv_shortterm_col" android:layout_below="@+id/btn_shortterm_col" android:src="@drawable/tblet_icon14_med" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" ><!-- android:src="@drawable/tblet_shape1" android:layout_gravity="center_horizontal" --> </ImageView> <TextView android:id="@+id/tv_shortterm_col1" android:layout_below="@+id/iv_shortterm_col" android:text="-10ºC" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10px" android:background="#DCDCDC" android:textColor="#000000" android:textSize="12px" android:layout_centerHorizontal="true" > <!-- android:layout_gravity="center_horizontal" --> </TextView> <TextView android:id="@+id/tv_shortterm_col2" android:layout_below="@+id/tv_shortterm_col1" android:text="Flurries" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10px" android:background="#DCDCDC" android:textColor="#000000" android:textSize="12px" android:layout_centerHorizontal="true" > </TextView> <RelativeLayout android:id="@+id/rlo_shortterm_col_1" android:layout_below="@+id/tv_shortterm_col2" android:src="@drawable/tblet_shape2" android:background="#32CD32" android:layout_height="113dp" android:layout_margin="40px" android:layout_width="125dp" > <!--android:background="#32CD32" android:orientation="vertical" --> </RelativeLayout> </RelativeLayout> </LinearLayout> A: Create a separate xml file for your RelativeLayout and then inflate it as many times as you want. A: llo_tmp is the parent view of the RelativeLayout you're trying to reuse. Thus, you can't add it to another ViewGroup and you get that logcat error. You can remove the LinearLayout stuff from your xml file and inflate the xml file in the same way (though maybe instead of returned View you'd return a RelativeLayout). You shouldn't have to change much of the java code since the reference is still the same. Or, a quick fix may be to add llo_tmp to your ViewGroup instead of rlo_tmp. Either way, rlo_tmp already has a parent and can't be reused. Since you don't have your layout fill the entire screen width, you probably don't want this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does the C language have support for multi-threading? Since C Language does not provide any object oriented concepts, I wonder whether it also does not have support for multi-threading? I searched on the web - can anyone give me answer regarding this? A: C is un-doubtfully have multi-threading support. Check out pthread. And here is an tutorial on pthread: https://computing.llnl.gov/tutorials/pthreads/ A: With C11, the language has full support for threading, including the memory model it inherited from C++11. It has facilities for threads, condition variables, mutexes and thread local storage, for instance. Prior to C11, people typically used pthreads on unix systems and CreateThread on windows, which was supported via implementation defined behavior (not the C standard). Multithreading behavior would mostly defer to the behavior of that hardware. A: Whether a language is Object Oriented or not doesn't affect it's support for threading. Yes you can use threads with C and there are various libraries you can use to do this, pthreads being one of them. A: C1X will support threading, but right now, there is no such thing in c99. Peeople do use less portable extensions like POSIX threads (pthreads), forking etc. Standard C1X is still a draft and support from compilers is somewhat lacking, gcc partially support it, but I heard threading isnt complete yet (I mean, unstable, dev version of gcc, not 4.6). A: Check these out: * *Read pthreads *See OpenMP *Have a look at Cilk And there is no relation between multithreaded computation and object oriented features. It will depend how you design your code, which will tell if it is object oriented or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Building zxing's cpp/lib Fails under Fedora14 even when Following instructions Exactly That is, following the instructions in zxing/cpp/README, which say 'To build the library only: - Run "scons lib" in this folder (cpp)' Well, that is exactly what I did. But I get: scons lib scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... o build/core/src/zxing/BarcodeFormat.o -c -O0 -g3 -ggdb -Wall -Ibuild/core/src build/core/src/zxing/BarcodeFormat.cpp sh: o: command not found Withs this "O: command not found" repeated many times. I thought the problem might be gcc not found, so I checked for that: it is installed. I took only a brief look at the python of scons before I gave up on trying to figure ouw why it is looking for a command 'o'. Of course there is none. BTW: I got my copy of zxing 1.7 using wget only three days ago and the yum installation of 'scons' today. So they are up-to-date. A: It is likely that you are correct, and that SCons isn't finding GCC. Your best bet is to add a call to display the contents of some (or all) of the environment. As shown below, you can either pull out specific variable, or show the whole environment. The best place would probably near a call to the builder (SharedLibrary, StaticLibrary or Program). For an environment named 'env': print env.Dump() print env['CC'] print env['CXX'] Ensuring that an appropriate default environment is being used initially (probably something like): env = DefaultEnvironment( ... ) Or that the environment variables on your system (including path) are being propagated through to SCons. One way to do this is by: import os # ... env = Environment( ENV = os.environ, ... ) In extreme cases you can resolve this problem by providing an explicit path to the compiler: env['CC'] = '/usr/bin/gcc' Edit: These changes need to be made in an appropriate SConstruct or SConscript file. Which depends on the exact project, and what you're trying to achieve - in the case of the current version of zxing on google code, it would be reasonable to make the changes on or near line 40 of the SConscript file
{ "language": "en", "url": "https://stackoverflow.com/questions/7524599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to export data with Excel? From my client, I am exporting a set of details to an Excel sheet. In these details, I have a field which is of Date type. Initially, the number format for this date field was "dd-mmm-yyyy". Now, I changed it to "Date" (just to see if it works). After exporting these details to Excel, I enter values in Excel. In this date field, say, "Forecasted Date", I enter the date. Now I try to update the data in my client by reading in the Excel sheet. Suppose the Excel data is in the dataset oDSExcelData. In the process of updating, I am creating a temporary table. I am creating a dataset which has the schema of this temporary table. Let's say that this dataset is oDsTemporarytable. In oDsTemporarytable the column "Forecasted Date" is of date type datatype. In oDsExcelData, the data type of "Forecasted Date" is string. It was supposed to be of Date type. Due to this, when I try to merge these 2 datasets, I get an exception saying Mismatch in data type. Datetime is expected. I think the problem begins while reading from Excel. How can I get the datetype field from Excel?
{ "language": "en", "url": "https://stackoverflow.com/questions/7524600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: User authentication management with user token and session management in java web application i am using devise and authlogic in rails that provide all user management functionality with email sending , session management ,token generation is there any ready api available in java that provides all user login management functionality ? please suggests any idea A: I am not sure I got your question correctly.. For a user login functionality.. i assume u would need to accept user anme and password.. The UI part you will have to design.. the password encryption etc can be taken care of using MD5 or SHA or any other custom implementation. (u can refer to MessageDigest javadoc or refer to a sample implementation here http://www.spiration.co.uk/post/1199/Java-md5-example-with-MessageDigest) Mailing.. can be taken care of using java mail or apache's mailing mechanism. you can look into http://commons.apache.org/email/ for details..Reg session management, there are several ways.. cookies or maintaining session id's etc. if u are planning to generate session id's on your own.. u can use UUID api's given by java. you can refer to it. over here http://download.oracle.com/javase/1,5.0/docs/api/java/util/UUID.html .. Again.. I am sorry if this is not what you are looking for :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }