text
stringlengths
8
267k
meta
dict
Q: Restore a deleted item/items on SQLite database when back button is pressed On my app user can click an item(row) on a listview to delete the clicked item(row) that was populated from a sqlite database. Is there a way to undelete the deleted items(rows) when the user clicks the back button? A: You would need a Redo/Undo Action. Something that stores specific actions like deleting, and can undo them by undeleting or redoing by redeleting. There are a ton of tutorials out with sample code. Should be easy for a simple delete/undelete. As for using the Back button. You can add a KeyListener that overrides the default implementation and uses your code instead. It is highly discourages, I would suggest making a undo icon in the ActionBar instead. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7604520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Css for an element that allows break-word on child divs, but that can also expand to take the width of its children I'm trying to determine whether it's possible to create css for an element that supports word-wrap:break-word, but that also expands to take the width of its children when breaking is not possible. <html> <style> .outer { background-color:red; word-wrap:break-word; } </style> <div class="outer"> User generated content: <a href="http://www.google.com">http://anannoyinglylongurlthatcausesthepagetogrowtolongunlessIusewordwrapbreakwordasdfasfasdfasdfasdfasdfasdfsadfasdfadsf</a> <table> <tr> <td>asdfasdfadsffdsasdfasdfsadfafsd</td> <td>asdfasdfadsffdaasdfassdffaafasds</td> </tr> </table> <img src="http://www.google.com/intl/en_com/images/srpr/logo3w.png"/> </div> </html> In the above sample, the url breaks properly, but the table and img overflow the red outer div if the window becomes narraower than the table. If I make the outer div display:inline-block or display:table, the red outer div correctly expands to include the content, but the url doesn't break if the window is narrower than the url. I only need this to work in WebKit (on Android), and I'm trying to find a CSS only (no Javascript) solution if possible. A: If I understood what you need correctly, all you need is overflow: auto set on .outer. Here's an example: http://jsfiddle.net/hgLbh/1/ (tested on safari & chrome). Update: After your scrolling related comment I've tried a few other solutions and I've found something that satisfies even that. I'll say in advance it's dirty, but if you can handle absolutely positioned content and you are willing to duplicate the generated markup I hope it will work (at least on my local safari it does). The solution is to duplicate your content and wrap the new content in 2 other divs, so the HTML will look something like: <div class="outer-fixed"> <div class="just-a-helper-wrapper"> ... user generated content </div> </div> <div class="outer"> ... same user generated content </div> And for the CSS: .outer, .outer-fixed { background-color:red; word-wrap:break-word; position: absolute; left: 0; right: 0; } .outer-fixed { position: fixed; right: 0; } .outer-fixed * { visibility: hidden; } I'd like to point out that the just-a-helper-wrapper is required only because outer-fixed * doesn't select text nodes (ie. content that's not in another tag) - for example the string User generated content: from your example would have still been visible. If you don't actually have that kind of content, you can remove it. Here's the link: http://jsfiddle.net/hgLbh/2/ A: Assigning width: 100%; and using table-layout: fixed; forces the td cells to fit the table and will allow for text wrapping. table { width:100%; table-layout:fixed } A: I don't know about mobile webkit but this worked in Chrome http://jsfiddle.net/HerrSerker/duDTz/1/ .outer { background-color:red; word-wrap:break-word; overflow:hidden; } .outer table { width: 100%; table-layout:fixed } .outer * { max-width: 100%; } A: It seems to me that draevor has the answer, but I suspect that you don't want a scroll bar showing up in the middle of the screen on the div. If that is so, and depending on your limitations, you might try this to make the div the window: CSS html {height: 100%} body {overflow: auto; height: 100%; margin: 0;} .outer { word-wrap: break-word; background-color: red; overflow: auto; min-height: 100%; } A: Looking at the CSS spec, it's likely that what I'm trying to do is impossible, although I find the size calculations fairly difficult to decipher. Here are some important bits: http://www.w3.org/TR/CSS21/visudet.html The content width of a non-replaced inline element's boxes is that of the rendered content within them So if I want the background of my containing box to grow to be the width of the children, it appears I need to make sure it's layout is calulated in an inline formatting context: http://www.w3.org/TR/CSS21/visuren.html#normal-flow When an inline box exceeds the width of a line box, it is split into several boxes and these boxes are distributed across several line boxes. If an inline box cannot be split (e.g., if the inline box contains a single character, or language specific word breaking rules disallow a break within the inline box, or if the inline box is affected by a white-space value of nowrap or pre), then the inline box overflows the line box. Great. Hopefully the breaking rules also include emergency wrapping possibilities. http://www.w3.org/TR/2010/WD-css3-text-20101005/#word-wrap This property specifies whether the UA may break within a word to prevent overflow when an otherwise-unbreakable string is too long to fit within the line box. Doesn't really help; let's look at the newer draft spec: http://www.w3.org/TR/css3-text/#overflow-wrap Break opportunities not part of ‘overflow-wrap: normal’ line breaking are not considered when calculating ‘min-content’ intrinsic sizes. This isn't very clear, but if 'min-content' instrinsic sizes has something to do with the same calculations used to determine line-breaking possibilities, I might be out of luck. I ended up just using Javascript to measure the content and decide whether to show it in block or inline context. Sigh. var messages = document.body.getElementsByClassName('mail_uncollapsed'); // Show overflowing content by setting element display to inline-block. This // prevents break-word from being applied to the element, so we only do this // if the element would overflow anyway. for (var i = 0; i < messages.length; ++i) { var message = messages[i]; message.style.display = 'block'; var isOverflowing = message.clientWidth < message.scrollWidth; if (isOverflowing) { message.style.display = 'inline-block'; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Need suggestion for SysLog with Node.js I have just npm install node-syslog but it doesn't work. I have a syslog server (IP address , and local0). And I'm looking for a syslog module to help me post the message to syslog. But I don't know which one I should use. Please give me some suggestion. thanks. oh.. if there is a good syslog parser (node.js), please let me know too. :) A: I tried most of the modules listed in npm search, and had very little luck with any of them. Luckily in the end, I stumbled across rconsole which I found was MUCH easier to configure and use than any of the others. It's also nice that it allows you to colour and timestamp (and trace, etc) your stdout during development. To use, simply npm i rconsole, then, from the docs: require('rconsole') console.set({ facility: 'local0', title: 'basic' }) console.emerg('level 0') console.alert('level 1') console.crit('level 2') console.error('level 3') console.warn('level 4') console.notice('level 5') console.info('level 6') console.log('level 6') On OSX, I check my syslog using tail -f /var/log/system.log A: Like you, I was also searching for a syslog solution until I found this opinion: Logs are a stream, and it behooves everyone to treat them as such. Your programs should log to stdout and/or stderr and omit any attempt to handle log paths, log rotation, or sending logs over the syslog protocol. Directing where the program’s log stream goes can be left up to the runtime container: a local terminal or IDE (in development environments), an Upstart / Systemd launch script (in traditional hosting environments), or a system like Logplex/Heroku (in a platform environment). https://adam.herokuapp.com/past/2011/4/1/logs_are_streams_not_files/ Now I've happily concluded my search and am using console.log. A: It doesn't look like the community has come to a consensus here. Each of the node syslog projects I've come across have long-open issues that seem pretty significant (or are ghost towns). Winston seems to be the best option for general-purpose logging and has the winston-syslog transport available. The problem is that there seem to be some pretty significant issues with it: https://github.com/indexzero/winston-syslog/issues I think I'm going to give winston-syslog-ain2 a shot, myself. A: syslog-stream creates a writable Stream for syslog using native C bindings. It also includes tests. You could then write to that stream directly or as an output for another logging module. A: I've used both https://github.com/cloudhead/node-syslog and https://github.com/cconstantine/syslog-node without any issues. But when I'm in your situation I run: npm search $(what im looking for) I ran npm search syslog and this is my output, hope it helps. ain Syslog logging for node.js =akaspin (prehi ain-tcp Syslog logging for node.js, with syslog/TCP support =andry1 2011-0 ain2 Syslog logging for node.js. Continuation of ain =phuesler 2012-0 ain2-fs Syslog logging for node.js. Continuation of ain =ossareh 2011-1 ain2-papandreou Syslog logging for node.js. Continuation of ain =papandreou 2012-0 artifi-glossy Syslog parser and producer. It is fork of https://github.com/squeeks/glossy - pleas beatit Simple agent that can stay hooked on a log file (even if while log rotated and send frontail tail -F output in browser =mthenw 2012-0 glossy Syslog parser and producer =squeeks 2012-0 netasqsyslog Syslog for NETASQ security appliances =sdolard 2012-0 node-nativesyslog JavaScript-only syslog module for NodeJS =janoszen 2011-1 node-syslog Node module to support sending messages to syslog daemon =schamane 2012-0 posix The missing POSIX system calls =mel 2012-0 rconsole 'syslog.h' bindings with a revised console module =tblobaum 2012-0 simplelogger A simple logging solution supporting file, stdout and syslog output =ditesh 2011-06 splog A NodeJS library which provides a syslog-like remote logging interface =mattbornski syslog Syslog-ng TCP client, with basic fault-tolerance. =cloudhead 2011-0 syslog-node A syslog server and realtime web view of syslog messages =cconstantine 2011-0 syslogd-nodejs syslogd in node.js with logging to cli, file, mongodb and via websockets =crahles 2 tails Aggregate your syslog messages & filter for those that matter in real time. =porter winston-syslog A syslog transport for winston =indexzero 2011-0 winston-syslog-ain2 An ain2 based syslog transport for winston =lamtha 2012-0
{ "language": "en", "url": "https://stackoverflow.com/questions/7604527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: stack program print function not working properly I just finished working on this program but from the beginning I noticed that it was somehow not printing out everything it was supposed to. It's needs to print the integers in a stack beginning from the top first and then do it again beginning from the bottom. It prints the top to bottom correctly, but for some reason it only prints the very bottom number on the bottom to top. for example if a stack contains the integers 1, 2, 3, 4, 5, 6, where 1 is at the bottom of the stack and 6 is the top number. the program should print the following: Top { 6 5 4 3 2 1 } Bottom Bottom { 1 2 3 4 5 6 } Top but it prints the following: Top { 6 5 4 3 2 1 } Bottom Bottom { 1 } Top here is the print function: void Print() const // Prints stack contents to stdout in both top-to-bottom and bottom-to-top order { Node* temp = topPtr; cout << "Top { "; // Forward print while (temp != NULL) { cout << temp->data << " "; if (temp->next == NULL) break; temp = temp->next; } cout << "} Bottom Bottom { "; // Reverse print while (temp != NULL) { cout << temp->data << " "; temp = temp->previous; } cout << "} Top" << endl; } // End Print() }; // End Class Stack and If you need any further reference here is the main() #include <iostream> #include <fstream> #include <new> #include <cstddef> #include "stack.h" using namespace std; int main(int argc, char* argv[]) { ifstream inputs; // Input file for commands char op; // Hold operation and optional char input int value; // Value input from file string comment; // Holds comment from file Stack* sPtr = NULL; // Will point to stack object // Output usage message if one input file name is not provided if (argc != 2) { cout << "Usage:\n project03 <inputfile>\n"; return 1; } // Attempt to open input file -- terminate if file does not open inputs.open(argv[1]); if (!inputs) { cout << "Error - unable to open input file" << endl; return 1; } // Input and echo header comment from file getline(inputs, comment); // Input and echo the comment appearing in the test file cout << endl << '#' << comment << endl; // Process commands from input file inputs >> op; // Attempt to input first command while (inputs) { switch (op) // Process operation input from file { case '#': // Test file comment getline(inputs, comment); // Input and echo the comment appearing in the test file cout << '#' << comment << endl; break; case 'c': // Constructor cout << endl << "Stack( )"; try { sPtr = new Stack( ); // Attempt to create an empty stack object cout << " -- Successful" << endl; } catch ( std::bad_alloc ) { cout << "Failed : Terminating now..." << endl; return 1; } break; case '+': // Push inputs >> value; cout << "Push(" << value << ")"; try { sPtr->Push(value); cout << " -- successful"; } catch (StackFull) { cout << " -- Failed Full Stack"; } cout << endl; break; case '-': // Pop cout << "Pop() -- "; try { sPtr->Pop(); cout << "successful"; } catch (StackEmpty) { cout << "Failed Empty Stack"; } cout << endl; break; case 'f': // IsFull cout << "IsFull() -- "; try { if (sPtr->IsFull()) cout << "true"; else cout << "false"; } catch ( ... ) { cout << "operation failed"; } cout << endl; break; case 'e': // IsEmpty cout << "IsEmpty() -- "; try { if (sPtr->IsEmpty()) cout << "true"; else cout << "false"; } catch ( ... ) { cout << "operation failed"; } cout << endl; break; case 'm': // Make Empty sPtr->MakeEmpty(); cout << "MakeEmpty()" << endl; break; case 'p': // Print Stack cout << "Print() -- "; sPtr->Print(); break; case 't': // Top of Stack try { cout << "Top() -- " << sPtr->Top() << endl; } catch (StackEmpty) { cout << "Top() -- Failed Empty Stack" << endl; } break; case '>': // Max value within Stack try { cout << "Max() -- " << sPtr->Max() << endl; } catch (StackEmpty) { cout << "Max() -- Failed Empty Stack" << endl; } break; case '<': // Min value within Stack try { cout << "Min() -- " << sPtr->Min() << endl; } catch (StackEmpty) { cout << "Min() -- Failed Empty Stack" << endl; } break; case '?': // Peek(n) Stack inputs >> value; try { cout << "Peek(" << value << ") -- " << sPtr->Peek(value) << endl; } catch (StackInvalidPeek) { cout << "Peek(" << value << ") -- Failed Invalid Peek" << endl; } break; case 's': // Size of Stack cout << "Size() -- " << sPtr->Size() << endl; break; case 'd': // Destructor delete sPtr; sPtr = NULL; cout << "~Stack()" << endl << endl; break; default: // Error cout << "Error - unrecognized operation '" << op << "'" << endl; cout << "Terminating now..." << endl; return 1; break; } inputs >> op; // Attempt to input next command } return 0; } // End main() and here is header file for stack.cpp (stack.h) // // stack.h // // Specification file for Stack class, a stack of integers implemented // using doubly-linked nodes. // // ***** DO NOT MODIFY THIS FILE ***** // #include <iostream> using namespace std; #ifndef STACK_H #define STACK_H class StackEmpty { /* No Code */ }; // StackEmpty exception class - throw an object of this type when stack is empty // Hint: there is no code for exception classes class StackFull { /* No Code */ }; // StackFull exception class - throw an object of this type when stack is full class StackInvalidPeek { /* No Code */ }; // StackInvalidPeek exception class - throw an object of this type when invalid peek position is used struct Node // Node data type for storing a single stack entry along with pointers to { // neighboring entries (previous and next) in the stack Node* previous; // Member variable that holds the address of the predessor node in the stack sequence Node* next; // Member variable that holds the address of the successor node in the stack sequence int data; // Member variable that holds the data value }; class Stack // Implements stack of integers ADT using doubly-linked sequence of nodes { private: Node* topPtr; // Points to the top node on the stack array public: Stack(); // Default constructor initializes empty stack ~Stack(); // Destructor deallocates all nodes from stack // Must not create a memory leak void Push(int n); // Pushes integer n onto top of stack. // If unable to push, throws StackFull exception. void Pop(); // Removes top integer from stack // If stack is already empty, throws StackEmpty exception bool IsEmpty() const; // Returns true if stack is empty; false otherwise bool IsFull() const; // Returns true if stack is full; false otherwise void MakeEmpty(); // Removes all nodes from stack leaving an empty, but usable stack // Must not create a memory leak int Top() const; // Returns value of top integer on stack WITHOUT modifying the stack // If stack is empty, throws StackEmpty exception int Size() const; // Returns number of items on stack WITHOUT modifying the stack int Max() const; // Returns value of largest integer within stack WITHOUT modifying the stack // If stack is empty, throws StackEmpty int Min() const; // Returns value of smallest integer within stack WITHOUT modifying the stack // If stack is empty, throws StackEmpty int Peek( int n) const; // Returns stack value n levels down from top of stack. Peek(0) = Top() // If position n does not exist, throws StackInvalidPeek . ./******* DO NOT MODIFY ANY OF THE CODE FOR PRINT() *******/ /****** DO NOT PLACE A COPY OF PRINT() CODE IN STACK.CPP!!! *******/ void Print() const // Prints stack contents to stdout in both top-to-bottom and bottom-to-top order { Node* temp = topPtr; cout << "Top { "; // Forward print while (temp != NULL) { cout << temp->data << " "; if (temp->next == NULL) break; temp = temp->next; } cout << "} Bottom Bottom { "; // Reverse print while (temp != NULL) { cout << temp->data << " "; temp = temp->previous; } cout << "} Top" << endl; } // End Print() }; // End Class Stack #endif and finally here is stack.cpp which is the file I created the rest was given. // // stack.cpp // // // Created by Otapia on 9/19/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include <iostream> #include <new> #include "stack.h" Stack::Stack() // Default constructor initializes empty stack { topPtr = NULL; } Stack::~Stack() // Destructor deallocates all nodes from stack // Must not create a memory leak { Node* tempPtr; while ( topPtr != NULL ) { tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr; } } void Stack::Push(int n) // Pushes integer n onto top of stack. // If unable to push, throws StackFull exception. { if(!IsFull()) { Node* tempPtr = new Node; tempPtr->data = n; tempPtr->next = topPtr; topPtr = tempPtr; } else throw IsFull(); } void Stack::Pop() // Removes top integer from stack // If stack is already empty, throws StackEmpty exception { if (!IsEmpty()) { Node* tempPtr; tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr; } else throw StackEmpty(); } bool Stack::IsEmpty() const // Returns true if stack is empty; false otherwise { return(topPtr == NULL); } bool Stack::IsFull() const // Returns true if stack is full; false otherwise { Node* location; try { location = new Node; delete location; return false; } catch(std::bad_alloc) {return true; } } void Stack::MakeEmpty() // Removes all nodes from stack leaving an empty, but usable stack // Must not create memory leak { Node* tempPtr; while ( topPtr != NULL ) { tempPtr = topPtr; topPtr = topPtr->next; delete tempPtr; } topPtr = NULL; } int Stack::Top() const // Returns value of top integer on stack WITHOUT modifying the stack { if(!IsEmpty()) return topPtr->data; throw StackEmpty(); } int Stack::Size() const // Returns number of items on stack WITHOUT modifying the stack { Node* temp = topPtr; int count = 0; while (temp != NULL) { temp = temp->next; count ++; } return count; } int Stack::Max() const // Returns value of largest integer within stack WITHOUT modifying the stack // If stack is empty, throws StackEmpty { int max = 0; int n; Node* temp = topPtr; if(!IsEmpty()) { while(temp != NULL) { n = temp->data; if(n > max) { max = n; } temp = temp->next; } return max;} else throw StackEmpty(); } int Stack::Min() const // Returns value of smallest integer within stack WITHOUT modifying the stack // If stack is empty, throws StackEmpty {int min = 100; int n; Node* temp = topPtr; if(!IsEmpty()) { while(temp != NULL) { n = temp->data; if(n < min) { min = n; } temp = temp->next; } return min;} else throw StackEmpty(); } int Stack::Peek(int n) const // Returns stack value n levels down from top of stack. Peek(0) = Top() // If position n does not exist, throws StackInvalidPeek { int num = 0; int x = 0; Node* temp = topPtr; if(!IsEmpty()) { while(temp != NULL) { if (x >= n || temp->next == NULL) break; temp = temp->next; x++; } if (n <= x) { num = temp->data; } else throw StackInvalidPeek(); } else throw StackInvalidPeek(); return num; } A: Simple. while (temp != NULL) { cout << temp->data << " "; temp = temp->previous; } From your problem description, and the error'd code, I'd assume temp->previous is incorrect. I assume this gets set in some sort of push function. void Stack::Push(int n) // Pushes integer n onto top of stack. // If unable to push, throws StackFull exception. { if(!IsFull()) { Node* tempPtr = new Node; tempPtr->data = n; tempPtr->next = topPtr; topPtr = tempPtr; } else throw IsFull(); } You never set previous, so it's left as some unspecified value (of zero). Also, previous is not set or checked anywhere in your cpp file. It should be set here, although really doesn't need to be anywhere else. Lastly, throw IsFull() is a heck of an exception. You probably didn't mean to throw the bool result of a function call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What motion does iPhone SDK give exactly? I am a little confused about iPhone's accelerometer and gyro data. I had worked with SDK at iOS 3.x times and as far as I remember it only gives rotation around axes. But with iPhone 4 I saw that it has a gyroscope; which is used for rotation again. If gyro is a new feature, what info does accelerometer give? I want to catch displacement of iPhone/iPod (without rotation) is there a way to catch this with any of the features? A: The 3D accelerometer in the iPhone 3G produces results that contain a mix of acceleration and orientation with respect to gravity. It doesn't really give a great answer for either acceleration or orientation as long as the phone is in changing motion. The Apple provided filtering algorithms only partially separate out the data, so each component can be slightly or greatly wrong. Rotation is then estimated from any changes in the estimated direction of gravity (the down vector with respect to the device). And estimates can be wrong. The Core Motion API in iOS 4.x, combined with the 3 axis gyros in an iPhone 4, uses actual rotation measurements to try to subtract out rotation from the potentially mixed-up 3D accelerometer data, usually producing a much better estimates of orientation, rotation, and acceleration. Displacement is much harder to measure, as the double integral of acceleration sums so much noise into the result, that the result will quickly diverge to be complete out of the park. A: Accelerometers measure lateral acceleration whereas gyroscopes measure relative rotation. If move your phone vertically up without rotating it, you will see a non-zero value for acceleration on one axis (assuming the device is perpendicular to the Earth) but the gyro will read 0. It sounds like you want to use only the accelerometer data. A: I think you will need a gyro anyway to have a precise estimate of user acceleration and cancel gravity correctly. As usually your movement will not be just along one axis but will include slight rotation combined with slight displacement along other axises.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Twitter API to follow someone I checked some other similar questions but some of them are old and i'm too new at api for the rest. So here it comes. I have my account's password, i have my username and i have a person's username who i want to follow. I want to login and follow that person with these information. So far i found out that process is about something called OAuth and i need to use friendships/create at twitter api. (which is : https://dev.twitter.com/docs/api/1/post/friendships/create ) The problem is hell i have no idea about using OAuth or that twitter api. Looked for some demos over internet but turned out empty, please give me a start point about how to use those. Thanks in advance. (Btw, i will use PHP for process, if it matters) A: here are some good tutorials : http://www.1stwebdesigner.com/tutorials/twitter-app-oauth-php/ http://net.tutsplus.com/tutorials/php/how-to-authenticate-users-with-twitter-oauth/ technically you would need to register your applications, and then simply use a twitter library to do the authentication etc (or you could write your own) and then use the library's functions to send your request with the auth code you get from twitter
{ "language": "en", "url": "https://stackoverflow.com/questions/7604539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EF CF: is it right always is null the object of FK? I have a Domain Models like this public class ShipToCode { public int ShipToCodeID { get; set; } [Required(ErrorMessage = "Nombre es requerido",AllowEmptyStrings = false)] [StringLength(50, ErrorMessage = "Debe ser menor a 50 carácteres")] [MaxLength(50)] [Column("nb_name")] public string Name { get; set; } [StringLength(15, ErrorMessage = "Debe ser menor a 15 carácteres")] [MaxLength(15)] [Column("cd_locId")] public string locId { get; set; } public int? RegionID { get; set; } public virtual Region Region { get; set; } [Required(ErrorMessage = "Dealer es requerido")] public int DealerID { get; set; } public virtual Dealer Dealer { get; set; } } public class Dealer { public Dealer() { this.ShipToCode = new HashSet<ShipToCode>(); } public int DealerID { get; set; } [Required(ErrorMessage = "Nombre es requerido")] [StringLength(100, ErrorMessage = "Debe ser menor a 100 carácteres")] [MaxLength(100)] [Column("nb_name")] public string Name { get; set; } [Required(ErrorMessage = "Codigo de distribuidor es requerido")] [StringLength(100, ErrorMessage = "Debe ser menor a 100 carácteres")] [MaxLength(100)] [Column("cd_dealerCode")] public string DealerCode { get; set; } public virtual ICollection<ShipToCode> ShipToCode { get; private set; } } In my context protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<ShipToCode>() .HasRequired<Dealer>(d => d.Dealer) .WithMany(d => d.ShipToCode) .HasForeignKey<int>(c => c.DealerID); } But when i get any ShipToCode or Dealer, using the function of find of the DbSet, my object of Dealer in the ShipToCode or The ICollection of ShipToCode in Dealer is empty This is normal or i'm missing something?? please help!! A: In your Dealer the property, public virtual ICollection<ShipToCode> ShipToCode { get; private set; } has the private set method you need to make it public otherwise EF can't set it from the database. And make sure you have enabled lazyloading in your context. If you are not enabled lazy loading you can use eager loading like this, Context.ShipToCodes.Include(s=>s.Dealer ).where(s=>s.ShipToCodeID ==1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7604540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yii relations trouble when trying to display CGridView from 2 models Image describing the tables -> http://i.stack.imgur.com/ki2YP.jpg Each of the tables is a model. Main model which shows through CGridView is "RegularTask". Now I need it to display fields from "YearlyTask" in the same row. "hp_id" and "up_id" are FK (foreign keys) in both tables. I tried to set the relations() in the RegularTask model like this: 'arp' => array(self::BELONGS_TO, 'YearlyTask', 'hp_id, up_id'), Then I try to display the "is_sent" and "is_reported" fields from YearlyTask by using "arp.is_sent" and "arp.is_reported", but nothing shows up (not even error). While data from RegularTask displays normally. What am I doing wrong? Here is a snippet from the dataprovider.. <?php $dataProvider=new CActiveDataProvider('RegularTask', array( 'criteria'=>array( 'condition'=>'t.id_id=' . $model->id, 'order'=>'t.created DESC', 'with'=>array('arp'), ), 'pagination'=>array( 'pageSize'=>10, ), )); $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'columns'=>array( 'comment', 'arp.is_sent' ), )); ?> A: Foreign key in one table must be primary key in linked table. If you look into SQL statement created by Yii with your structure, you will see something like this (simplified): SELECT `t`.*, `arp`.* FROM `RegularTask` `t` LEFT OUTER JOIN `YearlyTask` `arp` ON (`t`.`hp_id`=`arp`.`id`) AND (`t`.`up_id`=`arp`.`id`) As you can see, what it looks for is that both RegularTask.hp_id and RegularTask.up_id have same value as YearlyTask.id which isn't correct. You have several solutions. One of them is create new column in RegularTask like yt_id which will be foreign key for YearlyTask.id and in my opinion it's the best solution. Otherwise you can delete your primary key column id in RegularTask table and make hp_id and up_id as complex primary key. In this case you can use the way you tried before, but as i don't know your full db structure i can't guarantee that it's good solution. A: have you tried using this style: $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'columns'=>array( 'comment', array( 'header'=>'Sent', 'type'=>'raw', 'value'=>'$data->arp->is_sent', ) ), )); perhaps not the most elegant way, but might be of help
{ "language": "en", "url": "https://stackoverflow.com/questions/7604541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Global code initialization in Java Since the JVM loads classes and code on-demand, there is no way to have initialization code in some random class (apart from the class containing the main() function) and have it run as the JVM starts. I'm aware that the very thought of this goes contrary to the JVM design. However, sometimes you want to do stuff like this, and I'm curious if there's some "standard" way of doing it, apart from having a function with a long, centralized list of initialization functions to call somewhere, and call them from the main() function. The specific reason I'm wondering is because I have a program with a GUI system. This program connects to a server and acts kind of like a graphical terminal, allowing the server to create widgets to interact with the user. In order to do this, the widgets need to have some kind of ID that the server can use to reference them over the protocol, and there needs to be some kind of registry of such IDs. Right now, I'm using a global map of such IDs, mapping to instances of a WidgetFactory class, and I'm initializing those IDs in a static {} block in the base Widget class, kind of like this: public class Widget { private final static Map<String, WidgetFactory> widgets = new HashMap<String, WidgetFactory(); static { widgets.put("wnd", Window.factory); widgets.put("lbl", Label.factory); widgets.put("text", TextEntry.factory); widgets.put("btn", Button.factory); } } However, as you can probably tell, this list grows large and unwieldy with growing numbers of widget types, and I also find it horribly ugly to centralize the widget logic in this way, when each widget type could instead be entirely self-contained in its own file. I would much prefer if I could do something like this in every file defining a widget class: public class Label extends Widget { static { Widget.register("lbl", new WidgetFactory() {...}); } } But, for the aforementioned reasons, this particular method of doing it is obviously not possible. It's not that I can't think of any ways to do this, but they all seem to possess varying degrees of ugliness, and I also think I can't really be the first one to grapple with this problem, so I guess what I want to ask is if there is, at least, some more-or-less "standard" way of doing these kinds of things. I would prefer not having to reinvent this particular wheel if I can avoid to. A: i think you could save id's and theclass name of widget you need in a temporally file, then use reflection to instance them, and also you can use a xml file. A: On startup, iterate through all .class files in your widget package folder and load them using a class loader. The widget's ID can be e.g. based on the class name or stored in an annotation. If you want, you can support loading from several widget directories, from inside JAR files etc. I'm sure there are libraries to help with this and hope someone will edit this answer to point to one. A: For the record, I've finally come to terms with the weirdness that no standard solution for this problem appears to exist, so I wrote one, which works by providing an annotation processor which collects classes annotated with Discoverable annotations into generated text files. This is still a centralized list, of course, but since it's autogenerated from decentralized annotations (which is not necessarily more strange that autogenerated ELF sections of initialization code, which is what GCC produces for C programs), I'm OK with that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you delete a couchdb document with an empty "" document id? I see the document in the db as this: {_id: "", _rev: "1-2f11e026763c10730d8b19ba5dce7565", forbidden: "must supply latest _rev to update existing package"} Everything I see in the docs shows referring to the document with the ID, but of course this can't happen. I'm not exactly sure how this happened, most likely something faulty between the chair and keyboard, but I wanted to know if there was a possibility of fixing this without starting over. A: There is a bug in CouchDB that allows this to happen. I believe it was introduced in v1.1.0 and will be fixed in v1.1.1 and v1.2.0. The bug is that _update functions can create documents with empty-string IDs. To delete the document, use the same update function and exploit the same bug. For example: { "_id": "_design/example", "updates": { "del_blank": "function(doc, req) { var doc = {_id:'', _rev:req.query.rev, _deleted:true}; return [doc, 'Trying to delete nastydoc@'+doc._rev]; }" } } Simply provide the revision that is giving you problems and it will mark it deleted. $ rev="1-2f11e026763c10730d8b19ba5dce7565" $ curl -XPOST localhost:5984/db/_design/example/_update/del_blank?rev=$rev Trying to delete nastydoc@1-2f11e026763c10730d8b19ba5dce7565 $ curl localhost:5984/db/_all_docs {"total_rows":1,"offset":0,"rows":[ {"id":"_design/example","key":"_design/test","value":{"rev":"2-b9bfbedff0c09fab88ff36d06cec0d34"}}, ]} A: Concerning version 2.1.1: There is a bug in Project Fauxton that allows you to clone a document while leaving the new ID blank. Neither the Project Fauxton nor CouchDB's API offers a way to edit or delete documents with blank IDs. In JasonSmith's answer, the del_blank update function throws {"error":"illegal_docid","reason":"Document id must not be empty"}. So, you must replicate the database into a new database, which will store documents with non-empty IDs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I make 2 pages inside a page ? Is that even possible? Like 2 "frames" containing their own javascript and forms inside a webpage. A: Yes, look up HTML frames, or iframes. A: <iframe src="www.google.com" frameborder="0" width="10px" height="10px"></iframe> <object src="http://www.google.com"> <em>Google In Page</em> </object> or using File API: function startRead() { // obtain input element through DOM var file = document.getElementById('file').files[0]; if(file){ getAsText(file); } } function getAsText(readFile) { var reader = new FileReader(); // Read file into memory as UTF-16 reader.readAsText(readFile, "UTF-16"); // Handle progress, success, and errors reader.onprogress = updateProgress; reader.onload = loaded; reader.onerror = errorHandler; } function updateProgress(evt) { if (evt.lengthComputable) { // evt.loaded and evt.total are ProgressEvent properties var loaded = (evt.loaded / evt.total); if (loaded < 1) { // Increase the prog bar length // style.width = (loaded * 200) + "px"; } } } function loaded(evt) { // Obtain the read file data var fileString = evt.target.result; // Handle UTF-16 file dump if(utils.regexp.isChinese(fileString)) { //Chinese Characters + Name validation } else { // run other charset test } // xhr.send(fileString) } function errorHandler(evt) { if(evt.target.error.code == evt.target.error.NOT_READABLE_ERR) { // The file could not be read } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Rails 3.1 - sharing precompiled assets across servers App 1 is on server A. App 2 is on server B. App 2 has precompiled assets and everything works great. Now App 1 wants to use the same CSS file as App 2 that resides on server B. Is there a way to make this work? I tried setting: config.action_controller.asset_host = "http://assets.example.com" in App 1 but that didn't seem to help. When I view an image on App 2 the path shows the url with the cache fingerprint like assets/logo-i3q73498g0.png where-as in App 1 where the image isn't showing, the path is just logo.png Thanks! A: The answer to this is probably to share the assets manifest file between apps. This file contains mappings for raw filenames to the ones with fingerprints in them. This is at public/assets/manifest.yml by default. I suggest that when you deploy App 2 you add a task to grab the asset manifest from App 1, and assuming that App 2 does not have any compiled assets (because you have changed the host) just use that for the app. You would have to set the config to make App 2 think it has compiled assets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: php array_sum on associative array I have associative array (dynamic-may have more arrays but same keys): Array ( [food] => Array ( [0] => 3 [1] => 4 [2] => 1 ) [liquor] => Array ( [0] => 4 [1] => 5 [2] => 0 ) [beer] => Array ( [0] => 5 [1] => 6 [2] => 0 ) ) I need to use array_sum on each array so result would be: Array ( [food] => 8, [liquor] => 9, [beer] => 11 ) Thanks! A: $result = array_map('array_sum', $your_array); Example: http://ideone.com/LqTAV
{ "language": "en", "url": "https://stackoverflow.com/questions/7604560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use Posterous API to 'scrape' my own site for contributor info, date info, and response info As a college teacher in STEM, I like it when I can use technology to enhance the learning experience of my students, and I doubly like it when it allows me to introduce them to cool tech, too. During the last year, I've had a couple classes make posts to a Posterous site (http://spectrawiki.posterous.com) and post comments to the posts of others. This is required for the course, and I've be saddled with keeping track of class activity. I'd hoped I could download site content in a way that gives me the data I need (who posted, when they posted, and if they posted an article or comment), but Posterous doesn't have this functionality. A very responsive Posterous Tech suggested I look at the API. But I'm not a coder. I know enough about coding (HTML, PHP, matlab, python, R, Mathematica) to respect those who really know what they're doing. So I ask the Stack Overflow community: how could I hack together something (e.g., a python script) with the API to get the data I'm looking for (listed above)? Are there any tutorials out there that would lead me through the steps of building a script? I've never used an API before, so I don't really know where to begin. Thanks in advance for any pointers. [Edit] For Example: the Posterous API Reference has an example like this curl -X PUT --user you@example.com:password -d "api_token=<your token>" -d "post[title]=New Title" http://posterous.com/api/2/sites/12345/posts/6789 when it talks about the API being RESTful. How can I modify this curl command to return some type of information about my Posterous site? I can (probably) handle the authentication flags and that token flag. But using the other flags, that's where I could use a pointer. A: Follow-up, 5 December 2012: It looks like pyposterous no longer works. My scripts fail and pyposterous fails its own unit tests. Bummer. ==== Pyposterous did, indeed, give me the tools to answer my question, so I thought I'd share it here for others. Here's the script I wrote: import datetime import pyposterous from pyposterous import Cursor api = pyposterous.API(username='[username]', password='[passwd]') d=datetime.datetime.today().strftime("%y%B%d-%H%M") filename = 'report-posts-' + str(d) +'.txt' log=open(filename,'w') for post in Cursor(method=api.read_posts, start_page=1, parameters={'hostname':'spectrawiki'}): try: print >> log, "--------------------" print >> log, "%s, %s, %s" % (post.author, post.date, post.title) except AttributeError: pass # No comments except UnicodeEncodeError: pass It's a crude script, but it gets the basic job done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: EF 4.1 Code-first executes queries 3x slower than regular EF in my application I have a pet project (a simple forum application) that I use to test out all the latest .NET tech and I recently got around to toying with Entity Framework Code-First. This app already had an existing EF solution with an EDMX file mapped to an existing database and all my entities were auto-generated. This solution has worked great so far. Note: Keep in mind that this change to EF 4.1 is purely for learning. If you are wondering what my needs were that caused me to upgrade, there weren't any. I simply wanted to do it for fun. I copied the project and did the upgrades so I would have the same project but with different Entity Framework implementations. In the new project I used a Visual Studio extension called Entity Framework Power Tools to generate POCOs and a DbContext from my existing database. Everything worked flawlessly. I had the app compiling in about 30 minutes time. Pretty impressive. However, I noticed now when running the app that the query execution is approximately 3 times slower than it was before. Any idea what I could have missed? Below are the details for both solutions, as well as LINQPad measurements for both. (click images for full size) EF 4.0 Details Here is a snapshot of my EF 4.0 data model. It cuts off a few entities on top and bottom but you get the idea. http://www.codetunnel.com/content/images/EF41question/1.jpg Here is a LINQPad test against my EF 4.0 data model. http://www.codetunnel.com/content/images/EF41question/2.jpg Notice that the query took 2.743 seconds to execute. EF 4.1 Details Here is a snapshot of my EF 4.1 data model. Since it's code-only I will show the DbContext class as well as one of the mapping classes (fluent API code) for one entity, and one entity itself. DbContext http://www.codetunnel.com/content/images/EF41question/3.jpg TopicMap (fluent API configuration) http://www.codetunnel.com/content/images/EF41question/4.jpg Topic (POCO entity) http://www.codetunnel.com/content/images/EF41question/5.jpg Here is a LINQPad test against my EF 4.1 model. http://www.codetunnel.com/content/images/EF41question/6.jpg Notice this time that the query took 6.287 seconds to execute and it was the exact same query. It takes over 30 seconds the very first time it is run. If I go to the SQL and IL tabs in LINQPad the generated SQL and the IL code are identical for both data models. This is really giving me grief. In the actual application things are so slow with EF 4.1 that it is unusable. I ran the same LINQ query against both models. The query grabs all topics for a regular forum user, orders them in descending order by their last reply date (or the topic post date if there are no replies). Obviously I can just go back to EF 4.0 and go about my merry way but I'm really interested if there might be something I missed. A: UPDATE I'm completely revisiting this answer because of some recent developments. Because of some inquiry by the Entity Framework team at Microsoft trying to duplicate my issue, I went back and retraced my steps to better help narrow down the problem. It's been a while since I asked this question and I understand things much better now than I did then. Rather than go back and try to get some very old code running I decided to start from scratch with a simple test project. I put together a simple database with two tables and mapped them to an EF 4.0 designer file. This generated a connection string like this: <add name="EFTestEntities" connectionString="metadata=res://*/Entities.csdl|res://*/Entities.ssdl|res://*/Entities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\sqlexpress;initial catalog=EFTest;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> I then populated the database with 1000 rows of test topics and 10 rows of replies for each topic. Once I had this working I timed a very basic query fairly similar to the one in my main question. Then I duplicated the test project and I modified it using the Entity Framework Power Tools extension to generate my model objects and DbContext. The only thing I modified was the connection string to remove the metadata that is referenced when there is a designer file in the project so it looked like this: <add name="EFTestContext" providerName="System.Data.SqlClient" connectionString="Data Source=.\sqlexpress;Initial Catalog=EFTest;Integrated Security=True;Pooling=False" /> I then ran the exact same query as I did with the designer. There was no difference in query times except for the slightly extra time it takes for the code-first to generate the mapping meta-data. After that initial query the two versions of EF performed pretty much the same. I was about to resolve the problem as not reproducible but then I notice I did something horrible in the question. I called .AsEnumerable() before my queries. If you don't already know what that does, that will cause the ENTIRE entity collection to be pulled into memory and then the query would be applied there as LINQ-to-Objects rather than LINQ-to-Entities. This means that I was sucking an entire table into memory and then doing LINQ against it there. In cases where SQL server is on the same machine as your website you might not notice the difference but there are many cases where this would be a huge issue. In my case it really was causing a performance loss. I went back to my tests and I ran them with .AsEnumerable() placed before the queries. Now I expected the time to be slower since my LINQ queries weren't being translated into expression trees and executed in the database. However, it seems I did reproduce the issue in my question. The code-only version is returning much slower. This is actually pretty strange because they both should be running the same. I am not surprised that they are running slower than when the queries were against IQueryable, but now that they are running against IEnumerable there is a big difference between the two. I was able to expand the difference between the two by adding more and more data to the table. I went ahead and added 5000 more topics to the database, with 30 replies for each topic. So there is now a total of 6000 topic rows and 165000 reply rows. First I ran the query with proper LINQ-to-Entities: As you can see, still no difference. Then I ran the queries against with LINQ-to-Objects using .AsEnumerable(). I stopped it after three queries because waiting about two minutes per query was excruciating. I can't seem to produce the 3x as slow issue that I show in my question, but code-only is significantly slower. The EDMX approach takes just shy of two minutes to complete one query while the code-only approach consistently takes over two minutes. A: If I don't misunderstand you have two situations and in both situations you compare the performance of a query: * *In your question you compare the performance of a query with the ObjectContext API in EF 4.0 with the performance of the same query with DbContext API using Code-First in EF 4.1. Now if I saw right in your code repositories for the EF 4.0 approach you have used EntityObject derived entities and not POCOs (generated from the T4 POCO generator for EF 4.0) whereas in your EF 4.1 solution you have POCOs. My hypothesis is that this makes the difference. If you are using EntityObject derived entities your objects are capable to track their own changes. If you use POCOs on the other hand EF will create property snapshots of every materialized entity in the context which is not necessary for EntityObjects. This snapshot creation might take a serious amount of time. So this is not really a comparison between EF 4.0 and EF 4.1 but between a POCO and non-POCO approach. (Working with POCOs (which are not prepared for change tracking proxies, i.e. every property is virtual) in Entity Framework is slower in every aspect. If performance matters you must avoid them.) *Now, what you mention in the UPDATE to your own answer is interesting. If I understand right you compare here EF 4.1 with DbContext using Code-First (OnModelCreating has entity configurations and the connection string doesn't have references to the EDMX file) and EF 4.1 with DbContext using Database-First (OnModelCreating is empty (or only throws this UnintentionalCodeFirstException from the DbContext generator) and the connection string has a reference to the EDMX file). In both cases you are using the same POCO entities. Here the performance difference is surprising to me and I don't have an immediate hypothesis why this happens. You didn't provide exact measurements though (as in the situation in your question) which would be interesting. I'm not surprised that the first query is faster with the EDMX approach because EF only needs to read and process an XML file to build the model in memory whereas without EDMX it must reflect over the code in the assembly which is probably slower. But once the model is built in memory (so starting with the second query latest) my understanding was that EF will only work with that in-memory representation of the model, no matter what's the source of the metadata. If you really have a big performance difference in that situation I am stumped. Edit To summarize the comments: We are talking about point 2 above which means that you compare EF 4.1 Database-First (EDMX specified in connection string, OnModelCreating is empty) with EF 4.1 Code-First (EDMX not specified in connection string, OnModelCreating contains model configuration). Result: Your query with EF 4.1 Database-First is three times faster than with EF 4.1 Code-First. For a simple model I could not reproduce the behaviour. I have created one with Code-First and tested the query time with dummy data (300000 users ("Spock 1" to "Spock 300000") in User table, Contains("pock")-query over user name, so that all 300000 users must be returned and materialized, needs 3.2 sec). Then I have generated an EDMX from the code-first model: using (var context = new MyEntities()) { using (var writer = new XmlTextWriter("model.edmx", Encoding.Default)) { EdmxWriter.WriteEdmx(context, writer); } } The resulting EDMX file I've added to the project, modified the connection string to include the EDMX metadata, and run the query again. The query time was almost exactly the same (3.2 sec). So, the reason for the problem is apparently not so obvious. It could have to do with the complexity of the model or the query though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: "Download declined" on android market People are able to see my paid app "Mypod unlock key" on honeycomb devices, but after they purchase an error, "Download declined" the app doesnt install. it downloads and installs fine on pre-honeycomb devices. The log shows I/vending ( 3174): [1] AssetDownloader.downloadDeclined(): Download declined for asset 954210361404590979 (org.my_pod.mypodunlockpaid:0) [DOWNLOAD_PENDING]: 4 Copy protection on market is off. Has anyone seen this "download declined" eror? its crazy - not explanation or reason at all... A: this is the standard error when you are trying to download a paid app from your developer account.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to draw line after every group in SQL Server Reporting Services? Below is the report I have created. I would like to draw a line after every group as depicted with red line in the image. Tried meddling with Textbox Properties > Border Style expression. But that would not stay once I close and reopen it. If I set border for whole group, the line would repeat for every row in group which I dont want. Any help? A: Select the entire detail row and add this expression to the BorderStyle-Top property: =IIF((Previous(Fields!ProductionCountry.Value) <> Fields!ProductionCountry.Value) OR (Previous(Fields!IndustryName.Value) <> Fields!IndustryName.Value) OR (Previous(Fields!ProductGroup.Value) <> Fields!ProductGroup.Value), "Solid", "None") A: To improve on @niktrs's answer, I would suggest: =Iif(Fields!ProductionCountry.Value = Previous(Fields!ProductionCountry.Value) OR IsNothing(Previous(Fields!ProductionCountry.Value)),"None","Solid") This has the advantage of not adding a line on the initial group row, even when the first group displayed isn't the first group in the dataset, for example where sorting or filtering is in place. A: * *Click on the View tab in Microsoft SQL Server Report Builder. *Ensure the Properties check box is checked so that the Properties window is shown. *For the ProductionCountry select the entire group row. The properties should show for the row. *In the properties dig down to Border->BorderStyle->Top. The value will more than likely be blank. *In the Top field, enter the expression below for the top border. Top field value: =IIF(Fields!ProductionCountry.Value = Previous(Fields!ProductionCountry.Value) OR Fields!ProductionCountry.Value = First(Fields!ProductionCountry.Value, "mydataset"),"None","Solid") Change mydataset value above to match the dataset name of your report. Note: If current row belongs to the same group as the previous row OR current group row is the first of the dataset, set border to none, set border to solid. A: What I found really easy to do is define the top border for the group. In this way each new group adds a border between the last row of the previous group and the first one of the new group. It also adds a border after the headers. This solution does not draw a border at the end of the last row. If you need that border too, you can define the bottom border for the tablix that contains the groups. A: =Iif(Fields!ProductionCountry.Value ="","None","Solid") also change the border default none left solid right solid bottom none top the above expression. and to the rectangle properties change bootom order.. i tried like this for the top border and it was working fine... A: In my case I have an aggregate value so I cant use previous function so I hard coded the first value from the group which I knew that is going to be the first value in that group.Then in Border Style I used this expression Top =iif(Fields!Group_Name.Value="Hard Corded(first value)","Solid","None") Also in Border Color used this expression =iif(Fields!Group_Name.Value="Hard Corded(first value)",,"Black","LightGrey")
{ "language": "en", "url": "https://stackoverflow.com/questions/7604574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Using GPU on Silverlight 5 for general-purpose math I'm working on an in-browser Silverlight application that has some fairly compute-intensive operations, e.g., running an Inverse Discrete Cosine Transform, or a Fast Fourier Transform, hundreds of times a second. It would be valuable to be able to offload as much of this as possible onto the computer's GPU. I know that there was some discussion of this with Silverlight 3 and 4, using pixel shaders, but the consensus was that because Silverlight 3/4 didn't use hardware acceleration for their pixel shaders, and because their pixel shader language was limited to Level 2, it wasn't going to result in much of a performance increase, if any. However, supposedly Silverlight 5 has a much broader range of hardware-accelerated graphics, including a reasonably complete 3D pipeline. However, I haven't yet heard if anyone has been able to leverage this pipeline for accelerating general purpose mathematical operations (like FFT's, DCT's, IDCT's, etc). Has anyone tried that yet? Any pointers on where to start looking? A: I thought I'd post back what I've discovered so far. The short answer is that no, I don't think that the 3D pipeline on Silverlight 5 can be leveraged for this sort of thing. On the one hand, from what I can tell, the pixel shaders and vertex shaders that are a part of the pipeline do, in fact, get executed on the GPU (unlike the 2D shaders in Silverlight 4, which were executed on the CPU). But that said: (1) Everything I've read says that getting data onto the GPU is very fast, but that for most machines, getting that data out of the GPU is much slower, on the order of milliseconds. That makes it unlikely that we could, say, load up the GPU with the data necessary to perform an FFT, perform the FFT, and then pull the data back faster than we could just do it on the CPU. (2) Silverlight 5 has a very limited set of instructions that it can execute on the GPU. Specifically, it's limited to HLSL Level 2, which has a limited number of instructions and registers available. I doubt that it would be possible -- at best, it would be very difficult and very slow -- to model an FFT or a DCT within those limited instructions. (3) But even if we could get around those two limitations, from what I can tell, Silverlight doesn't have any ability to read the results of the calculations the GPU is performing. Normal XNA (the framework on which Silverlight's 3D features are based) has various GetData() or GetTexture() methods that I think you could use to read the results of a set of calculations. But those equivalent methods are missing in their Silverlight 5 versions. From everything I can tell, in Silverlight 5, the GPU is a write-only device. You load your shaders onto it, you load up your data, you pull the trigger, and you wave good-bye. Your code will never see those bytes again. If it turns out that I'm wrong on this, I'll come back here and update this answer. But at least at the moment, it looks as if this is a dead-end. [Edit 10/10/11 - According to Shawn Hargreaves from MS, this isn't supported in Silverlight 5. His guess as to why is that (a) it would be difficult to get it working consistently across all GPU drivers, and (b) for all but a tiny class of demo-ware-style problems, it wouldn't make any sense. Oh well.]
{ "language": "en", "url": "https://stackoverflow.com/questions/7604577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can I reset sandboxed in-app purchases on iOS for testing? I made a sandbox iTunes user, bought an item. That worked but there were some issues in my code for displaying the item. So, I want to re-buy it to test again. Problem is, I can't clear my purchases. I signed out my sandbox user, deleted the app and re-installed it, changed itunes users a few times... the item still shows up as purchased. I'm using MKStoreKit. Any ideas? A: Well, I figured it out. MKStoreKit saves purchased items to the keychain, which persists even if you change iTunes accounts or delete the app. Calling a quick [[MKStoreManager sharedManager] removeAllKeychainData]; reset things. A: If you have your own domain, you often get email handling for free; for example, I have a go daddy account, and I can set a mail forwarding rule for unrecognised email accounts. This makes it very easy to create loads of test accounts without having to have a separate email account for each one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: C# Copy text in a textbox where focus is I have this problem and don't know where to start. I need to write a program that will run in WinCE, so Compact Framework will be required, and this program has to write text (a string) wherever the cursor is. I mean, if my program is running, and the cursor is in a notepad window. the text must be displayed in notepad. Or if the cursor is in another application inside a textbox (or textfield if that app was wrote in java), the text must be placed in that textbox. I'm able to do all the other functionality the program requires, but I don't know how to do this. As far as I have read, it is done with API's. And that is all I can understand. Any help will be apreciated. Thanks! A: The first thing that comes to mind is SendKeys. It's a simple way to emulate typing. A: We use P/Invoke keybd_event to generate keyboard entry. The only other approach I can think of would be to put your string in the clipboard, and generate a paste key stroke. I'm not sure every app you encounter is going to respond to CTRL+V the same. Perhaps there's a way to trigger the paste programmatically from your app? [DllImport("coredll.dll", EntryPoint = "keybd_event", SetLastError = true)] public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); This should generate a silent A keystroke. keybd_event((byte)Keys.A, 0, 0, 0x0004); keybd_event((byte)Keys.A, 0, 0x0002, 0x0004);
{ "language": "en", "url": "https://stackoverflow.com/questions/7604582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Comboxbox auto select first item when data is available I am looking for way to select the first item when data became available. But if no data in the source , then do not select. How to do it ? I am very new to WPF. <ComboBox Grid.Row="5" Grid.Column="1" IsEditable="False" ItemsSource="{Binding Source={x:Static l:DirectXResolution.Resolutions}}" ToolTip="Resolutions"> <ComboBox.Resources> <l:ResolutionConverter x:Key="resolutionConverter"/> </ComboBox.Resources> <ComboBox.Text> <MultiBinding Converter="{StaticResource resolutionConverter}"> <Binding Path="GameWidth" Mode="OneWayToSource"/> <Binding Path="GameHeight" Mode="OneWayToSource"/> </MultiBinding> </ComboBox.Text> </ComboBox> A: The easiest way is to use SelectedIndex. Please, check the code below. <ComboBox Grid.Row="5" Grid.Column="1" IsEditable="False" ItemsSource="{Binding Source={x:Static l:DirectXResolution.Resolutions}}" ToolTip="Resolutions" SelectedIndex="0"> .... A: DirectXResolution.Resolutions must be ObservableCollection<T> otherwise your ComboBox will not be updated when the data becomes available. You can use CollectionChanged event of ObservableCollection<T> to select the first item. If DirectXResolution.Resolutions is not ObservableCollection, create a wrapper for this collection and inherit INotifyCollectionChanged A: Here is how to do it in code: Items.CollectionChanged += (sender, e) => { if (!Items.Contains(Selected)) { Selected = Items.FirstOrDefault(); } }; Items is an ObservableCollection that may be updated. Selected is a two-way property of the selected item. This code should be placed in the constructor of your view-model.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: AutoMapper with complex types I'm having a problem trying to use complex types with AutoMapper. I have two objects, a domain and a ViewModel that utlize in my View; ViewModel public class RegisterCoupleModel { [Required(ErrorMessage = "campo obrigatório")] [Display(Name = "Primeiro nome", Order = 0, GroupName = "Noivo")] [StringLength(60)] public string FistNameGroom { get; set; } [Required(ErrorMessage = "campo obrigatório")] [Display(Name = "Último nome", Order = 1, GroupName = "Noivo")] [StringLength(60)] public string LastNameGroom { get; set; } [Required(ErrorMessage = "campo obrigatório")] [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Formato de email inválido.")] [DataType(DataType.EmailAddress)] [Remote("IsEmailAvailable", "Validation", "", ErrorMessage = "este email já está sendo usado por outro usuário.")] [Display(Name = "Email", Order = 2, GroupName = "Noivo")] [StringLength(180)] public string EmailGroom { get; set; } [Required(ErrorMessage = "campo obrigatório")] [Display(Name = "Primeiro nome", Order = 0, GroupName = "Noiva")] [StringLength(60)] public string FistNameBride { get; set; } [Required(ErrorMessage = "campo obrigatório")] [Display(Name = "Último nome", Order = 1, GroupName = "Noiva")] [StringLength(60)] public string LastNameBride { get; set; } [Required(ErrorMessage = "campo obrigatório")] [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Formato de email inválido.")] [DataType(DataType.EmailAddress)] [Remote("IsEmailAvailable", "Validation", "", ErrorMessage = "este email já está sendo usado por outro usuário.")] [Display(Name = "Email", Order = 2, GroupName = "Noiva")] [StringLength(180)] public string EmailBride { get; set; } [Required(ErrorMessage = "campo obrigatório")] [Display(Name = "Url")] [RegularExpression(@"^[a-zA-Z0-9_\-\.\+]{5,22}$", ErrorMessage = "Chave inválida")] [StringLength(22, MinimumLength = 5, ErrorMessage = "A chave deve ter entre {0} e {1} caracteres.")] [Remote("IsKeywordAvaliable", "Validation")] public string UrlKeyword { get; set; } [Display(Name = "Voce é humano?")] [UIHint("ReCaptcha")] public string ReCaptcha { get; set; } } Domain Object public class Couple { [Key] public Guid Id { get; set; } public string UrlKeyword { get; set; } public virtual Partner Groom { get; set; } public virtual Partner Bride { get; set; } public DateTime Marriage { get; set; } public DateTime Dating { get; set; } public DateTime Engagement { get; set; } public virtual ICollection<User> Users { get; set; } } If you look you will see that my object Couple domain has the properties has Bride and Groom which are actually the same type. How can I map my domain object Couple with the RegisterCoupleModel? Here I made it as far as: In settings automapper tried to do something like: CreateMap<RegisterCoupleModel, Couple>() .ForMember(dest => dest.Bride.User.FirstName, opt => opt.MapFrom(source => source.FistNameBride)) .ForMember(dest => dest.Bride.User.LastName, opt => opt.MapFrom(source => source.LastNameBride)) .ForMember(dest => dest.Bride.User.Email, opt => opt.MapFrom(source => source.EmailBride)) .ForMember(dest => dest.Groom.User.FirstName, opt => opt.MapFrom(source => source.FistNameGroom)) .ForMember(dest => dest.Groom.User.LastName, opt => opt.MapFrom(source => source.LastNameGroom)) .ForMember(dest => dest.Groom.User.Email, opt => opt.MapFrom(source => source.EmailGroom)); But the error below is displayed: Expression 'dest => dest.Bride.User.FirstName' must resolve to top-level member. Parameter name: lambdaExpression I know this takes the act of trying to use to map properties with nested types. But how can I map RegisterCoupleModel to Couple and the two properties Bride and Groom are the same type? I found a question here on StackOverflow that looks like this, but it helped me. A: What i would do is encapsulate the properties for FirstNameBride, LastNameBride, EmailBride, FirstNameGroom, LastNameGroom, EmailGroom into a nested viewmodel type, let's say PersonDetails: public class PersonDetails { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } And update your parent VM accordingly: public class RegisterCoupleModel { public PersonDetails GroomDetails { get; set; } public PersonDetails BrideDetails { get; set; } } Then you can provide the mapping from PersonDetails to User (or whatever type Groom.User is): Mapper.CreateMap<PersonDetails,User>(); Note how i've got so explict property mapping -> because the fields have the same name in the source and destination, so no explicit mapping is required. Always try and do this where possible. Less code -> better code. Then in addition to the above mapping, simply do this: Mapper.CreateMap<RegisterCoupleModel, Couple>(); And AutoMapper will see that RegisterCoupleModel has two PersonDetails objects, see it already has a mapping definition, then automatically use that. That should work (i've done it before). You shouldn't always use flat viewmodels, nest them where necessary (such as reusing fields).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: break javascript one line code to readable code I have seen people put all their JS code into one single line. (something like this: http://www.drasticdata.nl/DrasticTreemap/Examples/js/swfobject.js) I know they are trying to protect their IP. But I want to read the code and study it. Is there a way to make those one-line code readable? For example, break it down to multiple lines? Thanks. A: A quick google search for "JavaScript de-obfuscator" will return you multiple online parsers that format obfuscated code into something formatted and readable. The following works pretty well: http://jsbeautifier.org/ There is no way to rename variable names to their, once semantic, forms. Something you'll have to tread through... A couple of terms to note minification and obfuscation: Minification (Wikipedia) Minification (also minimisation or minimization), in computer programming languages and especially JavaScript, is the process of removing all unnecessary characters from source code, without changing its functionality. Obfuscation (Wikipedia) Obfuscated code is source or machine code that has been made difficult to understand for humans. Programmers may deliberately obfuscate code to conceal its purpose (security through obscurity) or its logic to prevent tampering, deter reverse engineering, or as a puzzle or recreational challenge for someone reading the source code. Programs known as obfuscators transform readable code into obfuscated code using various techniques. References http://en.wikipedia.org/wiki/Obfuscated_code http://en.wikipedia.org/wiki/Minification_(programming) A: for eg. this tool has "pretty print" option: http://closure-compiler.appspot.com/home . Some IDEs (eclipse) has it too. A: You're looking for http://jsbeautifier.org/ A: For pretty much any language, just google for a "beautifier". They'll handle all indentation etc., but obviously any shortened variables or obfuscation can't easily be dealt with. A: You could paste the source into a Javascript beautifier, but you're still stuck with the problem of having variable names that make no sense. Considering the source is SWFObject, it is an opensource script by google, and the link to its project home page is in the source you posted: http://code.google.com/p/swfobject/ You can download the non-obfuscated code at that link. A: If you are using Chrome, there is a Pretty Print button in the scripts panel of the developer tools. This is probably much easier than going to a web app constantly. http://cristian-radulescu.ro/article/pretty-print-javascript-with-google-chrome.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7604585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to hide miniprofiler? I'm using MVC Mini profiler to check the speed of specific parts of my application, and would like to keep it there just in case something happens later and I may need to check "what's going wrong". It's not a full log set, but it comes pretty in handy to know what's making a page take long. So, my goal is to hide it and have it profile only when the request comes with a specific parameter. However, none of my attempts have worked in the way that I would expect. This has done the trick of not showing it on the screen (code in a view): @if (Request.QueryString.AllKeys.Contains("showProfiler")) { @MvcMiniProfiler.MiniProfiler.RenderIncludes() } This is the attempt that got closer. Correctly hides the mini profiler info, but at the moment I show it, it profiles everything since I stopped showing it. So, let's say that I profile my page and it takes 3 seconds. I remove the query parameter and load the page three more times. I add my parameter again and I see 4 sets of profile information. That implies that it keeps track of everything and I wonder it if could give memory issues. Attempts to make that not happen anymore: Attempt 1: protected void Application_BeginRequest() { if (Request.QueryString.AllKeys.Contains("showProfiler")) { MiniProfiler.Start(); } } Attempt 2: protected void Application_EndRequest() { MiniProfiler.Stop(!Request.QueryString.AllKeys.Contains("showProfiler")); } Attempt 3: protected void Application_EndRequest() { MiniProfiler.Stop(true); } None of these worked. Any ideas? A: The home page (see the "Abandoning a Profiler Session section) of the profiler has the usage pattern are looking for: protected void Application_BeginRequest() { MvcMiniProfiler.MiniProfiler.Start(); } protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if(!CurrentUserIsAllowedToSeeProfiler()) { MvcMiniProfiler.MiniProfiler.Stop(discardResults: true); } } Your implementation of CurrentUserIsAllowedToSeeProfiler will be checking if the query string contains the key the trigger the profiler. EDIT: You can also look at their Example Project to see how they implement disabling it in certain situation. Their check is to see if you are accessing it via localhost, but you could of course change that to check the query string instead. Based on that, it appears that "Attempt #1" should be the trick. Do note that the difference between the one "that is close" and "attempt #1" is the former is looking for query string profiling, whereas your Attempt #1 is checking for showProfiler. Could it have just been a simple query string mixup? A: Just start the profiler like normal in your begin request event. Then in your controller or view, check for the query string and call MiniProfiler.Stop(true) to discard the profiled data if it doesn't or is set to false. protected void Application_BeginRequest() { MiniProfiler.Start(); } Then in your view: @if(!Request.QueryString.AllKeys.Contains("profiling")) { MiniProfiler.Stop(true); } A: I did't find a solution in above. For me the only solution was to set the debug="false" in the Web.Config file. <compilation defaultLanguage="c#" debug="false" batch="false" targetFramework="4.5.2"> Hope this helps for other as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: iOS trace in XCode 4? I'm working on an iOS project and am trying to find out how I can go about getting a trace of all the functions that are being called when I do something on my emulator. The reason I'm looking for something like this is because I'm not quite sure what listeners are being triggered upon some of my actions on the emulator. Cheers and thanks again. A: Set a breakpoint? I'd read Apple's guide to debugging first, but just click the sidebar to the left of the line of code you want to stop at, and a blue indicator will appear. Then when you run the app, it will break when that line of code is hit. From there you can look at the stack using the acessory view on the bottom (where NSLog outputs, there are two views... one has the stack trace). A: When your debugging a large code base with multiple listeners, it's sometimes tough to figure out where to put the right break point. Another option is to log to see all the listeners that are triggered. However, a big issue with NSLog is you'll end up littering your code and then eventually want to remove it before shipping. Ideally, you could: * *Add logging/tracing throughout your code *Enable/Disable the logging at levels *Optionally turn it off for retail shipping. I have logging macros which offers those which I pieced together from others and I responded to this SO article and pasted in the implementation. What logging solutions to use while log-debugging objective-C code? Hope that helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7604602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Having issue with Javascript Here is my code: JS PART $(document).ready(function(){ $("#parent").hide(); $(".parentcheck").click(function(){ if($(this).val()==="1") { $("#parent").show(); $('#switch').attr('disabled', ''); } else { $("#parent").hide(); $('#switch').attr('disabled', 'disabled'); } }); $("#switch").change(function () { var selectedSwitch = $("#switch").val(); var parentcheck = $(".parentcheck:checked").val(); if (selectedSwitch!='' && selectedSwitch!='0'){ $.ajax({ type: "POST", url : "optionsgenerator.php", data: {menu: selectedSwitch}, success: function(result, status, xResponse){ if (result!=''){ if($('#parentcheck').attr('checked')){ $("#parent").hide(); } else { $("#parent").html(result); $("#parent").show(); } } else{ alert('Error occured.'); $("#parent").hide(); } }, error: function(e){ alert(e); } }); } else $("#parent").hide(); }); }); And HTML Markup <select name="switch" id="switch"> <option value="" selected="selected">Select one...</option> <option value="1">a</option> <option value="2">b</option> <option value="0">no one</option> </select> <div class="parent"> <input type="radio" class="parentcheck" name="parentcheck" value="0"/> <input type="radio" class="parentcheck" name="parentcheck" value="1"/> <select name="parent" id="parent"></select> </div> The problems is If value of radio button with class "parentcheck" is 1, my js shows selectbox without checking if it has something to show (in my case options returned from backend php code) or not I'm trying to achieve following If value of radio button with class "parentcheck" is 1 then show selectbox #parent ONLY if ajax has already returned something, enable selectbox #switch A: You are trying to get parentcheck by id, but parentcheck is a class: var parentcheck = $("#parentcheck:checked").val(); try to change it to var parentcheck = $(".parentcheck:checked").val(); EDIT: for the unselecting: if($(this).val()==="1") { if ($("#parent option").length > 0) { $("#parent").show(); } $('#switch').attr('disabled', ''); } else { $("#parent").hide().find('option:selected').removeAttr('selected'); $('#switch').attr('disabled', 'disabled').find('option:selected').removeAttr('selected'); } A: Solutions: 1) if(selectedSwitch != '' && selectedSwitch !=0) * *you are shorting your OR statement, needs to be an AND. 2) $(".parentcheck").click(function(){ if($(this).val() == "1") { $('#parent).show(); $('#switch').attr('disabled', ''); } else { $('#parent').val(''); $('#parent').hide(); $('#switch').val("Select one..."); $('#switch').attr('disabled', 'disabled'); } }); * *To set the value of the select, you need to give it the actual value of the index you want. 3) Set a boolean flag in your AJAX function, and then in the click listener only enable the selectbox if(flag).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vectorization vs. parallelization in R As a toy example, suppose that we have a function called 'my_func' (the code is below) that takes two parameters 'n' and 'p'. Our function, 'my_func', will generate a random matrix 'x' with 'n' rows and 'p' columns and do something expensive in both runtime and memory usage, such as computing the sum of the singular values of 'x'. (Of course, the function is a one-liner, but I am shooting for readability here.) my_func <- function(n, p) { x <- replicate(p, rnorm(n)) sum(svd(x)$d) } If we wish to compute 'my_func' for several values of 'n', and for each value of 'n' we have several values of 'p', then vectorizing the function and then applying it the combinations to 'my_func' is straightforward: n <- 10 * seq_len(5) p <- 100 * seq_len(10) grid <- expand.grid(n = n, p = p) my_func <- Vectorize(my_func) set.seed(42) do.call(my_func, grid) [1] 98.61785 195.50822 292.21575 376.79186 468.13570 145.18359 [7] 280.67456 421.03196 557.87138 687.75040 168.42994 340.42452 [13] 509.65528 683.69883 851.29063 199.08474 400.25584 595.18311 [19] 784.21508 982.34591 220.73215 448.23698 669.02622 895.34184 [25] 1105.48817 242.52422 487.56694 735.67588 976.93840 1203.25949 Notice that each call to 'my_func' can be painfully slow for large 'n' and 'p' (try n = 1000 and p = 2000 for starters). Now, in my actual application with a similarly constructed function, the number of rows in 'grid' is much larger than given here. Hence, I am trying to understand vectorizing in R a little better. First question: In the above example, are the calls to 'my_func' performed sequentially so that the the memory usage in one call is garbage collected before the next call? I use vectorization often but have never stopped to ask this question. Second question: (This question may depend on the first) Assuming that the number of calls is large enough and that 'my_func' is slow enough, is parallelization warranted here? I am presuming yes. My real question is: is parallelization warranted here if instead 'my_func' had the same large matrix passed to it for each call? For sake of argument, assume the matrix is called 'y', has 1000 rows and 5000 columns and is calculated on-the-fly. Of course, passing the matrix 'y' to each of the parallel nodes will incur some lag. I understand that the answer to the second question may be "It depends on..." If that is the case, please let me know, and I will try to give more detail. Also, I appreciate any advice, feedback, or OMFG WTF N00B YOU HAVEN'T SEEN THIS OTHER OBSCURE SOMEWHAT RELEVANT DISCUSSION??!!!111oneone1 A: The answer to the first question is pretty clearly yes: almost everything in R is by default serial. (A very few things internally start to use OpenMP, but R as an engine will likely remain single-threaded). So for the second question: Yes, do try that. I don't use Vectorize() much, but I do like the *apply() family. Solve it with lapply(), then load the multicore package and use mclapply() to run it over as many cores as yo u have. Here is an example: R> system.time(res <- lapply(1:nrow(grid), + function(i) my_func(grid[i,1],grid[i,2]))) user system elapsed 0.470 0.000 0.459 R> system.time(res <- mclapply(1:nrow(grid), + function(i) my_func(grid[i,1], grid[i,2]))) user system elapsed 0.610 0.140 0.135 R> Notice how elapsed time is now about 29% (= 0.135/0.459) of the original. From here you can generalize further with parallel execution across several machines--the Task View on High-Performane Computing with R has further pointers. R 2.14.0 due October 31 will have a new package 'parallel' which combines parts of multicore and snow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Emacs Ensime-sbt not responding to enter after I try to use RUN command I am using emacs to program in scala, now I installed ensime to be able to run SBT directly from emacs. I use C-c-C-v-s to launch a buffer for ensime-sbt. but when I type the run and hit enter nothing happens, how to make sbt run run ? It's working find in command line I am using Emacs 23 and Ensime in windows. Thanks A: Try adding "-Djline.WindowsTerminal.directConsole=false" to your sbt startup command. This fixed the problem for me. From here: http://code.google.com/p/simple-build-tool/wiki/IntegrationSupport
{ "language": "en", "url": "https://stackoverflow.com/questions/7604615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How does iOS's UISlider evaluate the position it's on? Is it linearly or logarithmically? I ask because I'm taking a Mobile Apps directed study and we're using Sam's Teach Yourself iPhone (2nd Edition, also, booooooo!). In Hour 8, if anyone has it, we make an animation, and we use a slider to determine how long it takes the animation to loop through. We're then supposed to make a manual entry option for how many loops per second. I have both of those implemented and have the slider change to what the manual entry was, but the only problem I can see is that when I enter a value in manually, it will cycle through the correct amount of loops and move the slider to the correct positioning, but whenever I set the speed of animation with the slider it seems to evaluate the values logarithmically instead of linearly. I have a range of .05 - 19.95 for the slider, so it starts at .05 and doesn't get passed the value '1' until like 4/5 of the way through, then it's from 1-20 the rest of the way and you pretty much have no accuracy on which number you get. Thanks for your time, if you need me to rephrase something let me know! *Revision Okay, here we go. ImageHopViewController.h: #import <UIKit/UIKit.h> @interface ImageHopViewController : UIViewController { IBOutlet UIImageView *images; IBOutlet UILabel *hps; IBOutlet UISlider *slider; IBOutlet UIButton *toggle; IBOutlet UITextField *manual; IBOutlet UIButton *go; } @property(retain, nonatomic) UIImageView *images; @property(retain, nonatomic) UILabel *hps; @property(retain, nonatomic) UISlider *slider; @property(retain, nonatomic) UIButton *toggle; @property(retain, nonatomic) UITextField *manual; @property(retain, nonatomic) UIButton *go; -(IBAction)toggleAnimation:(id)sender; -(IBAction)setSpeed:(id)sender; -(IBAction)manualEntry:(id)sender; @end ImageHopViewController.m: #import "ImageHopViewController.h" #import "ImageHopViewController.h" @implementation ImageHopViewController @synthesize images; @synthesize hps; @synthesize slider; @synthesize toggle; @synthesize manual; @synthesize go; -(IBAction)toggleAnimation:(id)sender{ if(images.isAnimating) { [images stopAnimating]; [toggle setTitle:@"Begin!" forState:UIControlStateNormal]; }else{ [images startAnimating]; [toggle setTitle:@"Desist!" forState:UIControlStateNormal]; } } -(IBAction)setSpeed:(id)sender { NSString *hopRate; images.animationDuration=20-slider.value; [images startAnimating]; [toggle setTitle:@"Desist!" forState:UIControlStateNormal]; hopRate=[[NSString alloc] initWithFormat:@"%1.2f", 1/(20-slider.value)]; hps.text=hopRate; [hopRate release]; } -(IBAction)manualEntry:(id)sender{ NSString *hopRate; NSString *manualValue; float value; manualValue=manual.text; value=[manualValue floatValue]; slider.value=value; images.animationDuration=1/slider.value; [images startAnimating]; [toggle setTitle:@"Desist!" forState:UIControlStateNormal]; hopRate=[[NSString alloc] initWithFormat:@"%1.2f", 1/(20-slider.value)]; hps.text=manualValue; [hopRate release]; } - (void)dealloc { [images dealloc]; [hps dealloc]; [slider dealloc]; [toggle dealloc]; [manual dealloc]; [go dealloc]; [super dealloc]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { NSArray *animation; animation=[[NSArray alloc] initWithObjects: [UIImage imageNamed:@"frame-1.png"], [UIImage imageNamed:@"frame-2.png"], [UIImage imageNamed:@"frame-3.png"], [UIImage imageNamed:@"frame-4.png"], [UIImage imageNamed:@"frame-5.png"], [UIImage imageNamed:@"frame-6.png"], [UIImage imageNamed:@"frame-7.png"], [UIImage imageNamed:@"frame-8.png"], [UIImage imageNamed:@"frame-9.png"], [UIImage imageNamed:@"frame-10.png"], [UIImage imageNamed:@"frame-11.png"], [UIImage imageNamed:@"frame-12.png"], [UIImage imageNamed:@"frame-13.png"], [UIImage imageNamed:@"frame-14.png"], [UIImage imageNamed:@"frame-15.png"], [UIImage imageNamed:@"frame-16.png"], [UIImage imageNamed:@"frame-17.png"], [UIImage imageNamed:@"frame-18.png"], [UIImage imageNamed:@"frame-19.png"], [UIImage imageNamed:@"frame-20.png"], nil ]; images.animationImages=animation; images.animationDuration=10; [animation release]; [super viewDidLoad]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return YES; } @end The NIB file just has a UIImageView (images), a UISlider (slider) for the animation speed, a UILabel (hps) for displaying the "hops per second", a UIButton (toggle) to toggle the animation, a UITextField (manual) for manual entry and another UIButton (go) to start the animation with the entered text converted to float. Since I have (id) for the object type that's being received, would that affect it in anyway? I'm still new to this so how would I go about remedying this? A: The UISlider is linear between its minimumValue (left) and maximumValue (right). You may want to check the continuous property to see if that isn't the culprit: continuous Contains a Boolean value indicating whether changes in the sliders value generate continuous update events. @property(nonatomic, getter=isContinuous) BOOL continuous Discussion If YES, the slider sends update events continuously to the associated target’s action method. If NO, the slider only sends an action event when the user releases the slider’s thumb control to set the final value. The default value of this property is YES. A: UISlider is definitely linear. A quick NSLog in action method should show this (NSLog(@"Slider value %f", sender.value);). Offhand, I would say your issue is probably with type casting (unintentionally converting your float to an int somewhere). I'd have to see code to confirm or deny that tho. A: *Solution Okay, the animationDuration inside setSpeed needed to be changed to images.animationDuration=1/slider.value; and the float inserted into hopRate in setSpeed needed to be changed to just slider.value instead of 1/(20-slider.value)];.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Call external program from python and get its output I want to call a program (.exe), which is written in C++ and compiled, from Python. The executable takes as input two files and returns a score. I need to do this for multiple files. So, I would like to write a small script in python which loops over multiple files, passes them to the executable and gets back the values. Now, I have done my search and I know about SWIG and Boost::Python may be an option but I was trying to find if there is an easier way. I do not need to 'extend' the C++ program. I simply want to call it just like I would from a command line and get the returned number. A: To run an external program and get its output, use subprocess.check_output on Python 2.7+. The example from the docs: >>> subprocess.check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' check_call just returns the return code of the program, not the output. A: You can use the subprocess module for that. result = subprocess.check_output(['your_program.exe', 'arg1', 'arg2'])
{ "language": "en", "url": "https://stackoverflow.com/questions/7604621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is swscanf substring formatting ([a-z]) implemented for osx standard lib? The following code works on windows, but not on osx. The docs on swscanf say that: "...some implementations of wscanf() use "A-Z" to represent the range of characters between 'A' and 'Z'. " By some implementations, does it mean that osx doesn't implement it? int main(int argc, const char* argv[]) { { wchar_t foo[] = L"bif3.zip"; wchar_t buh[10] = L""; int val = 0; wchar_t ext[4] = L""; int s = swscanf(foo, L"%[a-z]%d.%ls", buh, &val, ext); wprintf(L"wchar: %ls %d %ls\n", buh, val, ext); } { char foo[] = "bif3.zip"; char buh[10] = ""; int val = 0; char ext[4] = ""; int s = sscanf(foo, "%[a-z]%d.%s", buh, &val, ext); printf("char: %s %d %s\n", buh, val, ext); } } result: wchar: 0 char: bif 3 zip A: The man page for swscanf(3) states the following under the Bugs section: In addition to the bugs documented in scanf(3), wscanf() does not support the “A-Z” notation for specifying character ranges with the character class conversion (‘%[’). Feel free to file a bug report with Apple.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: user authentication package I need a quick and dirty way to authenticate user(GUI is also included) in java web start app, how/where can I find one? if I need to make it a webapp (war file), that's fine too. A: In which approach do you want to authenticate the user? Local authentication or third-party based authentication? Don't known any utilizable library for local authentication. However, openID or oAuth can be employed if you want trusty service provider help you complete.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET C# Session Variables Being Lost I have a solution which includes 2 projects and 2 class files that are called by reference. In one of my projects, I have some code in Global.asax in the Session_Start block that loads a few variables from a database and sets them into session variables. If I put a break point in the Global.asax I can verify that the variables are in fact being set correctly. When I reference the session variables in classes in any of my code-behind modules or a class in my project, they are there. But if I reference them in one of the classes that is called by reference (a shared class, essentially), the Session variables are all null. I am using HttpContext.Current.Session["varName"] to access the variables in a class, as is standard. Is there something else I need to consider to have access to these session variables? Could it perhaps be a namespace issue? A: I had the same issue before, I keep on losing the my session variables (although not in the same context as yours). I found this articles helpful for my issue: ASP.NET Case Study: Lost session variables and appdomain recycles and PRB: Session Data Is Lost When You Use ASP.NET InProc Session State Mode. Hope it might help you too. Cheers! A: Are you calling Session.Abandon() anywhere in the code? I was doing this at the start of my Web App to ensure I was starting with a "fresh" session. Turns out that any Session variables stored even after the "Abandon" would be dropped (even if the SessionID was forced to remain the same via other means, such as using Server.Transfer(Url, true) rather than Response.Redirect), upon postback. i.e. I could trace into my app, watch all the session variables be correctly set, and then the moment any event handler (anything with AutoPostBack="True", like a checkbox or button on an UpdatePanel) was called, BAM, I had the same SessionID, but zero session variables. Removing the pre-emptive call to Session.Abandon() solved my problem straightaway. Jeff A: Check Maximum Worker Process property set to 1 in your AppPool Advanced Settings window. If you unintentionally set greater than 1, the application pool will be a Web Garden so you cannot find Session nor Application variables even though they still exists inside one of them. Click here for more information
{ "language": "en", "url": "https://stackoverflow.com/questions/7604632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how to automatically post status on twitter Does anyone know how to post automatically on twitter like Facebook has... In facebook, there is API/SDK that allows PHP to post status to visitors wall if they allow my application to do that, but what about twitter? I know that it's possible, but I don't know how... I found 2 ways online to post with twitter with PHP script BUT: * *Request me to insert my username/password ( which I think users won't insert ) *Use my customer ID/secret found on application page, but then it post to my twitter, not to visitors Is there any way to post to twitter using PHP but for my visitors on site, not for myself? Something like allowing application to post instead of them like facebook has... Can someone help me with that? A: You need to have the user authenticated using oAuth, and then store their credentials in a DB and use that to post the status updates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android populate spinner from php/mysql query I am using the CustomHttpClient to connect and do queries from my android app. I was wondering if it was possible to populate a spinner from a php/mysql query and if so how it would be done? A: So this should actually be fairly easy. You haven't really given us much to work on in terms of implementations details so I'll do my best to semi-psuedo code things out for you and give you a good general answer. We're going to want to do the query from a separate thread so as to not block the UI thread while we're waiting for a network response. You can do this many different ways including using an AsyncTask, IntentService, or some sort of Loader. I'm thinking in your case a custom class derived form the AsyncTaskLoader class will be the best. So lets see how this would look (note you'll need access to some of the newer apis in order to use the loader, checkout the http://developer.android.com/resources/articles/backward-compatibility.html if you're writing this application for anything less than api level 11). MyActivity extends Activity implements LoaderManager.LoaderCallbacks<List<SpinnerItem>>{ private Adapter<SpinnerItem> spinnerAdapter; private static final int SPINNER_LOADER_ID = 0; public void onCreate(Bundle icicle){ Spinner theSpinner = findViewById(R.id.the_spinner); spinnerAdapater = new Adapter<SpinnerItem>(...); //create empty adapter spinnerAdapater.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); theSpinner.setAdapter(spinnerAdapater); getLoaderManager().initLoader(SPINNER_LOADER_ID, null, this); } public Loader<List<SpinnerItems>> onCreateLoader(int id, Bundle arg){ //Create and return your loader } public void onLoadFinish(Loader<List<SpinnerItem>> loader, List<SpinnerItem> data){ //update your adapater with the new data } public void onLoaderReset(Loader<List<SpinnerItem>> loader){ //clear out all the data in the adapter } } This is all pretty straight-forward stuff here. You should be able to fill in the gaps by reading about loaders, adapters, etc. on the Android dev pages. The fact that we're using a "List" full of "SpinnerItem"s is of course going to be dependent on your particular implementation, as is the type of adapter you choose to use. Feel free to choose whatever actual data structures you want. Once again, consult the Android dev pages for details. As far as the loader class goes, you'll wanna do something like this: MyNetworkLoader extends AsyncTaskLoader<List<SpinnerItem>> public MyNetworkLoader(Context context){ super(context); } List<SpinnerItem> loadInBackground(){ //Get data from server } } In the loadInBackground method you'll use your CustomHttpClient to query your server and convert the response into some sort of data structure (just as before, in this example we're using a "List" of "SpinnerItem"s). As a final note, your spinner is going to be empty until your network request completes. You may want to include some sort of logic informing the user that the contents of the spinner are loading. That's it. The new loader api's make things really simple. A: Yes its possible. Retrieve the a list of items using the php/mysql query and then provide those items to the spinner using an Adapter. This question provides an exmample of how to write an SpinnerAdapter: How to correctly overwrite methods of SpinnerAdapter
{ "language": "en", "url": "https://stackoverflow.com/questions/7604634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Better to 'try' something and catch the exception or test if it's possible first to avoid an exception? Should I test if something is valid or just try to do it and catch the exception? * *Is there any solid documentation saying that one way is preferred? *Is one way more pythonic? For example, should I: if len(my_list) >= 4: x = my_list[3] else: x = 'NO_ABC' Or: try: x = my_list[3] except IndexError: x = 'NO_ABC' Some thoughts... PEP 20 says: Errors should never pass silently. Unless explicitly silenced. Should using a try instead of an if be interpreted as an error passing silently? And if so, are you explicitly silencing it by using it in this way, therefore making it OK? I'm not referring to situations where you can only do things 1 way; for example: try: import foo except ImportError: import baz A: Using try and except directly rather than inside an if guard should always be done if there is any possibility of a race condition. For example, if you want to ensure that a directory exists, do not do this: import os, sys if not os.path.isdir('foo'): try: os.mkdir('foo') except OSError, e print e sys.exit(1) If another thread or process creates the directory between isdir and mkdir, you'll exit. Instead, do this: import os, sys, errno try: os.mkdir('foo') except OSError, e if e.errno != errno.EEXIST: print e sys.exit(1) That will only exit if the 'foo' directory can't be created. A: If it's trivial to check whether something will fail before you do it, you should probably favor that. After all, constructing exceptions (including their associated tracebacks) takes time. Exceptions should be used for: * *things that are unexpected, or... *things where you need to jump more than one level of logic (e.g. where a break doesn't get you far enough), or... *things where you don't know exactly what is going to be handling the exception ahead of time, or... *things where checking ahead of time for failure is expensive (relative to just attempting the operation) Note that oftentimes, the real answer is "neither" - for instance, in your first example, what you really should do is just use .get() to provide a default: x = myDict.get('ABC', 'NO_ABC') A: As the other posts mention, it depends on the situation. There are a few dangers with using try/except in place of checking the validity of your data in advance, especially when using it on bigger projects. * *The code in the try block may have a chance to wreak all sorts of havoc before the exception is caught - if you proactively check beforehand with an if statement you can avoid this. *If the code called in your try block raises a common exception type, like TypeError or ValueError, you may not actually catch the same exception you were expecting to catch - it may be something else that raise the same exception class before or after even getting to the line where your exception may be raised. e.g., suppose you had: try: x = my_list[index_list[3]] except IndexError: x = 'NO_ABC' The IndexError says nothing about whether it occurred when trying to get an element of index_list or my_list. A: Should using a try instead of an if be interpreted as an error passing silently? And if so, are you explicitly silencing it by using it in this way, therefore making it OK? Using try is acknowledging that an error may pass, which is the opposite of having it pass silently. Using except is causing it not to pass at all. Using try: except: is preferred in cases where if: else: logic is more complicated. Simple is better than complex; complex is better than complicated; and it's easier to ask for forgiveness than permission. What "errors should never pass silently" is warning about, is the case where code could raise an exception that you know about, and where your design admits the possibility, but you haven't designed in a way to deal with the exception. Explicitly silencing an error, in my view, would be doing something like pass in an except block, which should only be done with an understanding that "doing nothing" really is the correct error handling in the particular situation. (This is one of the few times where I feel like a comment in well-written code is probably really needed.) However, in your particular example, neither is appropriate: x = myDict.get('ABC', 'NO_ABC') The reason everyone is pointing this out - even though you acknowledge your desire to understand in general, and inability to come up with a better example - is that equivalent side-steps actually exist in quite a lot of cases, and looking for them is the first step in solving the problem. A: Whenever you use try/except for control flow, ask yourself: * *Is it easy to see when the try block succeeds and when it fails? *Are you aware of all side effects inside the try block? *Are you aware of all cases in which the try block throws the exception? *If the implementation of the try block changes, will your control flow still behave as expected? If the answer to one or more of these questions is 'no', there might be a lot of forgiveness to ask for; most likely from your future self. An example. I recently saw code in a larger project that looked like this: try: y = foo(x) except ProgrammingError: y = bar(x) Talking to the programmer it turned that the intended control flow was: If x is an integer, do y = foo(x). If x is a list of integers, do y = bar(x). This worked because foo made a database query and the query would be successful if x was an integer and throw a ProgrammingError if x was a list. Using try/except is a bad choice here: * *The name of the exception, ProgrammingError, does not give away the actual problem (that x is not an integer), which makes it difficult to see what is going on. *The ProgrammingError is raised during a database call, which wastes time. Things would get truly horrible if it turned out that foo writes something to the database before it throws an exception, or alters the state of some other system. *It is unclear if ProgrammingError is only raised when x is a list of integers. Suppose for instance that there is a typo in foo's database query. This might also raise a ProgrammingError. The consequence is that bar(x) is now also called when x is an integer. This might raise cryptic exceptions or produce unforeseeable results. *The try/except block adds a requirement to all future implementations of foo. Whenever we change foo, we must now think about how it handles lists and make sure that it throws a ProgrammingError and not, say, an AttributeError or no error at all. A: In this particular case, you should use something else entirely: x = myDict.get("ABC", "NO_ABC") In general, though: If you expect the test to fail frequently, use if. If the test is expensive relative to just trying the operation and catching the exception if it fails, use try. If neither one of these conditions applies, go with whatever reads easier. A: You should prefer try/except over if/else if that results in * *speed-ups (for example by preventing extra lookups) *cleaner code (fewer lines/easier to read) Often, these go hand-in-hand. speed-ups In the case of trying to find an element in a long list by: try: x = my_list[index] except IndexError: x = 'NO_ABC' the try, except is the best option when the index is probably in the list and the IndexError is usually not raised. This way you avoid the need for an extra lookup by if index < len(my_list). Python encourages the use of exceptions, which you handle is a phrase from Dive Into Python. Your example not only handles the exception (gracefully), rather than letting it silently pass, also the exception occurs only in the exceptional case of index not being found (hence the word exception!). cleaner code The official Python Documentation mentions EAFP: Easier to ask for forgiveness than permission and Rob Knight notes that catching errors rather than avoiding them, can result in cleaner, easier to read code. His example says it like this: Worse (LBYL 'look before you leap'): #check whether int conversion will raise an error if not isinstance(s, str) or not s.isdigit(): return None elif len(s) > 10: #too many digits for int conversion return None else: return int(s) Better (EAFP: Easier to ask for forgiveness than permission): try: return int(s) except (TypeError, ValueError, OverflowError): #int conversion failed return None A: For a general meaning, you may consider reading Idioms and Anti-Idioms in Python: Exceptions. In your particular case, as others stated, you should use dict.get(): get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "150" }
Q: Transfering data between two Android devices in a WLAN In this question I asked how (programatically) was the best way to transfer data in the context referred in title - it was suggested connection through Sockets which I accepted, but now I have other problem (the reason why I'm creating another question) The problem is, I did the Socket communication, but I faced the problem of the open ports availability. The app I want to do meant to be independent of the Wireless Network - because it will be something I (the user) can't control - so it should work on most WLAN. So my questions are: * *Connection through Sockets between two devices, always need open ports on the router/host? If yes, there's any efficient way to search through ports efficiently? If not: *There's any good alternative for connection through Wireless? If not some of you of are probably thinking in Bluetooth connection but because in my app that requires that BT is always on (bidireccional communcation should be user "transparent" and will not always happen, also also want to convert my app to a service). Guys, can you please give me some ideas? I appreciate very much any help. A: One of the basic functions of a router is to pass network traffic between connected devices. When sending data from between devices connected to the same router you don't need to worry about the router blocking traffic on specific ports, unless the router has been programmed to do so. However, most routers are not programmed to do this for internal traffic. If you want to know if a port is available you can simply try to bind it. If the port is taken then you won't be able to bind it. Its that simple.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to bind a 1:many relation in Interface Builder I have a simple Core Data app with to model objects: employee and notes. Employees can have many notes (1:many), each note belongs to one employee (1:1). In the employee window I display a list (NSTableView) of employees on file using an NSArrayController. Clicking on an employee displays their details next to the list (name address, gender etc.). Now, I would also like to display a list (also NSTableView) of the notes on file for the selected employee. The list should display 2 attributes of each note on file: its topic and its entry date). I tried to do the following: (1) bind the date column of the table to the Employee controller, controller key: selection, model key path: notes.date (2) bind the topic column of the Employee controller, controller key: selection, model key path: notes.topic However this throws an exception (unrecognised selector). How do I correctly bind the notes attribute of an employee to the NSTableView? Can it be done "directly" using cocoa bindings in IB or is additional code required to access the notes attribute of an employee before I can set up the bindings? I checked the data written by Core Data and this looks all good. Many thanks for your help... EDIT: here's the stack trace from the debugger... 2011-09-30 00:46:56.010 EmployeeDemo[3843:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSFaultingMutableSet objectAtIndex:]: unrecognized selector sent to instance 0x10260b9c0' *** First throw call stack: ( 0 CoreFoundation 0x00007fff8c654986 __exceptionPreprocess + 198 1 libobjc.A.dylib 0x00007fff8b040d5e objc_exception_throw + 43 2 CoreFoundation 0x00007fff8c6e05ae -[NSObject doesNotRecognizeSelector:] + 190 3 CoreFoundation 0x00007fff8c641803 ___forwarding___ + 371 4 CoreFoundation 0x00007fff8c641618 _CF_forwarding_prep_0 + 232 5 AppKit 0x00007fff87c72648 -[NSTableBinder _visibleRowIndexesForObject:] + 267 6 AppKit 0x00007fff87c72291 -[NSTableBinder observeValueForKeyPath:ofObject:change:context:] + 131 7 Foundation 0x00007fff8dbb818a NSKeyValueNotifyObserver + 387 8 Foundation 0x00007fff8dbb21af -[NSObject(NSKeyValueObservingPrivate) _notifyObserversForKeyPath:change:] + 756 9 AppKit 0x00007fff876f1f0b -[NSController _notifyObserversForKeyPath:change:] + 206 10 AppKit 0x00007fff877fc5fc -[NSController observeValueForKeyPath:ofObject:change:context:] + 847 11 AppKit 0x00007fff879a1cf9 -[NSArrayController observeValueForKeyPath:ofObject:change:context:] + 98 12 Foundation 0x00007fff8dbb818a NSKeyValueNotifyObserver + 387 13 Foundation 0x00007fff8dbd9387 NSKeyValueDidChange + 486 14 Foundation 0x00007fff8dc6834b -[NSObject(NSKeyValueObservingPrivate) _didChangeValuesForKeys:] + 631 15 CoreData 0x00007fff8e827543 _PFFaultHandlerFulfillFault + 3619 16 CoreData 0x00007fff8e825bd8 _PFFaultHandlerLookupRow + 1592 17 CoreData 0x00007fff8e825254 _PF_FulfillDeferredFault + 212 18 CoreData 0x00007fff8e8250d8 _sharedIMPL_pvfk_core + 56 19 CoreData 0x00007fff8e85bd3e -[NSManagedObject valueForKey:] + 222 20 Foundation 0x00007fff8dbb479e -[NSObject(NSKeyValueCoding) valueForKeyPath:] + 348 21 AppKit 0x00007fff8799ded5 -[NSArrayController _multipleValueForKeyPath:atIndex:] + 84 22 AppKit 0x00007fff8799cfc9 -[NSArrayController _singleValueForKeyPath:] + 151 23 AppKit 0x00007fff87704cfe -[_NSControllerObjectProxy valueForKeyPath:] + 77 24 Foundation 0x00007fff8dbb4761 -[NSObject(NSKeyValueCoding) valueForKeyPath:] + 287 25 AppKit 0x00007fff87704baa -[NSBinder _valueForKeyPath:ofObject:mode:raisesForNotApplicableKeys:] + 654 26 AppKit 0x00007fff87704894 -[NSBinder valueForBinding:resolveMarkersToPlaceholders:] + 171 27 AppKit 0x00007fff87907352 -[NSValueBinder _referenceBindingValue] + 31 28 AppKit 0x00007fff87907163 -[NSValueBinder _adjustObject:mode:observedController:observedKeyPath:context:editableState:adjustState:] + 647 29 AppKit 0x00007fff87906e48 -[NSValueBinder _observeValueForKeyPath:ofObject:context:] + 303 30 AppKit 0x00007fff8791ed0b -[NSTextValueBinder _observeValueForKeyPath:ofObject:context:] + 43 31 Foundation 0x00007fff8dbb818a NSKeyValueNotifyObserver + 387 32 Foundation 0x00007fff8dbb21af -[NSObject(NSKeyValueObservingPrivate) _notifyObserversForKeyPath:change:] + 756 33 AppKit 0x00007fff876f1f0b -[NSController _notifyObserversForKeyPath:change:] + 206 34 AppKit 0x00007fff8795e7a5 -[NSArrayController didChangeValuesForArrangedKeys:objectKeys:indexKeys:] + 120 35 AppKit 0x00007fff879601bd -[NSArrayController setContent:] + 870 36 AppKit 0x00007fff879a2664 -[NSArrayController(NSManagedController) _performFetchWithRequest:merge:error:] + 370 37 AppKit 0x00007fff87bb149e -[NSObjectController(NSManagedController) fetchWithRequest:merge:error:] + 177 38 AppKit 0x00007fff87bb1522 -[NSObjectController(NSManagedController) _executeFetch:didCommitSuccessfully:actionSender:] + 92 39 AppKit 0x00007fff87d932e7 _NSSendCommitEditingSelector + 30 40 AppKit 0x00007fff87a50246 -[NSController _controllerEditor:didCommit:contextInfo:] + 188 41 libdispatch.dylib 0x00007fff847df90a _dispatch_call_block_and_release + 18 42 libdispatch.dylib 0x00007fff847e177a _dispatch_main_queue_callback_4CF + 308 43 CoreFoundation 0x00007fff8c5e9c0c __CFRunLoopRun + 1724 44 CoreFoundation 0x00007fff8c5e9216 CFRunLoopRunSpecific + 230 45 HIToolbox 0x00007fff871924ff RunCurrentEventLoopInMode + 277 46 HIToolbox 0x00007fff87199c21 ReceiveNextEventCommon + 355 47 HIToolbox 0x00007fff87199aae BlockUntilNextEventMatchingListInMode + 62 48 AppKit 0x00007fff876de191 _DPSNextEvent + 659 49 AppKit 0x00007fff876dda95 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 135 50 AppKit 0x00007fff876da3d6 -[NSApplication run] + 463 51 AppKit 0x00007fff8795852a NSApplicationMain + 867 52 EmployeeDemo 0x0000000100001a62 main + 34 53 EmployeeDemo 0x0000000100001a34 start + 52 ) terminate called throwing an exception EDIT 2: It seems that there's another problem which has to do with the underlying model. The notes for an employee are entered via a separate window with its own controller. It creates the new note and allows the user to set its properties (topic, body text). When the user presses the "Save" button the saveNote method is executed: - (IBAction)saveNote:(id)sender { [[self note] setValue: [[self topicField] stringValue] forKey: @"topic"]; [[self note] setValue: [[self textView] string] forKey: @"bodyText"]; [[self note] setValue: [self employee] forKey: @"employee"]; NSError *error = nil; if (![[self managedObjectContext] save:&error]) { //todo: add proper error handling NSLog(@"An error occurred while trying to save the memo"); } [[self window] close]; } When I step through this method the exception is actually generated when setting the relation between the note and the employee (3rd line). A: What you need is an NSArrayController whose content is bound to the relationship. Then you bind the NSTableView content to the NSArrayController. From there you can do the columns. UPDATE This tutorial from Apple might help you out. A: It appears that the behaviour described in my question has something to do with having a document based Core Date app or having a "plain" core data app (the check you place when you create a new project in XCode). I found that when I choose a document based core data app, the above problems do not occur. When I develop the same app as a non-document core data app, binding the notes controller generates the stack trace as shown in my original question and the exception is thrown as soon as I add a note to an existing employee. So, in all fairness this is just a part of the solution as my experience of Cocoa and XCode is not sufficient to explain why it will not work using the non-document based variant.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IActionFilter Redirect in MVC3 I am implementing an IActionFilter to authenticate the request in MVC3, if my authentication returns false I want to redirect the request to a different controller from within the IActionFilter. I would like to be able to kill the processing of the current request and totally redirect the request to a different controller action. I am also willing to use the IAuthorizationFilter but this appears for the most part the same as the IActionFilter. Thanks for the help. A: There are several ways to accomplish this - some good ways provided here: Redirecting to specified controller and action in asp.net mvc action filter In a nutshell you can either ctx.Response.Redirect() or create a new route as the result of your filter context. Ensure wherever you redirect to won't fail authentication though or you can get stuck in a loop unless you code in your specific url which is somewhat hacky. If you have a problem with this, post back we'll help you out, but that should work just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UPS worldship "date" field is in an unusable format I export records from UPS Worldship to Access and the date field called "Collectiondate" is not in a standard date/time format. Instead it outputs like "20110928" , but I want it to output like "9/28/11". please advise thanks in advance A: Starting with your string value, "20110928", you can transform it to a string which the CDate() function will recognize as a valid date ("2011-09-28"). Debug.Print Left("20110928", 4) & "-" & Mid("20110928", 5, 2) & "-" & _ Right("20110928", 2) You can then use CDate() to convert the string to a Date/Time value, and use Format() to convert that back to a string in your desired format. Debug.Print Format(CDate(Left("20110928", 4) & "-" & Mid("20110928", 5, 2) & _ "-" & Right("20110928", 2)), "m/d/yy") Since the string is in a field, Collectiondate, you can do something similar with a SELECT query. SELECT Format(CDate(Left(Collectiondate, 4) & "-" & Mid(Collectiondate, 5, 2) & "-" & Right(Collectiondate, 2)), "m/d/yy") AS Formatted_Collectiondate FROM UPS_CSV_EXPORT;
{ "language": "en", "url": "https://stackoverflow.com/questions/7604646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Appending asterisks to required fields when validation is conditional I have conditional validation and want to append an asterisk to the fields that are required. I could easily do this if i specify the class "required" to the fields however i am specifying the requireds using Rules, as some of the validation rules are conditional. For example, i have 3 radio buttons: (Home Tel, Work Tel, Cell) and 3 corresponding fields that are required depending on which radio is selected. I want to be able to append an asterisk initially to Home Tel field, however if Work Tel radio is selected then i want the Work Tel field to have the asterisk instead of the Home Tel as Work Tel becomes required and not Home Tel. Below is my conditions: hphone: { required: function(element){ return $('#phonePref:checked').val() == 0; } }, cPhone: { required: function(element){ return $('#phonePref:checked').val() == 2; } }, wphone: { required: function(element){ return $('#phonePref:checked').val() == 1; } }, What is the best way to handle this? In advance, thanks for your help. A: Your logic seems backwards... You should be structuring your html to automatically have the * already defined and then after you process for validation then use jquery to identify areas in your html that are required however, have not been filled in, ie your form as defined should require a phone option and the phone selection be a radio list once you select which phone will be primary (ie work phone) then require that particular phone number and set your conditional to it. Your going backwards to me...
{ "language": "en", "url": "https://stackoverflow.com/questions/7604648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: xpages and java frameworks there seems to be a rising hype in XPages for web development. so far all i see XPages is good for is quick development of Forms. It seems like a modern day version of VB what are the advantages of using xpages as oppose to other java frameworks? A: XPages is IBM's web and mobile application development platform for collaborative and social applications. As other platforms it's based on standards like Java, JavaScript, JSF and OSGi. The unique thing is that the infrastructure comes with everything you need to build and run applications. There is a built in document oriented database (though you can use relational databases), web server, directory, security, search functionality, etc. While the frontend part is rather new the backend components have been proven in production for almost two decades. Another unique thing are the rapid development and deployment mechanisms. XPages are built with an Eclipse based tool supporting drag and drop functionality for simpler applications but also full Java capabilities for advanced programming. Since the document oriented databases can store both the design and the data complete applications can be easily deployed. Furthermore these databases can be easily replicated to other databases wherever they are located. The community site http://xpages.info aggregates news, comes with demos, videos, open source applications, list resources and describes the technologies: http://xpag.es/?stackoverflow A: The main language of XPages is JavaScript. So you have JavaScript on the client and the server. This allows to loadbalance your development team better since they can work on both ends. Also Domino provides a robust NoSQL database (no more JDBC connection errors) that has an unparalleled declarative security model. Just by saving a respective field (type reader/author) you can define read/update access to every single record/document. This is WAY harder to do in any other platform (including Domino's mental offspring CouchDB). Domino is schema free, so the database never gets into the way of your rapid development cycle A: Another advantage of using XPages is the fact that it natively sits on top of a fully distributable and locally replicable data store that can be consumed by the Notes client. The security model of the Notes NSF file is unmatched and so provides additional benefits beyond the standards-based extensible dev environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the most efficient way in Java to pack bits into byte[] and read it back? I currently use these two functions to pack and read bits in a byte array. Wondering if anybody has any better ideas or faster ways to do it? Edited the program with a few more optimization and tabled a few calculations. Currently 100mil Put and Get takes about 12 secs instead of 16 secs now. If anybody is using the current code make sure the value passed in to Put is a positive number as it's expecting unsigned numbers coming down. If there is interest I can put up signed and unsigned versions. class BitData { static void Put(byte Data[], final int BitOffset, int NumBits, final int Value) { final long valLong=(Value&((1L<<NumBits)-1L)); int posByte=BitOffset>>3; int posBit=BitOffset&7; int valByte; int ModifyBits; long lValue; int LeftShift; ModifyBits=8-posBit; if(NumBits<ModifyBits) ModifyBits=NumBits; LeftShift=(8-posBit-ModifyBits); while(true) { valByte = Data[posByte]; if(ModifyBits==8) { lValue=valLong<<(32-NumBits)>>(24); Data[posByte]=(byte)lValue; } else { lValue=valLong<<(32-NumBits)>>(32-ModifyBits)<<LeftShift; Data[posByte]=(byte)((valByte & ~(((1<<ModifyBits)-1) << LeftShift)) | lValue); } NumBits-=ModifyBits; if(NumBits==0) break; posByte++; ModifyBits=8; if(NumBits<ModifyBits) { ModifyBits=NumBits; LeftShift=(8-ModifyBits); } } } static int GetInt(byte Data[], final int BitOffset, int NumBits) { int posByte=BitOffset>>3; int posBit=BitOffset&7; long Value=0; int ModifyBits; int valByte; int LeftShift; ModifyBits=8-posBit; if(NumBits<ModifyBits) ModifyBits=NumBits; LeftShift=(8-posBit-ModifyBits); while(true) { valByte = Data[posByte] & 0xff; if(ModifyBits==8) Value+=valByte; else Value+=(valByte & ((1<<ModifyBits)-1) << LeftShift) >> LeftShift; NumBits-=ModifyBits; if(NumBits==0) break; posByte++; ModifyBits=8; if(NumBits<ModifyBits) { ModifyBits=NumBits; LeftShift=(8-ModifyBits); } Value<<=ModifyBits; } return (int)Value; } } A: A totally different route would be to define static table of all possible combinations and perform a lookup instead of calculating results each time. I think thats how they do it in cryptography. array[i] x 3 should be much faster than numBits bitwise operations. It will occupy some heap though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: preventing xss in .net OWASP guidelines I've read the OWASP guidelines regarding preventing XSS. The guidelines seem to only refer to having a whitelist and encoding output. However, this leaves open the problem with so called free text fields e.g. the text box im writing in to make this post. Are there any preventative measures besides a black list (not desirable) that can be done server side when accepting free text fields. From the OWASP guidelines i get the impression that xss should just be allowed to be stored in the database and just sanitise it when ever it is displayed to the front end. I am however, a bit uncomfortable with this. Or do i have it wrong, is there a better way? A: XSS is an output problem. You can't have one catch all encoding or input validation function that works for all xss. Even by converting an input string to their htmlentities, your application can still be vulnerable to xss in dom events as well as another of other vectors. Its hard to keep all of these rules straight. Make sure to test your code, there are free XSS scanners such as Sitewatch and Skipfish. Storing HTML in the database isn't a vulnerability, but displaying it would be persistent XSS. Which is the worst form of xss. It is common to store the un-encoded version in the database because its makes the data consistent and better for text comparisons and matching. In SQL injection for MS-SQL you can stack queries so its possible to introduce an xss payload into the database. For instance select...; insert into comments (post)values('<script>alert(xss)</script>'). Don't trust your database. A: i get the impression that xss should just be allowed to be stored in the database and just sanitise it when ever it is displayed to the front end That is correct. Whichever anti-XSS encoding library/function you use to do the encoding will prevent the XSS attempt from working, by preventing the dodgy code being rendered as HTML when it is added to the page output. You should not attempt to scrub the input before storing it for much the same reason that you do not maintain a black list - it is too easy to get it wrong, and either scrub too much, or not enough. If you are going to attempt to scrub the input, you better know what you are doing. A: I lead the OWASP Guide, and I have matured my view on this since the Guide 2.0 was written back in 2004/2005. In my view, there's two phases you need to deal with: Input validation - you should always avoid allowing the incursion of XSS vectors into your data if at all possible. I have Views™, but honestly, the best bet is to strongly type and length restrict as far as you can. There's no point in allowing boolean or integer variables to be stored as a text column. The residual risk will be text areas stored in text blobs, which should be obvious when coding the presentation layer, whatever that may be. Output encoding - when the original Guide was written (2002), we were doing the Big 5, that's no longer true. You need to correctly output encode for the context, so if you're outputting to Ajax, you need to make it both JSON and JavaScript safe, as well as HTML safe. There's a new version of the Guide in the works, OWASP Guide 2013. I will be making sure this is correctly updated. Please log an issue on our project's Issues tracker, as you have a very valid concern: Log an issue in the OWASP Guide 2013 issue tracker The days of simply encoding for the big 5 are well and truly over. Particularly, as HTML is fairly unlikely to be the primary presentation layer going forward. Andrew van der Stock, OWASP Guide 2.0 / 2013 Guide Lead. A: So there are two things to note here. Input validation on the way in is done to make sure the data is valid according to the domain, and this stops some attacks, but definitely not all. Output encoding is done to make sure the data is not somehow parsed as HTML or javascript. So as described by Rook it is an output problem. You should see the OWASP XSS prevention cheat sheet which explains how to avoid XSS directly in the HTML page, and the OWASP DOM based XSS prevention cheat sheet to understand how to avoid XSS triggered by javascript reading and writing unsanitized or unencoded data. As mentioned by Rook, do not fall for the temptation of encoding or scrubbing the data on the way in, unless of course it's invalid according to your domain. There really is no way to encode properly before the output, because that's when you know which context you are encoding for. Is it an HTML attribute, a javascript string, a javascript string in an HTML attribute etc. And as mentioned by Rule#6 in the OWASP XSS prevention cheat sheet, if you want to allow some HTML user a white-list based engine like OWASP AntiSamy or HTMLPurifier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Gyroscope updates not starting I am creating test app that receives gyroscope pitch, roll and yaw. This code does not work as I would think it would: - (void) enableGyro { motionManager.deviceMotionUpdateInterval = 1.0/30.0; if (motionManager.gyroAvailable) { [motionManager startGyroUpdates]; } NSLog(@"Gyro Available? %@", (motionManager.gyroAvailable ? @"YES" : @"NO")); NSLog(@"Gyro Active? %@", (motionManager.gyroActive ? @"YES" : @"NO")); } The output of that is 2011-09-29 16:37:08.070 Gyro2[4014:607] Gyro Available? YES 2011-09-29 16:37:08.074 Gyro2[4014:607] Gyro Active? NO I don't understand why, when I begin the gyro updates, it does not actually start. A: According to documentation (http://developer.apple.com/library/ios/#DOCUMENTATION/CoreMotion/Reference/CMMotionManager_Class/Reference/Reference.html), gyroActive will only be true if you've called startGyroUpdatesToQueue:withHandler: or startGyroUpdates. Even though startDeviceMotionUpdates uses the gyroscope, it doesn't set gyroActive. A: If you really want to use raw unbiased sensor data, you have to set the update interval of every sensor independently although they often will be the same value: motionManager.gyroUpdateInterval = myGyroInterval; motionManager.accelerometerUpdateInterval = myAccelerometerInterval; The deviceMotionUpdateInterval is bound to device motions only. Most people don't want to handle sensor data processing with Kalman filter etc. but just the current orientation of the device. If that's the case, have a look at Simple iPhone motion detect. The only situation when I saw the values of CMMotionManager's xxxActive methods did not report the correct state was putting the app in background and activating it again when motion handling is done within an own NSThread. I think this related to some actions done by the operating system maybe combined with kind of racing condition. The trick then is to release CMMotionManager instance and allocate a new one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run Time Error - (pics) I've been testing my C++ server application recently, and when a few clients are connected and doing a variety of things, I've been getting the odd run time error which crashes the server. Could you help me - how do I debug the following error when all I have is these event viewer logs: The type of error was "C++ Server has stopped responding", with just an option to close the dialogue box. I couldn't even see the console. Please let me know if there's any other information I can provide. Thanks. A: I would recommend two courses of action for you to take: 1) Add sufficient logging (to a file or standard out) so that you can trace where the problem is coming from. 2) Run your server in a debugger so that you can pinpoint the location and type of the fault. This will give you a call stack and index to your source files if set up correctly I can recommend WinDbg as a standalone debugger for the task, though I would assume that you are using an IDE with debugging capability. If for some reason you can't run the server in a debugger, then you can at least attach one when the error occurs. So instead of Dr Watson giving you information WinDbg can attach to the process giving you a call stack and all the other goodness. A: Configure WER (Windows Error Reporting) on the server to save crash dumps of your crashing apps to the disk. Then load and inspect them in WinDbg. Don't forget to set the app's symbols file (.pdb) in the debugger to see the stacks and variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: as2 give background I wanto to make set background color the mc. 1.mc-2.mc-3.mc-my_mc This codes not show bacground. var bg_colour:Color = new Color(1_mc.2_mc.3_mc.my_mc); bg_colour.setRGB(0x6546a0); This codes show color. but my work does not. How can I do this? Thanks for answers. var bg_colour:Color = new Color(1_mc.2_mc); bg_colour.setRGB(0x6546a0); A: bg_colour = new Color("1_mc"); bg_colour.setRGB(0x6546a0); A: Why are you using a number as instance name prefix? This is not reccomended in Flash actionscript (and in any programming language). Use mc_1, mc_2 instead: var bg_colour:Color = new Color(mc_1.mc_2); bg_colour.setRGB(0x6546a0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7604667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBA can't send calendar appointment When I manually make a calendar reminder/appointment, I can then click "Invite Attendees" and chose the people to invite and then click "Send" and everyone will receive that calendar reminder/appointment. I have the following code to make a reminder programmatically, but it won't send to the intended recipients. If I open the reminder after the script has run and click on "Invite Attendees" I can see the list is filled with the people I want to send the reminder to, so I'm not really sure why it's not actually sending the reminder to them. Can anyone shed some light on this for me? Private Function CreateAppointment(SubjectStr As String, BodyStr As String, StartTime As Date, EndTime As Date, AllDay As Boolean) Dim olApp As Outlook.Application Dim Appt As Outlook.AppointmentItem ' Only create the reminder if there's no duplicate If (CheckForDuplicates(SubjectStr) = False) Then Set olApp = CreateObject("Outlook.Application") Set Appt = olApp.CreateItem(olAppointmentItem) Appt.Recipients.Add ("John Doe") Appt.Recipients.ResolveAll Appt.Subject = SubjectStr Appt.Start = StartTime Appt.End = EndTime Appt.AllDayEvent = AllDay Appt.Body = BodyStr Appt.ReminderSet = True Appt.Save Appt.Send End If Set Appt = Nothing Set olApp = Nothing End Function A: A meeting is a specific type of appointment -- an appointment that other people are invited to. In order to make an appointment a meeting, you need to do more than just invite attendees. You need to set the status to 'Meeting'. Add this to your code: Appt.MeetingStatus = olMeeting Also note that you set a reminder, but didn't set a reminder time. For example, Appt.ReminderMinutesBeforeStart = 30 Finally, if this is Outlook VBA, why are you using CreateObject? You should be using the native Application Object to derive all your objects. i.e. instead of Set olApp = CreateObject("Outlook.Application") you would use Set olApp = Outlook.Application HTH A: I had the same issue, didn't get it to work until I replaced Appt.Recipients.Add ("John Doe") Appt.Recipients.ResolveAll With Appt.RequiredAttendees = "john.doe@email.com" Regards Chris
{ "language": "en", "url": "https://stackoverflow.com/questions/7604670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: tower defense game in as3 adding the enemy ok so i have been creating tower defense game off of a tutorial. I finished the tutorial and it worked fine but i couldn't figure out how to build off of it. So I started all over and built more towers and a second enemy but the problem is that on the first level it works but in the second level it doesn't. I've been working with this for hours i have not found anything. so what i am asking if someone can give me a tutorial or anything that might be of help on arrays and tower defense games in as3 it is kind of a lot of code so i wont post it now unless you really need it heres the tutorial http://www.flashgametuts.com/tutorials/as3/how-to-create-a-tower-defense-game-in-as3-part-1/ stop(); //othervariables var money:int=100;//how much money the player has to spend on turrets var lives:int=20;//how many lives the player has //lvlarray var S:String = 'START'; var F:String = 'FINISH'; var U:String = 'UP'; var R:String = 'RIGHT'; var D:String = 'DOWN'; var L:String = 'LEFT'; var startDir:String;//the direction the enemies go when they enter var finDir:String;//the direction the enemies go when they exit var startCoord:int;//the coordinates of the beginning of the road var lvlArray:Array = new Array();//this array will hold the formatting of the roads lvlArray = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,R,1,1,D,0,0,R,1,1,D,0,0,R,1,1,D,0,0, 0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0, 0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0, S,D,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,R,1,F, 0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0, 0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0, 0,R,1,1,U,0,0,R,1,1,U,0,0,R,1,1,U,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, ]; //enemy1array var currentLvl:int = 1; var gameOver:Boolean = false; var currentEnemy:int = 0;//the current enemy that we're creating from the array var enemyTime:int = 0;//how many frames have elapsed since the last enemy was created var enemyLimit:int = 12;//how many frames are allowed before another enemy is created var enemyArray:Array = new Array();//this array will tell the function when to create an enemy var enemiesLeft:int;//how many enemies are left on the field enemyArray = [//defining the array [2,2,1,1,1],//1's will just represent an enemy to be created [1,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],//another row means another level [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ]; function startGame():void{//we'll run this function every time a new level begins for(var i:int=0;i<enemyArray[currentLvl-1].length;i++){ if(enemyArray[currentLvl-1][i] == 1){ enemiesLeft ++; } } } //enemy2array var currentEnemy2:int = 0;//the current enemy that we're creating from the array var enemy2Time:int = 0;//how many frames have elapsed since the last enemy was created var enemy2Limit:int = 15;//how many frames are allowed before another enemy is created function start2Game():void{//we'll run this function every time a new level begins for(var i:int=0;i<enemyArray[currentLvl-1].length;i++){ if(enemyArray[currentLvl-1][i] == 1){ enemiesLeft ++; } } } //lvlcreate var roadHolder:Sprite = new Sprite();//create an object that will hold all parts of the road addChild(roadHolder);//add it to the stage function makeRoad():void{ var row:int = 0;//the current row we're working on var block;//this will act as the block that we're placing down for(var i:int=0;i<lvlArray.length;i++){//creating a loop that'll go through the level array if(lvlArray[i] == 0){//if the current index is set to 0 block = new EmptyBlock();//create a gray empty block block.graphics.beginFill(0x333333); block.graphics.drawRect(0,0,25,25); block.graphics.endFill(); addChild(block); //and set the coordinates to be relative to the place in the array block.x= (i-row*22)*25; block.y = row*25; } else if(lvlArray[i] == 1){//if there is supposed to be a row //just add a box that will be a darker color and won't have any actions block = new Shape(); block.graphics.beginFill(0x111111); block.graphics.drawRect(0,0,25,25); block.graphics.endFill(); block.x= (i-row*22)*25; block.y = row*25; roadHolder.addChild(block);//add it to the roadHolder } else if(lvlArray[i] is String){//if it's a string, meaning a special block //then create a special block block = new DirectBlock(lvlArray[i],(i-row*22)*25,row*25); addChild(block); } for(var c:int = 1;c<=16;c++){ if(i == c*22-1){ //if 22 columns have gone by, then we move onto the next row row++; } } } } //towers function makeTurret(xValue:int,yValue:int):void{//this will need to be told the x and y values var turret:Turret = new Turret();//creating a variable to hold the Turret //changing the coordinates turret.x = xValue+12.5; turret.y = yValue+12.5; addChild(turret);//add it to the stage } function makeTurret2(xValue:int,yValue:int):void{//this will need to be told the x and y values var turret2:Turret2 = new Turret2();//creating a variable to hold the Turrettwo //changing the coordinates turret2.x = xValue+12.5; turret2.y = yValue+12.5; addChild(turret2);//add it to the stage } //enemy1 addEventListener(Event.ENTER_FRAME, eFrame);//adding an eFrame function function eFrame(e:Event):void{ //if there aren't any levels left if(currentLvl > enemyArray.length){ gameOver=true;//set the game to be over //reset all the stats currentLvl = 1; currentEnemy = 0; enemyTime = 0; enemyLimit = 12; enemiesLeft = 0; removeEventListener(Event.ENTER_FRAME, eFrame);//remove this listener removeChild(roadHolder);//remove the pieces of road gotoAndStop('win');//go to the win frame } if(lives<=0){//if the user runs out of lives gameOver=true;//set the game to be over //reset all the stats currentLvl = 1; currentEnemy = 0; enemyTime = 0; enemyLimit = 12; enemiesLeft = 0; removeEventListener(Event.ENTER_FRAME, eFrame);//remove this listener removeChild(roadHolder);//remove the pieces of road gotoAndStop('lose');//go to the lose frame } makeEnemies();//we'll just make some enemies if(enemiesLeft==0){//if there are no more enemies left currentLvl ++;//continue to the next level currentEnemy = 0;//reset the amount of enemies there are start2Game(); startGame();//restart the game } //Updating the text fields txtLevel.text = 'Level '+currentLvl; txtMoney.text = '$'+money; txtLives.text = 'Lives: '+lives; txtEnemiesLeft.text = 'Enemies Left: '+enemiesLeft; } function makeEnemies():void{//this function will add enemies to the field if(enemyTime < enemyLimit){//if it isn't time to make them yet enemyTime ++;//then keep on waiting } else {//otherwise var theCode:int = enemyArray[currentLvl-1][currentEnemy];//get the code from the array if(theCode == 2){//if it's set as 1 var newEnemy:Enemy = new Enemy();//then create a new enemy enemyHolder.addChild(newEnemy);//and add it to the enemyholder } currentEnemy ++;//move on to the next enemy enemyTime = 0;//and reset the time } } //enemy2 addEventListener(Event.ENTER_FRAME, e2Frame);//adding an eFrame function function e2Frame(e:Event):void{ //if there aren't any levels left if(currentLvl > enemyArray.length){ gameOver=true;//set the game to be over //reset all the stats currentLvl = 1; currentEnemy2 = 0; enemy2Time = 0; enemy2Limit = 12; enemiesLeft = 0; removeEventListener(Event.ENTER_FRAME, eFrame);//remove this listener removeChild(roadHolder);//remove the pieces of road gotoAndStop('win');//go to the win frame } if(lives<=0){//if the user runs out of lives gameOver=true;//set the game to be over //reset all the stats currentLvl = 1; currentEnemy2 = 0; enemy2Time = 0; enemy2Limit = 12; enemiesLeft = 0; removeEventListener(Event.ENTER_FRAME, e2Frame);//remove this listener removeChild(roadHolder);//remove the pieces of road gotoAndStop('lose');//go to the lose frame } makeEnemies2();//we'll just make some enemies if(enemiesLeft==0){//if there are no more enemies left currentLvl ++;//continue to the next level currentEnemy2 = 0;//reset the amount of enemies there are start2Game(); startGame();//restart the game } //Updating the text fields txtLevel.text = 'Level '+currentLvl; txtMoney.text = '$'+money; txtLives.text = 'Lives: '+lives; txtEnemiesLeft.text = 'Enemies Left: '+enemiesLeft; } function makeEnemies2():void{//this function will add enemies to the field if(enemy2Time < enemy2Limit){//if it isn't time to make them yet enemy2Time ++;//then keep on waiting } else {//otherwise var theCode:int = enemyArray[currentLvl-1][currentEnemy2];//get the code from the array if(theCode == 2){//if it's set as 1 var newEnemy2:Enemy2 = new Enemy2();//then create a new enemy enemyHolder.addChild(newEnemy2);//and add it to the enemyholder } currentEnemy2 ++;//move on to the next enemy enemy2Time = 0;//and reset the time } } //other //run these functions at the start makeRoad(); var enemyHolder:Sprite = new Sprite(); addChild(enemyHolder); startGame(); start2Game(); A: You need to create the ability to reset your game state easily. Remove listeners (might not be needed if you use weak references; http://gskinner.com/blog/archives/2006/07/as3_weakly_refe.html), clear arrays, remove graphics (removeChild) etc. Storing everything in a "level" object and having a dispose() (or similar) function on that is a nice way of doing it (as mentioned in comments). Then simply create a new level object for the next level, and you are good to go :) A: I'd guess that the problem you're having is that you aren't removing everything from the level properly before you start the next level. Here's how the "loading of the game" should work: * *Set up all in-game static assets. (HUD, Tiles, etc) *Set up all the Tower Elements (Buying panel for towers) *Set up all the Enemy Elements. (Create the array that represents the enemies that will spawn) *Continue setting up all other elements you have in-game. After they've finished playing this level, whether it be win/lose, you should remove ALL things that were added during the "loading" phase. The idea here is that you want everything to be loaded, each new level, the exact same way every time you do it with small changes to the level like design. Things like enemies and tower assets will always be loaded the same way, so you need to make sure you remove them properly before the next rounds starts so that when you do add them for that round, you aren't re-adding something that still exists in-game. You seem confused about game design in general. The problem I mentioned above is just one of the many trip-ups when beginning the designing of games. I'd recommend that you go through a game-design book. I'd recommend this one. The reason I recommend a book like this is because it walks you through the conceptual portion of game design and gets you thinking correctly. I learned Game Programming from this book and recently coded Symphonic Tower Defense.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery AJAX Form does not return values I have a multi-form app that gathers some information via AJAX and then allows the user to update that information and submit it again while continuing through the form. The goal is to eliminate multiple pages to perform simple record updates. My jQuery .post() returns the 'new' form with new values, but my second form does not submit the returned values, even the 'delete' returns either object.HTMLElement or undefined. Please help, as I'm a jQuery newbie. index.php <form id="getCustomer"> <select> <option value="1">John Doe</option> <option value="2">Jane Doe</option> </select> </form> <div id="customer_info"> <form id="updateCustomer"> <input type="text" name="firstName" value="" /> <input type="text" name="lastName" value="" /> <input type="submit" id="updateCustomer" value="Update" /> <input type="submit" id="deleteCustomer" value="Delete" /> </form> </div> <div id="info_status"></div> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> //AJAX selected customer $('#getCustomer').change(function(){ var id = $(this).val(); $.post( 'inc/getCust.inc.php', {id:id}, function(output){ $('#customer_info').html(output).show(); }); }); //Prevent default form actions $('form').live('submit', function(){ return false;// On submit return false }); //AJAX Update Customer $('#updateCustomer').live('click', function(){ var fname = $('input[name=firstName]').val(); var lname = $('input[name=lastName]').val(); $.post( 'inc/updateCust.inc.php', { }, function(output){ $('#info_status').html(output).show(); }); }); //AJAX Delete Customer $('#deleteCustomer').live('click', function(){ var fname = $('input[name=firstName]').val(); var lname = $('input[name=lastName]').val(); var deleteCust = confirm('Delete: ' + c_fname + ' ' + c_lname + '?'); if(deleteCust){ $.post( 'inc/deleteCust.inc.php', { id:id }, function(output){ $('#info_status').html(output).show(); } ); } }); </script> getCust.inc.php <?php getCust($_POST['id']);?> <form id="updateCustomer"> <input type="text" name="firstName" value="<?php echo $CUST['fname'];?>" /> <input type="text" name="lastName" value="<?php echo $CUST['lname'];?>" /> <input type="submit" id="updateCustomer" value="Update" /> <input type="submit" id="deleteCustomer" value="Delete" /> </form> A: Part of your problem is that you have a function called preCustData, but you're calling it usng prepCustData() (pre -> prep) Another problem is that prepCustData isn't actually doing anything, just storing values in local variables that can't be accessed elsewhere. Try this instead: function prepCustData(){ var fname = $('input[name=firstName]').val(); var lname = $('input[name=lastName]').val(); return {f:fname,l:lname}; } You can then access the data like this: var data=prepCustData(); alert(data[f]); alert(data[l]); Another problem is that your code uses a variable called cid that doesn't seem to be calculated anywhere. A: So, I was unable to resolve the usage of $('input[name=firstName]').val(); However, after some modification $('#firstName').val(); is working. Final Working index.php code: <form id="getCustomer"> <select> <option value="1">John Doe</option> <option value="2">Jane Doe</option> </select> </form> <div id="customer_info"> <form id="updateCustomer"> <input type="text" id="firstName" value="" /> <input type="text" id="lastName" value="" /> <input type="submit" id="updateCustomer" value="Update" /> <input type="submit" id="deleteCustomer" value="Delete" /> </form> </div> <div id="info_status"></div> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> //AJAX selected customer $('#getCustomer').change(function(){ var id = $(this).val(); $.post( 'inc/getCust.inc.php', {id:id}, function(output){ $('#customer_info').html(output).show(); }); }); //Prevent default form actions $('form').live('submit', function(){ return false;// On submit return false }); //AJAX Update Customer $('#updateCustomer').live('click', function(){ var fname = $('#firstName').val(); var lname = $('#lastName').val(); $.post( 'inc/updateCust.inc.php', { }, function(output){ $('#info_status').html(output).show(); }); }); //AJAX Delete Customer $('#deleteCustomer').live('click', function(){ var fname = $('#firstName').val(); var lname = $('#lastName').val(); var deleteCust = confirm('Delete: ' + fname + ' ' + lname + '?'); if(deleteCust){ $.post( 'inc/deleteCust.inc.php', { id:id }, function(output){ $('#info_status').html(output).show(); } ); } }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7604674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding duplicates in java Array Anyway, I have this extremely simple java program to find out if 2 objects in an array are the same. How ever when I run it when a set of unique objects it always returns 1 error, If I add more objects that are the same it counts as normal. This is the code; int[] array= new int[] {1,245,324,523}; int size = array.length; int error=0; System.out.println(error); int i = 0; for(i=0; i<size; i++){ if(array[0] == array[i]){ error= error +1; } System.out.println(error); } A: The 1 error is because you're comparing array[0] with array[0], which is of course equal to itself. If you want to find all pairwise duplicates, you will need to do a double loop: for(int i=0;i<size;i++){ for(int j=i+1;j<size;j++){ if(array[i] == array[j]){ if(i!=j){ error = error + 1; } } } } You'll notice a few things from this code: * *j starts at i+1, not at 0. *error is only incremented when i!=j The first is because you're taking turns with each element in your array to compare with every other element. By the time its turn comes around (in the outer loop), it's already been compared to the elements before it, and should not be compared with them again. The second is because you'll end up comparing an element to itself for each outer loop. You don't want to count it as an error. A: You're starting i at 0. Therefore the first test is if(array[0] == array[0]) ;) A: You're always going to get at least one error because array[0] == array[i] will be true on the first iteration, when i = 0. A: Try a doubly nested for loop. Something like this for (int i=0;i<size-1;i++){ for (int j=i+1; j<size; j++) { error += (array[i] == array[j]) ? 1 : 0; } } A: In your code at int i=0; for(i=0;i<size;i++){ if(array[0]==array[i]){ //this condition runs true only for the first time. as i=0 here error=error+1; } System.out.println(error); //now here you had put the println(error) outside the if()-condition therefore it will be printed repeatedly value of error which is 1 } A: You also need to "think Java". Use Array.equals for the comparison. See the documentation here and some examples here A: If you are going to make use of any collection, you can easiy findout the duplicates in the array Example: public static void main(String[] args) { boolean containsDuplicate =false; int[] intArray = new int[] {1,245,324,1,523}; List<Integer> myObj = new ArrayList<Integer>(); for(int id : intArray){ if(myObj.contains(id)){ containsDuplicate = true; System.out.println("Duplicate"); }else{ myObj.add(id); } } } A: Following code is fine but it returns 11. Not sure if it is what was expected. public static void main(String[] args){ int[] array = {23, 23, 0, 43, 545, 12, -55, 43, 12, 12, -999, -87, 12, 0, 0}; int error = 0; for(int i=0;i<array.length;i++){ for(int j=i+1;j<array.length;j++){ if(array[i] == array[j]){ if(i!=j){ error = error + 1; } } } } System.out.println(error); } I propose little bit complicated but hopefully more advanced solution. package myjavaprogram; import java.util.Arrays; public class TestClass1 { public static void main(String[] args){ int[] array = {23, 23, 0, 43, 545, 12, -55, 43, 12, 12, -999, -87, 12, 0, 0}; //int[] array = {23, -22, 0, 43, 545, 12, -55, 43, 12, 0, -999, -87, 12}; //int[] array = {23, -22, 0, 23}; //int[] array = {23, -22, 23}; calculate_duplicates(array); } private static void calculate_duplicates(int[] array) { calculateUniqueNumbers(array); } private static void calculateUniqueNumbers(int[] array) { Pair[] pairs = new Pair[array.length]; initializePairsAtrray(pairs, array); printPairsAtrray(pairs); System.out.println("array.length="+array.length); System.out.println("--------------------"); // update pairs array taking in account duplicates duplicates for(int i = 0; i < array.length; i++) { System.out.println("array[i]="+array[i] + " i="+i); for(int j = i+1; j < array.length; j++) { System.out.println("array[j]="+array[j]+" j="+j); if(array[i] == array[j] && pairs[j].useDuringCount == true) { pairs[i].occurance_num++; pairs[j].occurance_num = 0; pairs[j].useDuringCount = false; } if(array[i] == 0) { pairs[i].occurance_num = 0; } if(array[j] == 0) { pairs[j].occurance_num = 0; pairs[j].useDuringCount = false; } } pairs[i].useDuringCount = false; System.out.println("--------------------"); } printPairsAtrray(pairs); // calculate general number of duplicates (numbers whick are repeated // in initial array) System.out.println("Duplicates in array:"+ calculateDuplicatesNumber(pairs)); } private static void initializePairsAtrray(Pair[] pairs, int[] array) { for(int i=0;i<pairs.length;i++) { Pair p = new Pair(); p.occurance_num = 1; p.value = array[i]; p.useDuringCount = true; pairs[i] = p; } } private static void printPairsAtrray(Pair[] pairs) { System.out.println("--------------------"); for(int i=0;i<pairs.length;i++) { System.out.println("pairs["+i+"].occurance_num="+pairs[i].occurance_num); System.out.println("pairs["+i+"].value="+pairs[i].value); System.out.println("pairs["+i+"].useDuringCount="+pairs[i].useDuringCount); System.out.println("--------------------"); } } private static int calculateDuplicatesNumber(Pair[] pairs) { System.out.println("-------------------- Duplicates:"); int duplicates_num = 0; for(int i=0;i<pairs.length;i++) { if(pairs[i].occurance_num > 1) { duplicates_num++; System.out.println("number: "+pairs[i].value+" occurance_num " + pairs[i].occurance_num); } } return duplicates_num; } } class Pair { int value; int occurance_num; boolean useDuringCount; } Mykola
{ "language": "en", "url": "https://stackoverflow.com/questions/7604683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: string returned in reading file line by line I want to pass the string returned by reading a file line by line into a function. But its givin an unusual error.Seems as if the string returned is not exactly the line in the .txt file(source file).However if i manually pass strings into the function by copy pasting it works.heres ma code:- <?php function check($string) { // for removing certain text from the file $x = 0; $delete = array(); $delete[0] = "*"; $delete[1] = "/"; for($i=0;$i<2;$i++){ $count=substr_count($string,$delete[$i]); if($count>0){ $x++; return false; break; } } if($x==0)return true; } $file = fopen("classlist.txt", "r") or die("Unable to open file!"); $myFile = "new.txt"; $fh = fopen($myFile, "w") or die("can't open file"); while(!feof($file)){ if(check(fgets($file))){ $stringData = fgets($file); fwrite($fh, $stringData); } } fclose($fh); ?> what i get on ma new.txt file is:line 2 line 4 line 6 line8---------- line 21 Plz help me out..... A: Each call to fgets() retrieves a new line from the file. Call it once per loop iteration, putting the returned line in a variable, and then check and use that variable. A: The while loop should look something more like this: while(!feof($file)){ $stringData = fgets($file); if(check($stringData)){ fwrite($fh, $stringData); } } Because you're calling fgets twice, you're checking odd lines and writing out even lines. A: You could rewrite your code so that you reduce the places where errors can occur, the SplFileObject is handy to operate with textfiles and to go over each line. A FilterIterator can be used to only return those lines that do not contain * or /. Example: <?php $inFile = "classlist.txt"; $myFile = "new.txt"; $outFile = new SplFileObject($myFile, 'w'); class LineFilter extends FilterIterator { public function accept() { $line = $this->getInnerIterator()->current(); return strlen($line) === strcspn($line, '*/'); } } $filteredLines = new LineFilter(new SplFileObject($inFile)); foreach($filteredLines as $line) { $outFile->fwrite($line); } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7604686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to hide iOS tab bar for a particular tab index and tab is shown back when the screen is touched? Im trying to hide the tab bar for a specific view and show it back when the screen is touch. I want it to have the similar effect as youtube, for example when the video is playing the player controls is hidden and the screen is touched the controls are shown again. A: You can use this code to show and hide the tab bar: @implementation UITabBarController (Extras) -(void)showTabBar:(BOOL)show { UITabBar* tabBar = self.tabBar; if (show != tabBar.hidden) return; UIView* subview = [self.view.subviews objectAtIndex:0]; CGRect frame = subview.frame; frame.size.height += tabBar.frame.size.height * (show ? -1 : 1); subview.frame = frame; tabBar.hidden = !show; } This code works, was recently accepted by Apple in an app, and (as a category) I found easier to use than other solutions. When you want to hide the tabBar, just call: [self.tabBarController showTabBar:NO]; Likewise, to show it again, call this message with YES as the parameter. NOTE: Somehow I had forgotten that I had already looked up this code at some point in the past, and I'm now unsure of who answered it originally. Saurabh answered a similar question. The code provided by Saurabh iterates over all views looking for isKindOfClass:[UITabBar class], whereas I just grab the first subview -- which might be fragile in the face of updates. A: Have you tried just straight up hiding the tab bar? In the View Controller you want to not have a tab bar, add tabBar.hidden = YES; to viewWillAppear: or viewDidAppear: to reverse that have a touch-up-inside event trigger tabBar.hidden = NO; I've not done this with tab bars personally, but this works with other views, so it's the way I would try first. A: Try This Code - (void) hideTabBar:(UITabBarController *) tabbarcontroller { CGRect screenRect = [[UIScreen mainScreen] bounds]; [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.5]; float fHeight = screenRect.size.height; if( UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) ) { fHeight = screenRect.size.width; } for(UIView *view in tabbarcontroller.view.subviews) { if([view isKindOfClass:[UITabBar class]]) { [view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)]; } else { [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)]; view.backgroundColor = [UIColor blackColor]; } } [UIView commitAnimations]; } - (void) showTabBar:(UITabBarController *) tabbarcontroller { CGRect screenRect = [[UIScreen mainScreen] bounds]; float fHeight = screenRect.size.height - 49.0; if( UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) ) { fHeight = screenRect.size.width - 49.0; } [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.5]; for(UIView *view in tabbarcontroller.view.subviews) { if([view isKindOfClass:[UITabBar class]]) { [view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)]; } else { [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)]; } } [UIView commitAnimations]; } A: Try this: self.tabBarController.tabbar.hidden = YES; Put it in viewDidLoad.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to have a sealed constructor? I have a baseclass which has public contructors. The baseclass is not sealed and is not abstract. There is one constructor which I desire to be sealed. Is this possible? My current attempt results in syntax error saying the constructor cannot be sealed. public sealed MyBase(string someParam) Additional: I wish to be able to instantiate the base class directly and have access to the sealed constructor. Derived classes cannot use that constructor via the derived constructors. E.g. public MyDerived() : base(string cant_access_my_sealed_constructor) A: You can't do that. If the constructor is public, you can call it from constructors of derived classes. But you can do something close – you can have a private constructor and a public static method that calls it: class MyBase { private MyBase(string someParam) { // some code } public static MyBase Create(string someParam) { return new MyBase(someParam); } protected MyBase() // or some other protected or public constructor { } } class MyDerived : MyBase { public MyDerived() : base("foo") // won't compile, as requested { } } A: All constructors are "sealed" in that they cannot be "overridden." They can only be called from the constructor in a child class. If you are hoping to prevent child classes from having a constructor with the same signature, that cannot be done. Based on the additional information you added to the post, it sounds like what you want to do is make your constructor private, as Kyle suggested. This will prevent the child class from calling the constructor, but it won't prevent it from taking the same types of arguments: public class Foo { private Foo(string s){ } // Allowed public Foo() : this("hello") { } } public class Bar : Foo { // Allowed public Bar(string s) : base(){ } // Not allowed public Bar(string s) : base(s){ } } A: If you want to prevent the constructor from being called by inherited classes, just mark it private. Constructors aren't inherited by a child class, you have to explicitly call a base constructor if desired. This code will call the base class' no-parameter constuctor when an instance of the child class is instantiated. Without it, the base class' constructor won't be called when creating a new instance of the child class. public class A { public A() { } } public class B : A { public B() : base() { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DiscriminatorFormula If I have a single table where I need multiple columns for discriminator, is my only solution to use a @DiscriminatorFormula? I ask because some prototyping gave us some results that I cannot explain. Failed Prototype: Initially we prototyped a 3-deep class hierarchy using one @DiscriminatorColumn on the super class and included the second @DiscriminatorColumn on subclasses. Of course we got this warning: Discriminator column has to be defined in the root entity, it will be ignored in subclass We found that updates worked, but inserts did not. So we scrapped that idea. Successful? prototype: We then tried the following which seems to work: Omit the second @DiscriminatorColumn on the subclasses and just include the @JoinColumn on a foreign key (which we were going to need anyway). Perhaps, since the joins are to different types of objects, Hibernate/JPA seems to be able to figure out which subclass is correct. Can anyone explain that? Should we scrap that and just use @DiscriminatorFormula to get the explicit relationship defined on the 2 discriminator columns? A: DiscriminatorFormula is an alternative to DiscriminatorColumn. You annotate the superclass (which maps the real table as default) with one of them. With DiscriminatorColumn it creates an additional column (as default called "dtype") which contains the discriminator value. You put the annotation in the superclass: @Entity @Table(name = "features") @DiscriminatorColumn public class Features{ //valid code } DiscriminatorFormula allows you to check the database row content and "select" a subclass by the discriminator value. No additional ("dtype") column is created. In the main class you annotate the superclass with the formula, like: @Entity @Table(name = "features") @DiscriminatorFormula( "CASE WHEN num_value IS NOT NULL THEN 'NUMERIC' " + " WHEN txt_value IS NOT NULL THEN 'TEXT' end" ) public class Features{ //valid code } In the DiscriminatorFormula you just put some pure SQL to do what you need. You can choose one of these two options and the subclasses is exactly the same in both cases. In the subclasses you specify the discriminator value, for Example: @Entity @DiscriminatorValue('NUMERIC') public class NumericFeatures extends Features { private Double numValue; public Double getNumValue() { return numValue; } public void setNumValue(Double numValue) { this.numValue = numValue; } //valid code } in the table called "features" you have both columns "num_value" and "txt_value", containing the corrensponding values. With DiscriminatorColumn you would have either "NUMERIC" or "TEXT" value in the additional dtype column and also both the "num_value" and "txt_value" columns. If you don´t specify the inheritance strategy the default is "SINGLE_TYPE". the following annotation can be omitted if it´s your chosen strategy: @Inheritance(strategy = InheritanceType.SINGLE_TABLE) With or without this annotation you get one table called "Features". A: I switched it to use a DiscriminatorFormula and it works just fine now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get YUI object on page I'm using the YUI2 framework. I want to be able to get a reference to an object that was created on the page. I don't want to change the existing JS code to store a global handle to it when it is created, if possible. The page has something like this on it: <script type="text/javascript">//<![CDATA[ new FirstRate.Reporter("report1").setOptions( { inData: "testfunc" })); //]]></script> I don't see any methods in YAHOO.util.Dom specific to finding objects. How can I get an object reference to FirstRate.Reporter? Is there anything to ennumerate the objects on the page? Thanks A: JavaScript objects aren't part of DOM. DOM is the Document Object Model, it's about objects in HTML document like divs, forms, inputs etc, the kind of objects Browser displays. There is no "global enumeration" of objects in JavaScript. There are global variables. I don't want to change the existing JS code to store a global handle to it So you don't want to use global variable. But why? This is the only way to do it, and it's also very simple: var myGlobalVar = new FirstRate.Reporter("report1").setOptions({inData: "testfunc"})); Here you'll store reference ("handle" as you say) to your object in global var myGlobalVar, which you can later access in another part of your JavaScript code. A: YUI contains lots of methods for finding objects in the webpage DOM. YAHOO.util.DOM contains methods: HTMLElement | Array get ( el ) Array getElementsBy ( method , tag , root , apply , o , overrides ) HTMLElement getElementBy ( method , tag , root ) Array getElementsByClassName ( className , tag , root , apply , o , overrides ) and many more. These retrieve objects from the DOM. To find an object in the page with YUI2, you would typically use some combination of the tag type, the class name or the id to query the page using YUI methods to find the object you want. It's easiest to find a specific object in the page if you give it a unique id value and then you can just using YAHOO.util.DOM.get("myObject") to retrieve it (where "myObject" is the id of the HTML element). If you want to get regular javascript objects, then you have to store references to them yourself in your own javascript variables. YUI doesn't do that for you except when using some UI widgets (which also have DOM elements). If you want to keep track of the result of this: new FirstRate.Reporter("report1").setOptions( { inData: "testfunc" }) Then, you have to assign it to a variable or to a property of an object whose scope allows it to last long enough for you to use it. var theReporter = new FirstRate.Reporter("report1").setOptions( { inData: "testfunc" }) or myObject.reporter = new FirstRate.Reporter("report1").setOptions( { inData: "testfunc" }) where myObject is some other object you've created and are storing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenGL goes green on tablets Description: My OpenGL game runs fine on phones. However, after a couple of seconds of running on a tablet the 3D rendering goes all green. The 2D overlays (gl) are mostly fine. This might be triggered by rotation, I can't be sure; no access to a tablet. A user kindly recording it happening, which I have posted online: http://www.youtube.com/watch?v=DRfDM673TRA Questions: Has anyone seen this before, or know of a possible cause/cure? Also, can anyone confirm this is is still happening? (BB Rally Lite is free). Other info: The game is locked into landscape mode so I wouldn't expect it to do anything on rotation. Update: This was a bug in my code. Tablets have a different default orientation, which was triggering conditional (bugged) code that never got run on a phone. The green screen was a result of the bug causing the model's matrix to contain nan (or inf, I can't recall). If you suffer from a green screen I suggest you start by looking at your matrices.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Match text to attribute value w/ jQuery If I have the following vars var $headers = $("#myTbl th").not(":first"); var $this = $(this); How do I match $this.text(); to the text within title tag inside th? <th title="match this title">value</th> This does not seem to work: $headers.filter(":contains(" + $this.text() + ")"); A: var title = $("#myTbl th").not(":first").attr("title"); var $headers = $("#myTbl th[title='"+title+"']"); something like that should do it
{ "language": "en", "url": "https://stackoverflow.com/questions/7604708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why no zoom dropdown in ASP.NET reportviewer in Firefox? I am using Visual Studio 2010. The web reportviewer is not showing the zoom dropdown in the report toolbar in Firefox. It shows in IE & Chrome. I have ShowZoomControl true. Is this a limitation of the control? Why? A: it seems zooming is only supported in IE, please see it here: http://msdn.microsoft.com/en-us/library/ms251670.aspx and there's a section about zoom saying that: Zooming the Report Page The ReportViewer toolbar provides standard zoom functionality so that you can enlarge or shrink the report. The Web server control only provides zooming support in Internet Explorer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make ASP.NET MVC Action return different formats? I don't know if this is the right way to approach something, but I'm hoping it is. The example below is a heavy controller and is absolutely the wrong approach, but it get's the idea of what I'm looking for across. public class PeopleController : Controller { public ActionResult List(string? api) { MyViewModel Model = new MyViewModel(); if (api == "json") { // I'd like to return the Model as JSON } else if (api == "XML") { // I'd like to return the Model as XML } else { return View(Model); } } } Now what I need to be able to do is return the Model to the View if it's being requested like this: http://example.com/People/List But I'd like it to output JSON if it's requested like this: http://example.com/People/List/?api=json Or output XML if it's requested like this: http://example.com/People/List/?api=xml Is this just plain wrong? If not, what is the best approach to achieve this? I was thinking of achieving it with a Custom MultiPurposeResult that could do all the filtering for me and then return it as this public class PeopleController : Controller { public MultiPurposeResult List(string? api) { MyViewModel Model = new MyViewModel(); return MultiPurpose(Model); } } } A: Agree with @Matt. Don't explicitly ask for the response type, infer it from the contentType in the request, which is more RESTful. For example, created a basic enum type to encapsulate the response types you want: public enum RestfulResultType { Json, Html, Xml } Then create a custom model binder than sets this property in your action, depending on the content type. Then your controller could look like this: public ActionResult List(RestfulResultType resultType) { var data = repo.GetSomeData(); switch (resultType) { case RestfulResultType.Json: return Json(data); case RestfulResultType.Xml: return XmlResult(data); // MvcContrib case RestfulResultType.Html: return View(data); } } If you need any more customization than the regular helpers provide, then create custom ActionResult's. You can leave the return type as ActionResult - that's the point, so that the controller can return different formats. ResfulResultTypeModelBinder.cs: public class ResfulResultTypeModelBinder: IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (controllerContext.HttpContext.Request.ContentType == "application/json") return RestfulResultType.Json; // other formats, etc. } } Global.asax: ModelBinders.Binders.Add(typeof(RestfulResultType), new RestfulResultTypeModelBinder()); A: You can create a custom MultiPurposeResult but I personally would lose the string? api from the method signature, instead have the MultiPurpose look for the presence of Request["format"] and then make the determination of what format to possible output the results in. Since the format doesn't nessecarily have anything to do with the ActionResult but more the format of the response.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: System.Threading.Tasks not obeying start rules? ReWrite: I have stripped the question down to contain the example code instead of a link to it and the results and question as the surrounding information seemed to be causing confusion. Question: Why do tasks seem to start with out being started? This is a piece of sample code from the Microsoft Website on tasks. It is described as creating an unstarted task, creating a second started task and waiting for it to complete, then starting the first task and finally starting a third task synchronously in the main thread. Here is an uncommented version of the sample code: using System; using System.Threading; using System.Threading.Tasks; class StartNewDemo { static void Main() { Action<object> action = (object obj) => { Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId); }; Task t1 = new Task(action, "alpha"); Task t2 = Task.Factory.StartNew(action, "beta"); t2.Wait(); t1.Start(); Console.WriteLine("t1 has been launched. (Main Thread={0})", Thread.CurrentThread.ManagedThreadId); t1.Wait(); Task t3 = new Task(action, "gamma"); t3.RunSynchronously(); t3.Wait(); } } Here are the results: Task=1, obj=beta, Thread=3 t1 has been launched. (Main Thread=1) Task=2, obj=alpha, Thread=3 Task=3, obj=gamma, Thread=1 From the description task 1, which is Beta, should be ran only after task 2 has completed so the main thread can progress. This does not seem to be the case from this output. I also ran a second test run where I put a display of the tick counts into the action object and received this, confirming that Task1 is indeed starting before Task2 is completed. Task=1, obj=beta, Thread=3 (634529151744201906) t1 has been launched. (Main Thread=1) Task=2, obj=alpha, Thread=3 (634529151744221908) Task=3, obj=gamma, Thread=1 (634529151744221908) I am not trying to do anything fancy here, I am simply looking for an explanation as to why Task1 (obj=beta) is apparently executing before it is given the instruction to do so. A: Task=1, obj=beta, Thread=3 Task=1 is slightly misleading here, as this is actually t2 in the sample code. You can see this because 'beta' is present. It is started and completed before running t1. t1 has been launched. (Main Thread=1) Task=2, obj=alpha, Thread=3 This is t1 (with Id 2). Task=3, obj=gamma, Thread=1 This is t3. A: Threads or assignment of Tasks to threads aren't guaranteed (i.e. non-deterministic) to be in order without some form of synchronization. A: When you start a task, it may not execute immediately (if there isn't a free thread pool thread). But tasks never start by themselves. And the output you observed is correct. The code executes like this: * *t1 (alpha) is created, but not executed *t2 (beta) is created, started, prints to console (apparently with TaskId == 1) and is waited upon *t1 (alpha) is started, apparently with TaskId == 2 *notification about starting t1 is printed *t1 (alpha) prints to the console and is waited upon *the rest should be obvious
{ "language": "en", "url": "https://stackoverflow.com/questions/7604714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: xfbml registration plugin validation error I used Facebook's demo scripts to understand registration plugin' system. I use this code: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml"> <head> <title>Home</title> </head> <body> <div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js#appId=285180546708&xfbml=1"></script> <fb:registration redirect-uri="http://basarozcan.com/store_userdata.php" fields='[{"name":"name"}, {"name":"username","description":"Username","type":"text"}]' onvalidate="validate_async"></fb:registration> <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script> <script> function validate_async(form, cb) { $.getJSON('validate.php?username=' + form.username, function (response) { if (response.error) { // Username isn't taken, let the form submit cb(); } cb({ username: 'That username is taken' }); }); } </script> </body> </html> I opened the page and write username but script can not validate username and firebug show an error. Error is: Permission denied to access property 'Arbiter' if (p == parent || !p.Arbiter || !p.JSON) { How can I solve this problem? Thanks A: I think you need to use HTTPS: <script src="https://connect.facebook.net/en_US/all.js#appId=285180546708&xfbml=1"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7604721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Middle-Mouse-button overflow bug in Chrome (Win) Observe this fiddle: http://jsfiddle.net/pixelfreak/AN5Wb/ Everything is fine until you try to scroll by clicking the middle mouse button. Then you can actually view past the boundaries of the element. This is not happening in FF or IE. Is this a known Chrome bug? A: I believe this is a Webkit bug. Here's the bug report from Chromium: https://code.google.com/p/chromium/issues/detail?id=89366 They say that its fixed in beta versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Getting the input from a PUT method in Web.py I'm using the following code in my server program: class AddLibSong: def PUT(self): db = MahData.getDBConnection() songs = json.loads(web.input().to_add) addToLibrary(songs) return But for some reason when I do a PUT with the data: "to_add=[ { "album" : "Unknonwn", "artist" : "Unknonwn", "host_lib_id" : "1", "is_deleted" : "false", "server_lib_id" : "-1", "song" : "Moneytalks" } ]" I get the following error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/application.py", line 237, in process return self.handle() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/application.py", line 228, in handle return self._delegate(fn, self.fvars, args) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/application.py", line 409, in _delegate return handle_class(cls) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/application.py", line 385, in handle_class return tocall(*args) File "/Users/kurtis/sandbox/udj/webserver/Library.py", line 114, in PUT song = json.loads(web.input().to_add) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/utils.py", line 76, in __getattr__ raise AttributeError, k AttributeError: 'to_add' 127.0.0.1:51096 - - [29/Sep/2011 19:02:58] "HTTP/1.1 PUT /add_songs_to_library" - 500 Internal Server Error Anybody know why this is? I think I saw something about Web.py begin only able to get input if given a POST or GET but I didn't see anything in the source code that should prevent this. A: Anyway, if you want more details on how to use PUT with WebPy I would advice you this great link. To make it work on the last version of webpy you should change the "main" code to that: if __name__ == "__main__": app=web.application(urls, globals()) app.run()
{ "language": "en", "url": "https://stackoverflow.com/questions/7604726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML Table Body Positioning and Scrolling As pictured in this Fiddle, I have a three tables on a page. I want to be able to scroll the body of "Leaderboard" and "Queue," leaving the caption and table header alone. Preferably without absolute positioning. Somewhat related, I also need the table (not including the caption to have a little bit of padding on the sides (but not between individual cells). A: Add overflow: scroll; to your divs and include a height. If you only want to scroll in one direction, instead you could do overflow-x for horizontal scrolling and overflow-y for vertical scrolling. For detecting if the div even needs to be scrollable, use overflow: auto;. A: Add overflow: auto; to the surrounding DIVs you want to scroll. You may want to set explicit heights, depending on your layout — you don't have to but it won't scroll if you don't. You could try setting a max-height if you want it to stretch only to a point. If you only want it to scroll vertically, some browsers support overflow-y: auto, but not all. Since the <caption> is in the table, you can't set the padding or margin on the table. You can either: * *Take the caption out of the table and make it a simple header like h2, then adding a margin to the table, or *You can set padding-left on the left table cells/column and padding-right on the other side. Not real clean, but lets you keep the <caption> semantic if you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: 3D Animation of Fractals I'm giving a presentation on Fractal Antennas (take a look at my previous threads) in November and I wanted to incorporate some animation to make my presentation easier to visualize the content I am referring to. Most of these animations would be relatively short, probably a minute long at the most. There are a few animations that would be fantastic to have: * *Fractal Mountains - The animation continues to add new iterations that depict the complex features of a mountain range. *Fractal Koch Curve - The animation begins with an initiator (triangle) and adds new iterations. Either I slowly bring in the new fractal that has the next iteration, or I use the same model and users can see the iterations branching outward. I would prefer the latter technique. *Show a fractal. Increase the iteration, while keeping a constant length, to vindicate the fractal shrinking in size. *Show a fractal. Increase the iteration, while keeping a constant size, to vindicate the fractal is increasing it's total perimeter length. *Cell phone animation - show a cell phone that has multiple antennas popping out (they can be simple sketches of lines). The trouble is, I've never done ANY animation before. In the programs I have already, they generate the coordinates of the fractals, if that can be of some use? What is the best way to render those animations in the shortest time possible? The presentation is almost 6 weeks away! Blender might be an option, but I have no idea of how to go about this. There are some great animations in this NOVA video that might give you an idea of what I'm after. Thanks, Austin A: Personally, I've used VPython to create simple 3D graphics and animations. It's an easy to learn library that's freely available at http://vpython.org/. Since you have the coordinates already, it should be fairly easy to for you to incorporate that into the drawing. Blender is a bit more complicated, but also incorporates python scripting if you want to spend the time to learn it. Lastly, referencing some of the YouTube comments: if you use the video just cite it, or email and get permission. If you're not making money on this presentation, then odds are you're going to just fine using the videos. A: The easiest would be to use matplotlib.mplot3d. The principle is the same as in the 2D animation described at http://www.scipy.org/Cookbook/Matplotlib/Animations but you will be using the 3D methods described in http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html. I teach computer methods in physics and one of the activities is to create a Koch snowflake using Python and matplotlib. I also had a group of students create 3D fractals as their project using Python and Chaco (for interactivity) but using matplotlib instead is pretty straightforward. You can also try mayavi2 which is another 3D plotting library in Python. If you want to create a movie then you need to save each frame as a graphics file then convert the files into movie using convert (ImageMagick), mencoder, ffmpeg or some other software. I can probably provide some pseudocode/sample code but I'm too sleepy at the moment (it's 11:30pm from where I am).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C++ correct use of stringstream::str()? Consider the following C++ program: #include <iostream> #include <string> #include <sstream> using namespace std; int main (void) { string l1, l2; int n1, n2; stringstream ss; getline(cin, l1); getline(cin, l2); cerr << l1 << " " << l2 << endl; ss.str(l1); ss >> n1; ss.str(l2); ss >> n2; cerr << n1 << " " << n2 << endl; return 0; } Sample input: 2 3 Corresponding output: 2 3 2 0 But I was expecting: 2 3 2 3 If I insert a call ss.clear() before the second call to ss.str(), the output is what I expected. Is this really necessary? And why? A: It is necessary, because the first input from the stringstring hits end of file. Calling str() does not clear any error flags that are already set on the stringstream. ss.str(l1); ss >> n1; // Reads the entire buffer, hits the end of buffer and sets eof flag ss.str(l2); // Sets the string, but does not clear error flags ss >> n2; // Fails, due to at EOF You can use clear before the second str() or after, just as long as it's before you attempt to read more data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: trying to create a popover control with a datepicker in it that pops up when i click on a UITextField So I've seen this question answered in such a way where someone says "use the TextFieldShouldBeginEditing which is a method in the UITextField delegate protocol" I'm already using the popover delegate protocol in my original view: @interface AddChildViewController : UIViewController <UIPopoverControllerDelegate> { and then I have the UITextField as an IBOutlet in that view. Do I instead have to create a new view and viewcontroller that just contains the UITextField? Please be specific about what I'm supposed to put in which file. Thank you! A: I know its too late to answer but here it is. * *You can implement more than one protocols in a class eg: @interface AddChildViewController : UIViewController <UIPopoverControllerDelegate, UItextFieldDelegate> *From Interface Builder (or Storyboard) drag the delegate property of textfield to the AddChildViewController *Do all the resizing and adding a date picker or a calendar component in this method: TextFieldShouldBeginEditing //you are done
{ "language": "en", "url": "https://stackoverflow.com/questions/7604752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does MongoID do a separate query for .count(true)? I have a ruby on rails 3 project in which I query for a certain number of objects by using a .limit(3) . Then, in my view, I loop through these objects. After that, if there are 3 objects in the view, I display a "load more" button. Here is the view code: <% @objects.each do |object| %> <%= render object._type.pluralize.underscore + '/teaser', :object => object %> <% end %> <% if @objects.size(true) == 3 %> #load more link here <% end %> The size(true) is passed a boolean to ensure that mongoID takes into account the .limit and .offset on my query (otherwise it returns the total number of objects that matched, regardless of the limit / offset). Here are the relevant development log lines: MONGODB project_development['system.indexes'].insert([{:name=>"_public_id_1", :ns=>"project_development.objects", :key=>{"_public_id"=>1}, :unique=>true}]) MONGODB project_development['objects'].find({:deleted_at=>{"$exists"=>false}}).limit(3).sort([[:created_at, :desc]]) #some rendering of views MONGODB project_development['system.indexes'].insert([{:name=>"_public_id_1", :ns=>"project_development.objects", :key=>{"_public_id"=>1}, :unique=>true}]) MONGODB project_development['$cmd'].find({"count"=>"objects", "query"=>{:deleted_at=>{"$exists"=>false}}, "limit"=>3, "fields"=>nil}) My question is: does MongoID do a separate query for my @objects.size(true)? I imagine the ['$cmd'] might indicate otherwise, but I'm not sure. A: I don't think so, there was a pull request month ago to add aliases for :size, :length to :count to avoid re-running queries. You can check that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can an Android marketplace account have more than one login? I am an iOS and Android developer, but newer to the Android Marketplace. On iOS, you can have multiple iTunes Connect & developer.apple.com accounts to access provisioning, applications, stats, etc. Is such a thing possible on Android? When I log into the marketplace to upload an app, I see no links referring to "settings" or really anything other than "Upload an app". 2 reasons: 1, I paid the $25 fee with my private Gmail account - want to change that to company email. 2, I have a client that wants to have multiple logins to the marketplace backend. A: Nope, you can't link other logins to the publisher account. You can, however, change the account (google will migrate your apps to the new account and refund the fee). Instructions here. A: You cannot link to other accounts. However, recently Google started to let developers to transfer application ownership to other accounts. "If you would like to change the Google Account that you use to publish your applications, we are able to transfer applications to a new account. When applications are transferred, all ratings, comments, metrics, and users will be preserved." The process is described here: (http://www.google.com/support/androidmarket/developer/bin/answer.py?hl=en&answer=139626) A: Now I see a new link on my developer console to manage user accounts and there is a message which says: Account owner and user access Starting on March 29, we are adding support for account owner and user roles within developer accounts. Go to our Help Center to learn more about what account owners and users can do. Learn more
{ "language": "en", "url": "https://stackoverflow.com/questions/7604761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding and removing the last occurrence of an element in a (singly) linked list with only one traversal Is it possible to find the last occurrence of an element (for example, an integer) and remove this node with only one (forward) traversal through the list? A: Yes. Simply remember the previous entry every time you find the value you're searching for on the traversal. When the traversal is complete, the last entry remembered will have a link to the entry to be removed, and that is sufficient to do the removal. A: public void DeleteLastOccurenceOfKey(Node head, int key) { Node current=head; Node prev=null; Node temp=null; while(current!=null) { if(current.next!=null && current.next.data==key) { prev=current; temp=current.next; } current=current.next; } prev.next=temp.next; } DeleteLastOccurenceOfKey(head,25); I/P:5 10 15 25 35 25 40 O/P:5 10 15 25 35 40 A: /* * Delete last occurrence of an item from linked list * Given a liked list and a key to be deleted. Delete last occurrence of key * from linked. The list may have duplicates. * * Examples: * * Input: 1->2->3->5->2->10, key = 2`enter code here` * Output: 1->2->3->5->10 */ #include <stdio.h> #include <stdlib.h> #include <assert.h> typedef struct list_ list; struct list_ { int d; list *next; }; void insert (list **head, int d) { list *tmp = (list *)malloc(sizeof(list)); assert(tmp); tmp->d = d; tmp->next = *head; *head = tmp; } void printL (list *p) { while (p) { printf (" %d ", p->d); p = p->next; } printf ("\n"); } void deletlastOccurence (list **head, int d) { list *cur = *head; list *prev = NULL; list *match = NULL; if (cur == NULL) { printf ("list is empty\n"); return; } /* * Special case when there only ONE NODE * in the LIST */ if (cur->next == NULL) { if (cur->d == d) { printf ("Deleted one node %d\n", cur->d); free(cur); *head = NULL; } else { printf(" No match\n"); } return; } /* * Keep track of previous node */ while (cur && cur->next) { if (cur->next->d == d) { prev = cur; match = cur->next; } cur = cur->next; } if (prev){ prev->next = match->next; printf ("Delete %d\n", match->d); free (match); } else { /* * Special case when the last node is * on the head itself */ if ((*head)->d == d) { cur = *head; *head = cur->next; printf("element is at head Delete %d\n", cur->d); free (cur); } else { printf ("No match\n"); } } printL(*head); } int main (int argc , char *argv) { list *h = NULL; insert(&h, 1); insert(&h, 2); insert(&h, 3); insert(&h, 4); insert(&h, 5); insert(&h, 2); insert(&h, 1); insert(&h, 6); printL(h); deletlastOccurence(&h, 6); deletlastOccurence(&h, 2); } A: public void deleteLastOccurence(int value) { Element cur = this.head; Element prev = null; Element tmp = null; if(this.head == null) return; if(this.head.data == value) { this.head = null; return; } while(cur != null) { if(cur.next != null && cur.next.data == value) { prev = cur; tmp = cur.next; } cur = cur.next; } prev.next = tmp.next; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NAnt
{ "language": "no", "url": "https://stackoverflow.com/questions/7604765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mySQL SELECT timestamp(now()-3000); I'm trying to make a query which brings back results based on a timestamp, say an interval of 30 minutes. So what I figured out is that I can SELECT * FROM x WHERE ts BETWEEN timestamp(now()-3000) AND timestamp(now()) So this will query everything from x with timestamps in column ts within the last 30 minutes. However, this only works after now() is past the yyyy-mm-dd HH:30:00 mark because anytime before it will result in NULL... this is rather cumbersome and I don't understand why it won't just subtract the friggin minutes from the hour! Please help me out! I couldn't find any other method of doing a query within the last 30 minutes, that is what I'm trying to achieve. Best regards, John A: SELECT * FROM x WHERE ts BETWEEN timestamp(DATE_SUB(NOW(), INTERVAL 30 MINUTE)) AND timestamp(NOW()) A: SELECT * FROM x WHERE ts BETWEEN TIMESTAMPADD(MINUTE, -30, NOW()) AND NOW(); A: SELECT * FROM x WHERE ts BETWEEN NOW() - INTERVAL 30 MINUTE AND NOW(); A: First of all you need to realize that timestamp() returns a unix timestamp in seconds. 3000 seconds is not 30 minutes, it should be 1800 seconds. try that A: For me, what worked is following query select * from x where (now() - ts) < 1800000 1800000 is 30 minutes, because 60000 ms is 1 minute A: You'll have to use DATE_ADD() and DATE_SUB() operators for dates. Take a look at the documentation: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html A: SELECT * FROM (`yourdb`) WHERE `timestamp` BETWEEN NOW() - INTERVAL 30 MINUTE AND NOW();
{ "language": "en", "url": "https://stackoverflow.com/questions/7604766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Issue in sighandler I am creating a user level thread library implementing preemptive round robin scheduler. I have the handler function like this: void handler(int signum) { gtthread_yield(); } In the gtthread_yield, i am doing the context switching to switch to the next thread to be executed. The logic works fine in most cases. But, i am getting a segmentation fault when the signal is raised even before the gtthread_yield function (called from sighandler) could finish executing. Because of this , my code accesses invalid memory location (memory that i had already freed) Is there any way to avoid handler being raised before the gtthread_yield function finishes execution? Thanks A: Use sigaction() and its helpers (sigemptyset(), sigfillset(), sigaddset(), etc.) to block signals while the handler is in progress. That is probably a necessary step; it may not be sufficient. If it is not sufficient, you probably need to revise the signal handling so that it does almost nothing except a volatile sig_atomic_t variable before returning. Then the calling code has to look at the atomic variable and call gtthread_yield() when it is set (remembering to clear the variable after returning from gtthread_yield(). A: You can block other signals for the handler duration, see e.g. this entry in glibc manual how to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Type Provider for Entity Framework Would it be possible to create a type provider in F# 3.0 for Entity Framework, so that I can get neat IntelliSense like with the SqlDataConnection (included in Microsoft.FSharp.Data.TypeProviders) but with EF under the hood? A: They already provide two Entity Framework type providers out of the box. The EdmxFile type provider for disconnected EDMX files, and the SqlEntityConnection type provider for live database connections (the latter being akin to the SqlDataConnection type provider).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is using TempData to pass details between controller actions bad practice? I have certain situations where I need to pass a value between controller actions. * *When passing a returnUrl from a view to all nested views. In the view I have @{ TempData["returnURL"] = Request.Url.AbsoluteUri; } and then access it in a similar way to this (in my real version I check that the key is in TempData and that the returnURL is a real URL): return Redirect(TempData["returnURL"].ToString()); If it needs to continue on past the first page change (i.e. Search page -> Edit page -> Edit Section page) I'm adding it again TempData["returnURL"] = TempData["returnURL"]; *When I need to pass a value from one controller action through a view to another controller action that is called by ajax such as here: public ViewResult Index(FormCollection form) { var model = new GridColumnChooserViewModel(); //Select deleted/not deleted rows if (form.HasKeys()) model.ShowRows = (form["deletedDropDown"] == null) ? "Active" : GetOptionByName(form["deletedDropDown"]); TempData["ShowRows"] = model.ShowRows; ... } and then in my other ajax-called action controller I access it: public JsonResult GetData() { //Select deleted/not deleted rows var showRows = (TempData.ContainsKey("ShowRows") && TempData["ShowRows"] == null) ? "Active" : GetOptionByName(TempData["ShowRows"].ToString()); //refresh tempdata showrows so it is there for next call TempData["ShowRows"] = model.ShowRows; return this.GetDataSource(showRows); } My question is, is this really bad practice? From my understanding of it, I'm essentially using TempData like a session cookie. Is there a better way to do this, like using an actual cookie? A: It seems like you are using TempData to flow state through the various pages of your site; in general, I'd say this is a bad practice. Ideally, you would flow whatever upcoming state you would need to the client, and the client would store it (in some sort of JSON or whatever). Then, the client would return it to you as part of their action, and then you'd pass back the appropriate state, etc.; it speaks more to the stateless nature of HTTP applications. A: Yes, I would say that this in general is bad practice. While the ViewData dictionary approach is fast and fairly easy to implement it can leads to typo's and errors that are not caught at compile time. An alternative would be to use the ViewModel pattern which allows you to use strongly-typed classes for the specific view you need to expose values or content within. Ultimately giving you type safe and compile time checking along with intellisense. My first choice would be to use a view model. If that doesn't fit then using session state may be just fine. A: I changed both situations to use Session so that I didn't have to keep pushing the TempData value on. public ActionResult Create() { Session["returnURL"] = Request.UrlReferrer.AbsoluteUri; ... } Then I access it like this var returnURL = (Session["returnURL"] != null) ? Session["returnURL"].ToString() : Url.Action("Index", "Home"); Seems a bit better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Pattern fills for graphs As ggplot2 produces nice colored graphs but sometimes it is required to have black and white graphs with pattern fills. I wonder how to do this in ggplot2, say for this code: ggplot(diamonds, aes(cut, fill=cut)) + geom_bar() Edit Is there any function in R to do pattern fills for graphs? A: have a look at the 6th plot of example(barplot).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Remove old folder from a public git repo I have a fork in Github of a repo that has large binary files in the vendor folder. I want to remove that folder, so that the repo returns to a normal size. Problems/Challenges: * *There are 7 – non sequential – commits concerning the vendor folder. *There are hundreds of commits separating those commits. Since they are OSS contributions, it would not be appropriate to lose that history. *It is OK if people who has forked my repo cannot use this new one. None of them has new commits. They can fork again without problems. I would like to hear suggestions on how to proceed. Thank you. A: You're going to want to look at git filter-branch, and more specifically, the --tree-filter option for it. For example: git filter-branch --tree-filter "rm -r vendor/*" HEAD
{ "language": "en", "url": "https://stackoverflow.com/questions/7604788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Index on a Varchar? We're suffering some heavy table locking issues in production. I have noticed that I created a stored procedure which gets a list of orders by order number. Order number is a VARCHAR(150). There is no index of any type on this column. At the moment, there is a LOT of NULL values in this column. However, over time (This table went live recently), the table will grow significantly. No more NULL values will be added in this time. My question is two fold. Firstly, would an index be beneficial here. The proc is heavily used. And if so, should it be clustered or not? Data is things like CP123456, DR126512. The second question, which probably influences the first question is - would it be beneficial to change the column to a CHAR(10), as it 'seems' the order number is always the same size. Is there any speed benefit in putting an index on a fixed length CHAR, as opposed to a VARCHAR(150)? (The different in size is because of unknown requirements when the column was created). SQL Server 2008. A: * *Yes, absolutely! Go right ahead and add an index. Clustering the index is probably unnecessary here, and will not be possible anyway if you already have another clustered index (such as the primary key) on the table. *Changing the column to a CHAR(10) might have some benefits in terms of storage size, but it's unlikely to make a particularly great difference in index performance. I'd skip it for now. A: I don't have references to cite on this, only experience / anecdotal evidence. Firstly, queries can nearly always be improved through use of indexes. The exact benefit depends on the query. - If a query requires only specific records / a small portion of the table, an index will help - If a query requires the whole table, but could benefit from ordered data, an index will help Clustered indexes generally provide performance benefits over non-clustered indexes. In a very simplified sense, using a non-clustered index is like using two tables and joining them (The search friendly index is used first, which is then joined to the data itself - Unless the index contains all the data fields you need). A consideration here, however, is the order in which data is added to your table. If your clustered index means that data is often inserted or deleted at the middle of the table, you'll get fragmentation and other artefacts. In my experience, however, awareness and consideration to this is only needed in extreme situations. In short, DEFINITELY index your data. And the clustered index is normally best placed to serve your worst performing queries. As for the difference between VARCHAR and CHAR? In the olden days it was important to keep variable length fields at the end of your data, to make the fixed length fields easier to identify. This meant that having a VARCHAR field as your first field, and using it as a unique identifier, was pretty poor. Nowadays, the performance difference is marginal. Personally, I'd still keep unique identifiers as fixed length though. Variable length data won't normally have noticeable performance costs, but when you're actually making comparisons for join predicates, etc., it's much tidier to have fixed length fields if possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I inspect element in chrome when right click is disabled? I want to debug a info box that shows when I mouse over a google map marker. But google map disables right click anywhere on the map canvas, so I can't inspect the element for debugging / viewing purposes. I tried to search for the element by the href content in the elements tab, but it didn't show up on search. Is there a way to inspect element despite the lack of right click? A: Use Ctrl+Shift+C (or Cmd+Shift+C on Mac) to open the DevTools in Inspect Element mode, or toggle Inspect Element mode if the DevTools are already open. A: So use the short cut keys , Press ctrl + shift + I and then Click on Magnifying Option on Left side and Then Hover the mouse cursor and you will be navigate to proper way A: CTRL+SHIFT+I brings up the developers tools. A: Press F12 to Inspect Element and Ctrl+U to View Page Source A: Sure, you can open the devtools with Ctrl+Shift+I, and then click the inspect element button (square with the arrow) A: On Mac OS you have to press: CMD+ALT+I A: ALTERNATE WAY: Click Developer Tools to inspect element. You may also use keyboard shortcuts, such as CtrlL+Shift+I, F12 (or Fn+F12), etc. A: On Mac OS press: CMD+OPTION+J for console
{ "language": "en", "url": "https://stackoverflow.com/questions/7604795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "79" }
Q: Is it possible to attach a debugger to a running PHP process? I have a PHP script that we run every few minutes through a cron entry, and every now and then (about once a week) instead of ending normally, it stays running, eating up 100% of a CPU core (i'm assuming, looping infinitely) Looking at the code and "thinking" about it, I can't find any reason for this to happen, but it does. So far, when I get 3 or more of those I kill them, and that solves the CPU issue, but I'd like to do something about this... Is there any way to dump a process, or attach to it with a debugger so that I can know something, anything about what it's doing? (Just which PHP line it's on would be of huge help). I don't mind if the process dies when I dump, or anything. This is a PHP script, running from the command line, in a CentOS 5.6 machine, and I'm a big noob when it comes to *nix, so if you can point me to some tutorial for dummies that'd be awesome. Thank you! Daniel A: There's no way I'm aware of to attach a debugger to a PHP process that hasn't specifically been prepared with a PHP debugging extension (such as xdebug). However, you may be able to make some guess as to what's going on using the more general-purpose utility strace, which can deliver a trace of the system calls being run by a process. This will only tell you what system calls are being executed, but this may be enough (depending on the context) to determine what's going on anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: jquery, access page tab "with ajax content" via external hyperlink? Im having trouble to open a page displaying a specific jquery tab that loads its content via ajax. The problem is that jquery-ui opens tabs called by external links using the anchor hashtag but a ajax content tab anchor doesn't has one. Any ideas Thanks in advance. Basicaly the same code in the jquery-ui demos What i want is to have a link in my homepage that will open this other page already displaying tabX $(document).ready(function() { $(function() { $( "#tabs" ).tabs({ ajaxOptions: { error: function( xhr, status, index, anchor ) { $( anchor.hash ).html( "Couldn't load this tab. We'll try to fix this as soon as possible. " + "If this wouldn't be a demo." ); } } }); }); }); <div id="tabs"> <ul> <li class="tab first_tab"><a id="tab1" href="tab1.html">dit doen we</a></li> <li class="tab"><a id="tab2" href="tab2.html">disciplines</a></li> <li class="tab"><a id="tab3" href="tab3.html">cases</a></li> <li class="tab"><a id="tab4" href="tab4.html">uitgelicht</a></li> </ul> </div> A: To select a tab, you can use the select method on .tabs(), e.g. $('#tabs').tabs('select', 1) would select the 2nd tab (with a tab index of 1). To open a page and tells it to select a tab, you will need to "pass the intention" somehow. If you're using AJAX for the page transition, then you can simply load the page and call .tabs('select', tabIndex). If you load the 2nd page without AJAX, you can pass in a variable with the querystring, e.g. ?loadTab=1 and parse for it in the page being loaded. location.search will give you the querystring. This question will help you parse it. So, on the 2nd page, you would have something like this: $(function() { $("#tabs").tabs({ ... }); // code to parse the loadTab variable in the querystring if (typeof(loadTab) !== 'undefined' && parseInt(loadTab) !== 'NaN') $('#tabs').tabs('select', parseInt(loadTab)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a jquery video player that handle mp4 video files? I need to find a jquery video player that can play mp4 files. please help me Thanks. A: I've come across a couple of free jQuery based video player scripts: http://flarevideo.com/ http://videojs.com/jquery/ Both of those first try a HTML5 video tag then fallback to Flash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Web Application multiple user session handling I use Glassfish server 3.1.1, and I successfully configured my realm for the usergroups. While only 1 user is logged in, everything works fine, but as I log in with another account from a different browser (or even a different computer), the first session is cleared and the last logged in users data is shown in every previous sessions. I'm using Netbeans, and I let it generate my entity classes from a postgreSQL database, then the JSF pages from the entities. I read about HttpSessions, but there wasn't everything clear to me. Shall I continue this way, or the solution is in a different direction? If this is the right way, could anyone send me a sample source? Here is my code: Login.xhtml: <h:inputText id="email" size="25" value="#{login.email}" maxlength="30"/> <h:inputSecret id="password" size="25" value="#{login.password}" maxlength="100"/> <h:commandLink value="Bejelentkezés" action="#{login.loginAction}"/> This is how my login class looks like: @ManagedBean(name="login") @RequestScoped public class LoginBean { private String email; private String password; public String loginAction() { HttpServletRequest req=(HttpServletRequest)FacesContext.getCurrentInstance() .getExternalContext().getRequest(); try { System.out.println("login with: " + email + ", " + password + "."); req.login(email, password); } catch(ServletException e) .... A: The code posted so far looks fine. but as I log in with another account from a different browser (or even a different computer), the first session is cleared and the last logged in users data is shown in every previous sessions. This problem is caused elsewhere than in the code posted so far. The session should not be cleared at all. This is likely a misinterpretation of the happening. Perhaps you don't understand the concept "session". The symptoms indicate that you're apparently getting hold of the logged-in user in some static variable or an @ApplicationScoped managed bean. Make sure that you aren't doing that. As to how the "session" works, please read this: How do servlets work? Instantiation, sessions, shared variables and multithreading. As to how to choose the proper managed bean scope, please read this: How to choose the right bean scope?
{ "language": "en", "url": "https://stackoverflow.com/questions/7604810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ObjectiveC Category is not imported but still running code I have created a category for UINavigationBar with the following code: // UINavigationBar+MyNavigationBar.m @interface UINavigationBar (MyNavigationBar) @end @implementation UINavigationBar (MyNavigationBar) - (void)drawRect:(CGRect)rect { UIImage *img = [UIImage imageNamed: @"header.png"]; [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; } @end I have not #import anywhere, in any of the code in my entire project, however, this category is still running and inserting the header graphic. How is this possible? A: Because you're including the code in your app when you compile it. #import just makes the current context (.h or .m) aware of the methods in that category. Any category that is compiled into your app will be loaded at all times while your app is running. To remove the category from being added to your target remove the category .m file from your app's Target->Build Phase->Compile Sources. Assuming you want SOME of your navigation bars to use this code, but not ALL of them, the best way to do that is probably to subclass UINavigationBar. (You'll want to call [super drawRect:rect] in your subclass, by the way) Edit: alternate method of adding an image to UINavigationBar, In any view controller you want the image to appear, just add self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header.png"]] autorelease]; to viewWillAppear:
{ "language": "en", "url": "https://stackoverflow.com/questions/7604813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Best way to format multiple 'or' conditions in an if statement I have an if statement with many conditions (have to check for 10 or 15 constants to see if any of them are present.) Instead of writing something like: if (x == 12 || x == 16 || x == 19 || ...) is there any way to format it like if x is [12, 16, 19]? Just wondering if there is an easier way to code this, any help appreciated. The answers have been very helpful, but I was asked to add more detail by a few people, so I will do that to satiate their curiosity. I was making a date validation class that needed to make sure days were not > 30 in the months that have only 30 days (of which there are 4, I think) and I was writing an if statement to check things like this: if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11)) I was just wondering if there was a faster way to code things like that - many of the answers below have helped. A: I use this kind of pattern often. It's very compact: Define a constant in your class: private static final Set<Integer> VALUES = Set.of(12, 16, 19); // Pre Java 9 use: VALUES = new HashSet<Integer>(Arrays.asList(12, 16, 19)); In your method: if (VALUES.contains(x)) { ... } Set.of() returns a HashSet, which performs very well even for very large sets. If performance is not important, you can code the gist of it into one line for less code footprint: if (Set.of(12, 16, 19).contains(x)) but know that it will create a new Set every time it executes. A: You could look for the presence of a map key or see if it's in a set. Depending on what you're actually doing, though, you might be trying to solve the problem wrong :) A: Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list: // Declared with constants private static List<Integer> myConstants = new ArrayList<Integer>(){{ add(12); add(16); add(19); }}; // Wherever you are checking for presence of the constant if(myConstants.contains(x)){ // ETC } As Bohemian points out the list of constants can be static so it's accessible in more than one place. For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations. A: If the set of possibilities is "compact" (i.e. largest-value - smallest-value is, say, less than 200) you might consider a lookup table. This would be especially useful if you had a structure like if (x == 12 || x == 16 || x == 19 || ...) else if (x==34 || x == 55 || ...) else if (...) Set up an array with values identifying the branch to be taken (1, 2, 3 in the example above) and then your tests become switch(dispatchTable[x]) { case 1: ... break; case 2: ... break; case 3: ... break; } Whether or not this is appropriate depends on the semantics of the problem. If an array isn't appropriate, you could use a Map<Integer,Integer>, or if you just want to test membership for a single statement, a Set<Integer> would do. That's a lot of firepower for a simple if statement, however, so without more context it's kind of hard to guide you in the right direction. A: No you cannot do that in Java. you can however write a method as follows: boolean isContains(int i, int ... numbers) { // code to check if i is one of the numbers for (int n : numbers) { if (i == n) return true; } return false; } A: With Java 8, you could use a primitive stream: if (IntStream.of(12, 16, 19).anyMatch(i -> i == x)) but this may have a slight overhead (or not), depending on the number of comparisons. A: Do you want to switch to this?? switch(x) { case 12: case 16: case 19: //Do something break; default: //Do nothing or something else.. break; } A: Here is another answer based on a comment above, but simpler: List numbers= Arrays.asList(1,2,3,4,5); if(numbers.contains(x)){ // }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: node-qunit not working with nodeJS I have installed node-qunit using npm and this appeared to work correctly. The following script simply does nothing...no errors, no qunit output (not even failed test cases): var testrunner = require('qunit'); testrunner.run({ code: '/Users/macuser/Documents/test-input.js', tests: '/Users/macuser/Documents/test-cases.js' }, function(report) { console.log(report); }); A: Check what version of qunit you are using. I believe 0.2+ is unstable as it relies on Node 0.5+ (which is also unstable : http://www.quora.com/What-is-the-current-state-of-node-js/answer/Matt-Ranney) See issue 31 https://github.com/kof/node-qunit/pull/31 Try installing the stable branch npm install qunit@stable
{ "language": "en", "url": "https://stackoverflow.com/questions/7604815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scheduled program VB.NET I would like to ask for a recommendation for my project. Basically, it's a scheduled program that shall run at a given period of time, for example, 6:00 pm daily, it includes importing an excel file and inserting it in a sql table. I have my codes with me, but I dont know how to execute this program automatically. can you give me some advice I'm using MSSQL2005 server. And VB.NET language. A: Build your application to an executable that just does the task once and use Windows task scheduler. A: In my old shop, we occassionally forgot about the one-off tasks running under Task SCheduler, but we had lots of SQL Agent jobs running nightly or weekly. So, just to keep things all together, we created SQL Agent jobs for things like this. So my answer is the same as Bala's, but I would trigger the app through a job on SQL Server instead. How? Take a look at this: http://bp0.blogger.com/_mDuWqJiJyXE/SB6fy1yBRfI/AAAAAAAAATc/bmdxxAfFTjc/s1600-h/JS_Steps1.png A: You could use Visual Studio to create windows service which performs the timed actions...it's a steeper learning curve though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to convert rgb values into regular css color values? I trying to compare the styles of elements on my page. But one element dynamically changes it's text color to red, but represented as a rgb value. And the other element (to compare it with) uses #123456 values. Is there a converter somewhere that can take rgb and turn it into #number? For example: #000 instead of rgb(0, 0, 0) A: People always forget that rgb colors can be expressed as percentages, as well as integers. function rgbToHex(rgb){ var i= 0, c, hex= '#', rgb= String(rgb).match(/\d+(\.\d+)?%?/g); while(i<3){ c= rgb[i++]; if(c.indexOf('%')!= -1){ c= Math.round(parseFloat(c)*2.55); } c= (+c).toString(16); if(c.length== 1) c= '0'+c; hex+= c; } return hex; } alert(rgbtohex('rgb(255,127,0)')+'\n'+ rgbtohex('rgb(100%,50%,0)')); /* returned value: #ff7f00 #ff7f00 */ // also works with arrays- rgbToHex([100,200,60]) // returned value: #64c83c A: function rgbToHex(R, G, B){ return toHex(R) + toHex(G) + toHex(B); } function toHex(n){ n = parseInt(n, 10); if( isNaN(n) ){ return "00"; } n = Math.max(0, Math.min(n,255)); return "0123456789ABCDEF".charAt((n - n % 16) / 16) + "0123456789ABCDEF".charAt(n % 16); } edited. courtesy of http://www.javascripter.net/faq/rgbtohex.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7604823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XML Schema Multiple Elements and Attributes I have this code: <root> <skill id="1">C++</skill> <skill id="2">C#</skill> <skill id="3">Java</skill> <skill id="4">PHP</skill> <skill id="5">MYSQL</skill> <skill id="6">HTML</skill> <skill id="7">CSS</skill> <skill id="8">JavaScript</skill> <skill id="9">XML</skill> </root> I'm trying to create a schema to this and I'm not quite sure how to declare multiple elements with same name and it's attributes. XML Schema: how to have multiple identical elements? but was unsure exactly what was going on. Do I need maxOccurs when I put a minOccurs? And in the link above I don't understand the attribute part in the schema could somebody help / elaborate please? A: The following declares the root element, which can only occur once and must be specified, and a sequence of skill elements with an id attribute of type xs:IDREF. xs:attribute declares an attribute for the element. The name attribute specifies the attribute name. The type attribute specifies the data type. <xs:element name="root" minOccurs="1"> <xs:complexType> <xs:sequence> <xs:element name="skill" minOccurs="1" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="id" type="xs:IDREF"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> Do I need maxOccurs when I put a minOccurs? No, you don't need to have maxOccurs. There is an implicit maxOccurs="1" if you don't specify it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Plotting densities in R So, I am plotting densities (histograms). For example: d <- density(table[table$position==2,]$rt) But, I want to plot multiple densities on the same plot. For instance, I also want to plot density(table[table$position==3,]$rt) density(table[table$position==4,]$rt) density(table[table$position==5,]$rt) Furthermore, I want to specify the center point for each of these densities. Another way to ask this question is, how can I manually shift a density plot over by a certain number of x units? (for instance, increase all x values by 5) A: As with many R analysis functions, saving the output is your friend. So is ?density. foo<-density(something) names(foo) "x", "y" , "bw", "n" , "call" ,"data.name" So, plot(foo$x+5, foo$y, t='l') And you're done so far as I can tell. A: For the piece of your question about plotting multiple densities on the same plot, use lines: dat <- data.frame(x = rnorm(100), y = rnorm(100) + 2, z = rnorm(100) + 5) plot(c(-2.5,8),c(0,0.5),type = "n") lines(density(dat$x)) lines(density(dat$y)) lines(density(dat$z)) You open an empty plotting device using plot(...,type = "n") and then draw on it using lines or points, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make a view not read only I created a view that I make read only create view EMP_VU AS select ename employee_name, deptno, empno from emp with READ ONLY CONSTRAINT EMP_VU_Read_ONLY; How do i make it not read only? I get this error when I try to insert information into the view so i am assuming thats my problem that is read only. SQL> insert into EMP_VU (employee_n,deptno, empno) values (Stutte, 40, 8888); values (Stutte, 40, 8888) * ERROR at line 2: ORA-00984: column not allowed here I made a change heres the new error I get SQL> insert into EMP_VU (employee_name, deptno, empno) values ('Stuttle', '40', '8888'); insert into EMP_VU (employee_name, deptno, empno) * ERROR at line 1: ORA-00001: unique constraint (CIS605.EMP_EMPNO_PK) violated Heres the View SQL> select * from EMP_VU; EMPLOYEE_N DEPTNO EMPNO ---------- ---------- ---------- KING 10 7839 BLAKE 30 7698 CLARK 10 7782 JONES 20 7566 MARTIN 30 7654 ALLEN 30 7499 TURNER 30 7844 JAMES 30 7900 WARD 30 7521 FORD 20 7902 SMITH 20 7369 EMPLOYEE_N DEPTNO EMPNO ---------- ---------- ---------- SCOTT 20 7788 ADAMS 20 7876 MILLER 10 7934 14 rows selected. A: Your error message is a breach of a primary key. You're inserting data with a primary key that already exists. From the name of the key, it's abotu the employee number. In short, don't insert records with the same employee number as any existing records? I've also noticed that in one query you don't have quotes aroudn your string for the employee name. And in another you have quotes around numeric values. You need to identify the data types for each column, and only use quotes where they're needed. (Strings and Dates, but not numbers)
{ "language": "en", "url": "https://stackoverflow.com/questions/7604843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing socket objects between processes, TCP, Java Ok so I've found out Sockets are not serializable... so I cant pass them over TCP... My problem is I have a homework assignment where I have 10 servers that must listen on one socket(lets call it request). For input from any of x number of clients that write to that socket. Then after one of the server processes reads a message from request it must communicate with that client over its own socket... I tried making each server socket and the request socket on the server side, then passing those to the clients when they connected to the server... but this doesn't work... Any tips on how I might do this? Having TCP not be 1-1 is really toying with me here. A: Passing a socket over a TCP connection is like trying to pass a telephone over a telephone call, or trying to fax your fax machine. What you need to do is organize another connection between the parties concerned. EDIT: In fact your assignment as stated doesn't even make sense: I have 10 servers that must listen on one socket(lets call it request). That's not even correct terminology. Servers listen at ports, not sockets, and 10 servers listening at one port is impossible. They must each have their own port. For input from any of x number of clients that write to that socket. See above. Clients don't write to 'that socket'. They create their own socket that is connected to the server port, and they write to that. Then after one of the server processes reads a message from request it must communicate with that client over its own socket If the server has received a connection from a client it already has a socket representing its endpoint to that connection. So all the server has to do is write the response back to the same socket it read the request from. In short you have a major terminology problem, but you don't have a software problem at all. A: Passing sockets seems crazy to me. If you're trying to write a better server, you'll have a hard time beating Netty. I'd recommend giving it a look.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Browsers reformat my HTML which results in different look EDIT: I found that the issue is actually that IE changes an HTML elements class text from: "<img class="blah".." to "<img class=blah..". This is only happening in IE for me. Note it doesn't remove the src quotation marks or the id quotation marks or others. This is sooo frustrating! I am using JQuery to update a website visually, Inside my main div(updatableDiv) I change each updatable HTML element(for eg an p, i, b, etc.) into a textarea. The user makes their textual changes then I change the textareas back to a p, b etc. This is all done using JQuery. My Problem: When I go to get the HTML from the div(with the id updatableDiv), my HTML is slightly different which results in the display of the HTML being slightly different. For example: if I have an image thats sits directly above a white box(not vertical gap in between), after I update the html, there is a vertical gap introduced in between the image & the white box. So the before html was(this is an example from IE): <img class="pageHeading" src="linksHeading.png" width="90%" alt=""/><div class="pageContent"> After getting the HTML using the call $("#updatableDiv").html() the html looks like this: <IMG class=pageHeading alt="" src="linksHeading.png" width="90%"> <DIV class=pageContent> So it results in a vertical gap. So my main question is how can I keep all the formatting of the HTML so problems like this dont occur after I update the HTML & get the HTML from the element by JQuery's $("#updatableDiv").html()? A: Make the img display: block. A: White-space in the source shouldn't matter. You're not losing (or adding) some CSS class information during the transition are you? img elements are inline by default, so normally they line up to the text baseline leaving a gap that is the extra space below the baseline for dangling letters like lowercase g. Block elements should line up with the bottom of the containing block. Try setting some CSS: img { display:block; } // or possibly img { vertical-align:bottom; } A: When you get the innerHTML in some versions of IE, it will NOT give you back your original HTML. It will give you a generated version of the HTML that can be quite different from the original (though semantically identical to it). I've seen some versions of IE: * *Remove quote marks around attributes *Change the order of attributes *Change the case of attribute names So, in a nutshell, all you can count on when you get the innerHTML of something in IE is that it will give you semantically the same HTML, but it may not be the same HTML as what was in the page originally. It appears that it doesn't save the original HTML, but instead generates it from the object attributes. Since there are many legal ways to express a given set of attributes, IE will not necessarily generate it the same way you originally specified it. I don't believe there is anything you can do about this unless you want to reformat the generated HTML that IE gives you according to your own style rules (add quotes where you want them, put attributes in a specific order, change to a specific case, etc...). If you run this jsFiddle in IE7, you will see it change all three items above from what was originally specified. I specify this HTML in IE7: <div id="test" data-item="test" style="background-color: red; height: 40px; width: 100px;"> When I request innerHTML, I get this back (different order, caps and quoting): <DIV style="BACKGROUND-COLOR: red; WIDTH: 100px; HEIGHT: 40px" id=test data-item="test"></DIV> I'd actually be surprised if the vertical gap you notice is because of the changed HTML. IE is notorious for putting extra space around images. For one, they are an inline item by default so it treats them as being part of a line and gives the line they are on the prevailing line height. This can add extra space around images in various ways. The work-arounds I've used in IE are to make the image display: block (if that's appropriate) or to set font-size: 0 on the container that the image is in so IE doesn't give the line any additional height. You should also make sure that you've specified a border for the image because older versions of IE like to give images a default border too. This extra spacing around an image can be triggered by the existence of a space in a line that didn't previously exist. Other browsers consider that space only as a separator, but in older versions of IE, it triggers some extra line spacing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I prevent form variable names from revealing the database structure? I'm in the early phases of working on a web application, and I've reached a point where I want to make the best choice about a particular security concern. At the moment, all fields found within HTML forms are named after the database column that they are representing. So, for example, if in the database I have a field named "email", then the form field will be called "email" as well. This makes it easier for my generic code to handle forms, but I naturally see one major problem with such names: They can give potential hackers insight into how my database is structured, just from viewing the source. The main solution I've thought of involves encrypting field names so that client never has the real ones. A server-side key would be used to do the encryption. I am, however, concerned that this approach may complicate things too much. For example: * *I may find myself having to use POSTs more often, as the encrypted text might be longer than the original - pushing the limits of GET when many fields and their data are present. *Frequent encrypt/decrypt calls might lead to performance issues down the line. I did not test this yet, so it could end up being negligible. *Non-AJAX GETs can't use this approach without looking really cryptic. So, I'm wondering what you guys think about this. Am I over-thinking it, or am I on the right track? Is there a better way to handle it? By the way, I'm also aware that a field name like "email" doesn't offer much information to the developer (why not txtEmail, or something like that?). I'm looking to see if there's a good naming convention that I can adopt, as it might help with the above problem. A: If anyone can gain access to your DB via SQL injection or any other method, your schema can be revealed with one query so there is no point in trying to obscure it. If you feel you have to do security by obscurity, you're not doing something else right. If your application is secured, then it doesn't matter if a potential attacker thinks they know your schema or not. They can't do anything with the information. I'd spend less time trying to obscure your database (which will only frustrate you and your developers) and more time trying to lock down your application against potential injection attacks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I interprete a greyscale matlab image passed to my c++ mexFunction Here is my project, I have a GUI that loads images and I need to pass this image and several information to my mexFunction coded in C++, like xSize, ySize, window size for processing. I am having trouble to interprete the information that matlabs gives me and I am not sure how to actually do it too. A: When you pass any matrix to a MEX function, it is stored as a 1D array in a column-major order. Thus it is fastest to access it sequentially using linear indices. In the case of an image, you can access it as a 2D matrix if you prefer, you just need to map row/column indices to linear indices with a simple calculation. Consider this example: matrixExample.c #include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwSize r,c, i,j, n; double *input; /* get size of the matrix */ r = mxGetM(prhs[0]); c = mxGetN(prhs[0]); /* get pointer to data */ input = mxGetPr(prhs[0]); /* access matrix using row/column indices */ for (i=0; i<r; i++) { for (j=0; j<c; j++) { mexPrintf("%lf ", input[j*r+i]); } mexPrintf("\n"); } /* access matrix using linear indices (column-major) */ n = mxGetNumberOfElements(prhs[0]); for (i=0; i<n; i++) { mexPrintf("%lf\n", input[i]); } } Compile this MEX function: >> mex -largeArrayDims matrixExample.c Then you can use it on sample matrix: >> matrixExample( rand(2,3) ) 0.646204 0.592287 0.464080 0.668417 0.740318 0.143579 0.646204 0.668417 0.592287 0.740318 0.464080 0.143579 Note that I skipped doing input checking just to keep the example simple.. Everything should be explained in the documentation, so start by reading the users guide, and refer to the API reference when needed. The are also a number of examples included with MATLAB you can study: >> winopen( fullfile(matlabroot,'extern','examples','mex') ) >> winopen( fullfile(matlabroot,'extern','examples','mx') ) A: Did you check the type of the data of your matrix? I think that imread returns a matrix of size m*n*3 of type uint8. try taking the example above and change the definition of input to: unsigned char *input; (since double takes four times the memory is uint8 you get memory exceptions when you treat the pointer as pointer to double). A: Look at the the MATLAB help for imread. It's quite detailed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery.mobile-1.0rc1 and themes When I update my apps to the latest release of jquery,mobile-1.0rc1 All my set data themes go to the black default. Even when I explicitly code data-theme="b" etc. Did I miss something? A: OK I see themes are now added to the element div you want them for and no longer will adding them to the page div work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Decrementing while loop in c Is it possible to decrement the array size in a while loop in C by more than x--. For example, can you decrement an array by a third of the array size with each iteration? int n = 10; while (n < 0) // do something (round(n/3))-- // this doesn't work, but can this idea be expressed in C? Thank you for the help! A: You can use any expression: int n = 10; while (n > 0) // Note change compared with original! { // Do something n = round(n/3.0) - 1; // Note assignment and floating point } Note that you can only decrement variables, not expressions. You could also use a for loop: for (int n = 10; n > 0; n = round(n/3.0) - 1) { // Do something } In this case, the sequence of values for n will be the same (n = 10, 2) whether you round using floating point or not, so you could write: n = n / 3 - 1; and you'd see the same results. For other upper limits, the sequence would change (n = 11, 3). Both techniques are fine, but you need to be sure you know what you want, that's all. A: Yes, it is possible to add or subtract any number to your variable n. Usually, if you want to do something a very predictable number of times, you would use a for loop; when you aren't sure how many times something will happen, but rather you are testing some sort of condition, you use a while loop. The rarest loop is a do / while loop, which is only used when you want to execute a loop one time for certain before the first time the while check occurs. Examples: // do something ten times for (i = 0; i < 10; ++i) do_something(); // do something as long as user holds down button while (button_is_pressed()) do_something(); // play a game, then find out if user wants to play again do { char answer; play_game(); printf("Do you want to play again? Answer 'y' to play again, anything else to exit. "); answer = getchar(); } while (answer == 'y' || answer == 'Y'); A: There is no array in your code. If you wan't n to have a third of its value on each iteration, you can do n /= 3;. Note that since n is integral then the integral division is applied. A: Just like K-Ballo said there is no array in your example code but here is an example with an integer array. int n = 10; int array[10]; int result; // Fill up the array with some values for (i=0;i<n;i++) array[i] = i+n; while(n > 0) { // Do something with array n -= sizeof(array)/3; } But be careful in the example code you gave the while loop is checking if n is less than zero. As n is intialised to 10 the while loop will never be executed. I have changed it in my example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Composite models (models within models), or manual foreign key associations between models? I have two models, and I want to "nest" one within the other. Is there a way to do this with Sencha Touch? My models look like this: Ext.regModel('OuterModel', { fields: ['name'] }); var outerStore = new Ext.data.Store({ model: 'OuterModel', data: [ {name: 'item1'}, {name: 'item2'} ] }); Ext.regModel('InnerModel', { fields: ['a', 'b'] }); var innerStore = new Ext.data.Store({ model: 'InnerModel', data: [ {a: 1, b: 5}, {a: 2, b: 5}, {a: 3, b: 3} ] }); Each OuterModel needs an associated InnerModel, and I would love to just be able to have a field that was an inner-model that I could create Ext.Lists from. I could add outerName to InnerModel and query on outerName, but this feels sloppy, manually managing the association. Is the manual solution my only option, or can I make a model a field of another model? A: Models can have associations with other Models via belongsTo and hasMany associations. For example, let's say we're writing a blog administration application which deals with Users, Posts and Comments. We can express the relationships between these models like this: Ext.regModel('Post', { fields: ['id', 'user_id'], belongsTo: 'User', hasMany : {model: 'Comment', name: 'comments'} }); Ext.regModel('Comment', { fields: ['id', 'user_id', 'post_id'], belongsTo: 'Post' }); Ext.regModel('User', { fields: ['id'], hasMany: [ 'Post', {model: 'Comment', name: 'comments'} ] }); See the docs for Ext.data.BelongsToAssociation and Ext.data.HasManyAssociation for details on the usage and configuration of associations. Note that associations can also be specified like this: Ext.regModel('User', { fields: ['id'], associations: [ {type: 'hasMany', model: 'Post', name: 'posts'}, {type: 'hasMany', model: 'Comment', name: 'comments'} ] });
{ "language": "en", "url": "https://stackoverflow.com/questions/7604878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Regex Illegal Escape Character in Character Class I'm trying to determine whether or not a expression passed into my Expressions class has an operator. Either +-*/^ for add, subtract, multiply, divide, and exponent respectively. What is wrong with this code? private static boolean hasOperator(String expression) { return expression.matches("[\+-\*/\^]+"); } I thought that I had the special characters escaped properly but I keep getting the error: "illegal escape character" when trying to compile. Thanks for your help. A: Don't escape what needs not to be escaped: return expression.matches("[-+*/^]+"); should work just fine. Most regex metacharacters (., (, ), +, *, etc.) lose their special meaning when used in a character class. The ones you need to pay attention to are [, -, ^, and ]. And for the last three, you can strategically place in them char class so they don't take their special meaning: * *^ can be placed anywhere except right after the opening bracket: [a^] *- can be placed right after the opening bracket or right before the closing bracket: [-a] or [a-] *] can be placed right after the opening bracket: []a] But for future reference, if you need to include a backslash as an escape character in a regex string, you'll need to escape it twice, eg: "\\(.*?\\)" // match something inside parentheses So to match a literal backslash, you'd need four of them: "hello\\\\world" // this regex matches hello\world Another note: String.matches() will try to match the entire string against the pattern, so unless your string consists of just a bunch of operators, you'll need to use use something like .matches(".*[-+*/^].*"); instead (or use Matcher.find())
{ "language": "en", "url": "https://stackoverflow.com/questions/7604879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }