text
stringlengths
8
267k
meta
dict
Q: I need to create a timer that has hour, mins, and seconds I currently have code that can display mins and seconds. But the problem I'm facing is that when the mins gets to 60, it counts up to 61 and beyond. How can I add the hours? -(void)update:(ccTime)dt{ totalTime += dt; currentTime = (int)totalTime; if (myTime < currentTime) { myTime = currentTime; [countUpTimer setString:[NSString stringWithFormat:@"%02d:%02d", myTime/60, myTime%60]]; } } A: [countUpTimer setString:[NSString stringWithFormat:@"%02d:%02d:%02d", myTime/3600, (myTime/60)%60, myTime%60]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7625088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS: How to trim an image to the useful parts (remove transparent border) I'm trying to automatically show the useful part of a largely transparent png in an iPhone app. The image may be say 500x500 but it is mostly transparent. Somewhere within that image is a non-transparent part that I want to display to the user as large as I can so I want to trim off as much as I can from each side (or make it appear that way by stretching and moving within the UIImageView. Any ideas? A: Using Quartz convert the image to a bitmap, examine the alpha channel bits to find the bounds of the non-transparent part of the image. Here is an Apple Tech Note: Getting the pixel data from a CGImage object. You can get a CIImage from a UIImage with: CGImageRef imageRef = [uiImage CGImage]; A: I made a method to do this that scans all of the pixels in the image looking for columns or rows that are all transparent (0.01 tolerance) vs contain any non-transparent pixels, then trims the image accordingly. ///crops image by trimming transparent edges -(UIImage *)trimImage:(UIImage *)originalImage { // components of replacement color – in a 255 UInt8 format (fairly standard bitmap format) const CGFloat* colorComponents = CGColorGetComponents([UIColor colorWithRed:1 green:0 blue:0 alpha:1].CGColor); UInt8* color255Components = calloc(sizeof(UInt8), 4); for (int i = 0; i < 4; i++) color255Components[i] = (UInt8)round(colorComponents[i]*255.0); // raw image reference CGImageRef rawImage = originalImage.CGImage; // image attributes size_t width = CGImageGetWidth(rawImage); size_t height = CGImageGetHeight(rawImage); CGRect rect = {CGPointZero, {width, height}}; // image format size_t bitsPerComponent = 8; size_t bytesPerRow = width*4; // the bitmap info CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big; // data pointer – stores an array of the pixel components. For example (r0, b0, g0, a0, r1, g1, b1, a1 .... rn, gn, bn, an) UInt8* data = calloc(bytesPerRow, height); // get new RGB color space CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // create bitmap context CGContextRef ctx = CGBitmapContextCreate(data, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); // draw image into context (populating the data array while doing so) CGContextDrawImage(ctx, rect, rawImage); //float iln2 = 1.0f/log(2.0f); float topTrim = 0; float bottomTrim = 0; float leftTrim = 0; float rightTrim = 0; @autoreleasepool { int pixelPosition = 0; // float row = 1; float column = 1; BOOL found = NO; while (row < height) { while (column < width) { pixelPosition = row*width+column; NSInteger pixelIndex = 4*pixelPosition; float alphaValue = data[pixelIndex+3]/255.0f; if (alphaValue > 0.01f) { found = YES; break; } column++; } if (found) { break; } column = 1; row++; } topTrim = row; // row = height-1; column = 1; found = NO; while (row > 0) { while (column < width) { pixelPosition = row*width+column; NSInteger pixelIndex = 4*pixelPosition; float alphaValue = data[pixelIndex+3]/255.0f; if (alphaValue > 0.01f) { found = YES; break; } column++; } if (found) { break; } column = 1; row--; } bottomTrim = row; // row = 1; column = 1; found = NO; while (column < width) { while (row < height) { pixelPosition = row*width+column; NSInteger pixelIndex = 4*pixelPosition; float alphaValue = data[pixelIndex+3]/255.0f; if (alphaValue > 0.01f) { found = YES; break; } row++; } if (found) { break; } row = 1; column++; } leftTrim = column; // row = 1; column = width-1; found = NO; while (column > 0) { while (row < height) { pixelPosition = row*width+column; NSInteger pixelIndex = 4*pixelPosition; float alphaValue = data[pixelIndex+3]/255.0f; if (alphaValue > 0.01f) { found = YES; break; } row++; } if (found) { break; } row = 1; column--; } rightTrim = column; } // clean up free(color255Components); CGContextRelease(ctx); CGColorSpaceRelease(colorSpace); free(data); // float trimWidth = rightTrim-leftTrim; float trimHeight = bottomTrim-topTrim; UIView *trimCanvas = [[UIView alloc] initWithFrame:CGRectMake(0, 0, trimWidth, trimHeight)]; trimCanvas.backgroundColor = [UIColor clearColor]; UIImageView *trimImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, height)]; trimImageView.image = originalImage; trimImageView.contentMode = UIViewContentModeScaleToFill; trimImageView.backgroundColor = [UIColor clearColor]; [trimCanvas addSubview:trimImageView]; // trimImageView.center = CGPointMake(trimImageView.center.x-leftTrim, trimImageView.center.y-topTrim); // CGRect __rect = [trimCanvas bounds]; UIGraphicsBeginImageContextWithOptions(__rect.size, (NO), (originalImage.scale)); CGContextRef __context = UIGraphicsGetCurrentContext(); [trimCanvas.layer renderInContext:__context]; UIImage *__image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // return __image; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7625089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to get content of that contains other embedded XML tag in Java? I have an XML document that has HTML tags included: <chapter> <h1>title of content</h1> <p> my paragraph ... </p> </chapter> I need to get the content of <chapter> tag and my output will be: <h1>title of content</h1> <p> my paragraph ... </p> My question is similar to this post: How parse XML to get one tag and save another tag inside But I need to implement it in Java using SAX or DOM or ...? I found a soluton using SAX in this post: SAX Parser : Retrieving HTML tags from XML but it's very buggy and doesn't work with large amounts of XML data. Updated: My SAX implementation: In some situation it throw exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -4029 public class MyXMLHandler extends DefaultHandler { private boolean tagFlag = false; private char[] temp; String insideTag; private int startPosition; private int endPosition; private String tag; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase(tag)) { tagFlag = true; } } public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase(tag)) { insideTag = new String(temp, startPosition, endPosition - startPosition); tagFlag = false; } } public void characters(char ch[], int start, int length) throws SAXException { temp = ch; if (tagFlag) { startPosition = start; tagFlag = false; } endPosition = start + length; } public String getInsideTag(String tag) { this.tag = tag; return insideTag; } } Update 2: (Using StringBuilder) I have accumulated characters by StringBuilder in this way: public class MyXMLHandler extends DefaultHandler { private boolean tagFlag = false; private char[] temp; String insideTag; private String tag; private StringBuilder builder; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase(tag)) { builder = new StringBuilder(); tagFlag = true; } } public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase(tag)) { insideTag = builder.toString(); tagFlag = false; } } public void characters(char ch[], int start, int length) throws SAXException { if (tagFlag) { builder.append(ch, start, length); } } public String getInsideTag(String tag) { this.tag = tag; return insideTag; } } But builder.append(ch, start, length); doesn't append Start tag like<EmbeddedTag atr="..."> and </EmbeddedTag> in the Buffer. This Code print Output: title of content my paragraph ... Instead of expected output: <h1>title of content</h1> <p> my paragraph ... </p> Update 3: Finally I have implemented the parser handler: public class MyXMLHandler extends DefaultHandler { private boolean tagFlag = false; private String insideTag; private String tag; private StringBuilder builder; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase(tag)) { builder = new StringBuilder(); tagFlag = true; } if (tagFlag) { builder.append("<" + qName); for (int i = 0; i < attributes.getLength(); i++) { builder.append(" " + attributes.getLocalName(i) + "=\"" + attributes.getValue(i) + "\""); } builder.append(">"); } } public void endElement(String uri, String localName, String qName) throws SAXException { if (tagFlag) { builder.append("</" + qName + ">"); } if (qName.equalsIgnoreCase(tag)) { insideTag = builder.toString(); tagFlag = false; } System.out.println("End Element :" + qName); } public void characters(char ch[], int start, int length) throws SAXException { temp = ch; if (tagFlag) { builder.append(ch, start, length); } } public String getInsideTag(String tag) { this.tag = tag; return insideTag; } } A: The problem with your code is that you try to remember the start and end positions of the string passed to you via the characters method. What you see in the exception thrown is the result of an inside tag that starts near the end of a character buffer and ends near the beginning of the next character buffer. With sax you need to copy the characters when they are offered or the temporary buffer they occupy might be cleared when you need them. Your best bet is not to remember the positions in the buffers, but to create a new StringBuilder in startElement and add the characters to that, then get the complete string out the builder in endElement. A: Try to use Digester, I've used it years ago, version 1.5 and it were simply to create mapping for xml like you. Just simple article how to use Digester, but it is for version 1.5 and currently there is 3.0 I think last version contains a lot of new features ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7625095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Microphone input gets -120.0 dB after call interruption (this is my first question so i hope i give enough information) i am developing an application that samples the microphone input continuously with a timer. during normal operation everything is ok, if i close the app with the home button and then return to it i may see a few iterations with microphone input of -120.0 but then it start measuring correctly again. however if i place a call to the phone (and not answer) the microphone input measures -120.0 all the time. any ideas? A: You need to set an audio session with an audio session interrupt handler. Then you can cleanly stop and restart your audio queue or audio unit (etc.) after the call interruption in the handler callbacks. See Apple's Audio Session documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redis queue with claim expire I have a queue interface I want to implement in redis. The trick is that each worker can claim an item for N seconds after that it's presumed the worker has crashed and the item needs to be claimable again. It's the worker's responsibility to remove the item when finished. How would you do this in redis? I am using phpredis but that's kind of irrelevant. A: To realize a simple queue in redis that can be used to resubmit crashed jobs I'd try something like this: * *1 list "up_for_grabs" *1 list "being_worked_on" *auto expiring locks a worker trying to grab a job would do something like this: timeout = 3600 #wrap this in a transaction so our cleanup wont kill the task #Move the job away from the queue so nobody else tries to claim it job = RPOPLPUSH(up_for_grabs, being_worked_on) #Set a lock and expire it, the value tells us when that job will time out. This can be arbitrary though SETEX('lock:' + job, Time.now + timeout, timeout) #our application logic do_work(job) #Remove the finished item from the queue. LREM being_worked_on -1 job #Delete the item's lock. If it crashes here, the expire will take care of it DEL('lock:' + job) And every now and then, we could just grab our list and check that all jobs that are in there actually have a lock. If we find any jobs that DON'T have a lock, this means it expired and our worker probably crashed. In this case we would resubmit. This would be the pseudo code for that: loop do items = LRANGE(being_worked_on, 0, -1) items.each do |job| if !(EXISTS("lock:" + job)) puts "We found a job that didn't have a lock, resubmitting" LREM being_worked_on -1 job LPUSH(up_for_grabs, job) end end sleep 60 end A: You can set up standard synchronized locking scheme in Redis with [SETNX][1]. Basically, you use SETNX to create a lock that everyone tries to acquire. To release the lock, you can DEL it and you can also set up an EXPIRE to make the lock releasable. There are other considerations here, but nothing out of the ordinary in setting up locking and critical sections in a distributed application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to provide auto change for a QTimeEdit? I have a QTimeEdit widget on my dialog and I want to provide some kind of autochange - if the cursor is on minutes section and the time is 04:59, the next click on the arrow up would lead the time to change to 5:00. How to do that? I saw some mention of AutoAdvance property but I suppose it's obsolete because I cannot find it in Qt 4.7. A: I noticed there is a signal called void timeChanged ( const QTime & time ). You can connect it to a slot and call function void QAbstractSpinBox::stepBy ( int steps ) in the slot function. EDIT1: Sorry for the misleading. In fact, we don't really need void timeChanged ( const QTime & time ). See the code below: class myTime : public QTimeEdit { Q_OBJECT public: virtual void stepBy(int steps) { if (this->time().minute()==59 && steps>0){ setTime(QTime(time().hour()+1,0,time().second(),time().msec())); }else if(this->time().minute()==00 && steps<0){ setTime(QTime(time().hour()-1,59,time().second(),time().msec())); }else{ QTimeEdit::stepBy(steps); } } }; Keep in mind, you need to setWrapping(true) yourself. A: I don't know whether it's still interesting, but I found another solution: class myTime : public QTimeEdit { Q_OBJECT public: virtual void stepBy(int steps) { long lFactor=1; if (currentSection()==QDateTimeEdit::MinuteSection) lFactor=60; else if (currentSection()==QDateTimeEdit::HourSection) lFactor=3600; long lDateTime = (dateTime().toMSecsSinceEpoch()/1000)+(steps*lFactor); QDateTime dt = QDateTime::fromMSecsSinceEpoch(1000*(qint64)(lDateTime)); setDateTime(dt); } }; A: If some one is wondering how to automatically change time (because I did), and needs easy, rather clean solution, here's what I came up with: class TimeWidget : public QTimeEdit { Q_OBJECT public: void stepBy(int steps) { //Grab the current time QTime t = time(); //So we edit the time as in raw milliseconds. Larger type would be better in this case. //But 32bits is more than enough for day amount of milliseconds. int raw = (t.hour()*360000 + t.minute()*60000 + t.second() * 1000 + t.msec()); //Let's find out what section time widget is changing //And edit the raw millisecond data accordingly. switch(currentSection()) { case QDateTimeEdit::MSecSection: raw += steps; break; case QDateTimeEdit::SecondSection: raw += steps*1000; break; case QDateTimeEdit::MinuteSection: raw+= steps*60000; break; case QDateTimeEdit::HourSection: raw += steps*3600000; break; } //Now we just split the "raw" milliseconds into int hrs = (raw/ 36000000) % 24; //... hours int mins = (raw/ 60000) % 60; //... minutes int secs = (raw / 1000) % 60; //... seconds int mills = raw % 1000; //... milliseconds //Update & save the current time t.setHMS(hrs, mins, secs, mills); setTime(t); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7625102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why can't I declare a string in my program: "string is undeclared identifier" I can't declare a string in my program: string MessageBoxText = CharNameTextBox->Text; it just doesn't work. It says string is undeclared identifier. What am I missing in the namespace or include or something like that? A: To use the standard string class in C++ you need to #include <string>. Once you've added the #include directive string will be defined in the std namespace and you can refer to it as std::string. E.g. #include <string> #include <iostream> int main() { std::string hw( "Hello, world!\n" ); std::cout << hw; return 0; } A: Make sure you've included this header: #include <string> And then use std::string instead of string. It is because string is defined in std namespace. And don't write this at namespace scope: using namespace std; //bad practice if you write this at namespace scope However, writing it at function scope is not that bad. But the best is one which I suggested before: Use std::string as: std::string MessageBoxText = CharNameTextBox->Text; A: Are you by any way compiling using C++/CLI, the Microsoft extension for .NET, and not standard ISO C++? In that case you should do the following: System::String^ MessageBoxText = CharNameTextBox->Text; Also see the following articles: * *How to: Convert Between Various String Types *How to: Convert System::String to Standard String *How to: Convert Standard String to System::String
{ "language": "en", "url": "https://stackoverflow.com/questions/7625105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to delegate a task to main thread and wait for it's execution to complete? I have a Borland C++ project where I see a synchronize() method which a worker thread can use to delegate a task to main thread and wait for task to complete. In C#, there is a similar Control.Invoke() method. Is there anything similar while working in C++ in Visual Studio for both GUI and Console applications? SendMessage() comes to my mind but is that equivalent of above two? A: SendMessage is OK for GUI applications, where main thread has a message queue. For Console applications there is no generic way. You need to decide first, how main thread should handle such requests. If main thread of the Console application has message queue, SendMessage is OK as well. You can think about another ways, for example, using events, everytning depends on the main application thread behavior and its ability to handle requests from another threads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS based framework like SCSS (Adaptive design) I am designing a web app from scratch, which would be a fluid-based layout and the same HTML would render on different screens using the adaptive CSS. I am going to use adaptive CSS (or responsive design) for this. I was looking to use a framework like SCSS (http://sass-lang.com/) which would improve my code maintenance efforts. I'll have lots of CSS files (and probably some skin based as well) Since I am using adaptive layout, I am going to use CSS Media Queries for desktop/tablet/mobile CSS. I could not get an idea how well the SCSS would integrate with media queries and overall speaking , how much flexibility will it offer to me. Please let me know your suggestions if you have used SASS/SCSS and in general, any other suggestions. A: SCSS is essentially an extension to CSS, and is useful (with mixins) to void repetition in your code. It also provides a way to group blocks of CSS in semantically meaningful ways and gives you variables to avoid repeating yourself. If you are using a framework such as Rails, it is no-brainer. There are also frameworks which focus on layout such as 960 (and its variants), and Blueprint which also adds code for thing like buttons. The underlying philosophy behind many of these is DRY (don't repeat yourself). One bonus of using an established framework is that many of the browser issues have been ironed out, so you can be sure that it will work cross-browser. It is true that perhaps the code is not quite a lean as rolling your own, but with careful editing and making sure you minify the result and send it gzipped, this is not a major issue except on the most high traffic sites. Personally I have objected to using frameworks in the past because of the small amount of additional redundant code, but after 15 years of hacking around browser issues, I now think they are a Good Thing. Larry Wall said in Programming Perl, "We will encourage you to develop the three great virtues of a programmer: laziness, impatience, and hubris." Anything that allows more people to use CSS in a repeatable and reliable way, to build on work done by other, and to try out some of the leading edge features has got be a good thing. Engineering a site with media queries is still a bit leading edge. There are compromises in each approach and you should read up as much as possible before choosing one. Adapt.js is a good alternative if you don't mind javascript. You may want to look into the HTML5 Boilerplate. This has some useful defaults, and lots of documentation about the HTML and CSS defaults that have been chosen. Good luck! A: I have not used media queries together with SCSS, but I don't think they conflict with each other. I have used SCSS extensively in my current rails apps, and it helped me to reduce the amount of code, and get a better understanding when to use which styles. The tricky part will be what to have fluid (changing depending on the medias viewport size), and how to avoid repetition. Have a look at the nice site Responsive Design with CSS3 Media Queries, to get an idea which parts of your layout may be fluid. A: Have a look at 320+Susy (GitHub repo here). It uses the Susy grid framework extension for Compass. All of these tools are based on Sass and make use of media queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to include text to speech functionality in my code? If I have an HTML and JS page, and I want to add text to speech or even speech to text to it what is the best way? I already have code for speech to text in C# but am not sure how to link them together! I saw a text-to-speech google chrome extension. How can I include it in my code? A: you can use SAPI for converting text to speech ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7625113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: easyXDM without Flash We are evaluating easyXDM for reading 3rd party cookies with http://easyxdm.net/wp/2010/03/17/sending-and-receiving-messages/ (i.e. following socket based messages). We have observed that easyXDM uses flash for communication. I would appreciate your letting me know that would easyXDM will continue to work on browser or system that do NOT have flash plugin installed. Also, we understand that newer version on Windows 8 would not officially support flash therefore if any new user having windows 8 without flash installed with browser, would easyXDM continue to work? A: Easyxdm has multiple transport streams, and uses flash for only one of them (for ie 6 and 7 support). I suggest you read https://github.com/oyvindkinsey/easyXDM#readme and dig through it's documentation a little more. And windows 8 ships with two browsers. One that supports external plugins (like flash) and one that does not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: aspectj-maven-compiler plugin : how to weave JRE System.*? I'm trying to detect where a mysterious System.gc() comes from, so I'm hoping to create a pointcut on all calls to System.gc() the doc describes how to weave existing jars and existing dirs, but how do I weave the JDK itself ? Thanks a lot A: You can weave rt.jar beforehand and replace it in your JDK/JRE. Note that load time weaving will not work as the Javaagent does not have access to bootstrap classloader. However, quick search reveals that there is only one place in the whole JDK (Sun 1.6.0_26) that calls System.gc() explicitly: java.nio.Bits#reserveMemory Maybe you can simply attach a debugger and put a breakpoint on gc() method? That being said you can use call() advice as opposed to execution() which will weave calling client code rather than target method. So you only have to weave your code and all libraries rather than the JDK.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to apply two transformations with different origins to one div? I've got a div that I would like to rotate about its y-axis (with perspective) then do another 3d rotation on it around a different origin and display the result. Is this possible? I've only been able to get transformation-origin working outside of a -transformation statement, so defining a new transformation just overrides the first one. I've also tried nesting divs and doing one transformation on an inner div and doing another on an outer div, but the result is just the projection of the first transformation on to the plane of the second, it does not exists on its own plane, so looks completely wrong on the screen. As far as I'm aware I can't use canvas with javascript, because those transformations don't have perspective. This is sort of what I am trying to do: -webkit-transform-origin: 0px 0px; -webkit-transform: perspective(1000px) rotateY(-90deg); -webkit-transform-origin: 200px 200px; -webkit-transform: perspective(1000px) rotateX(x deg) rotateZ(z deg); Any ideas on how I can see the result of both of these transformations? A: A solution that does not involve having a wrapper is to chain the two transforms with a translate3d between them. Any translate transform moves the transform-origin for all subsequent transforms - translateX(tx) moves it by tx along the x axis, translateY(ty) moves it by ty along the y axis, translateZ(tz) moves it by tz along the z axis and translate3d(tx, ty, tz) moves it by tx along the x axis, by ty along the y axis and by tz along the z axis. So your transform would become: transform: perspective(1000px) rotateY(-90deg) translate3d(200px, 200px, 0) perspective(1000px) rotateX(x deg) rotateZ(z deg); A: I think I've found the answer, use -webkit-transform-style: preserve-3d; in a wrapper div. Thanks to this question, and as shown here and explained here (from the answers to that question).
{ "language": "en", "url": "https://stackoverflow.com/questions/7625126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ABGroupAddMember returns false. Why? When I call ABRecordRef aRecord = ABPersonCreate(), ABGroupAddMember() returns YES. But when I use ABNewPersonViewController - (void)newPersonViewController:(ABNewPersonViewController *)newPersonViewController didCompleteWithNewPerson:(ABRecordRef)person And use the (ABRecordRef)person to ABGroupAddMember(), it returns NO. Why? A: Set the addressBook property of the ABNewPersonViewController to the address book reference, which you use to retrieve the group reference. If you don't set the addressBook property before the ABNewPersonViewController is displayed, then it will create its own address book reference and the ABGroupAddMember function will not work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: unsupported operand type(s) for /: 'str' and 'int' I am new to Python and am learning some basics. I would like to know why I am getting this error. The code is: Hours = raw_input ("How many Hours you worked for today : ") minutes = (Hours * 60) Percentage = (minutes * 100) / 60 print "Today you worked : ", "percentage" A: You have to convert your Hours variable to a number, since raw_input() gives you a string: Hours = int(raw_input("How many hours you worked for today: ")) The reason why this is failing so late is because * is defined for string and int: it "multiplies" the string by the int argument. So if you type 7 at the prompt, you'll get: Hours = '7' minutes = '777777....77777' # 7 repeated 60 times Percentage = '77777....77777' / 60 # 7 repeated 60*100 = 6000 times So when it tries to do / on a string and a number it finally fails. A: Hours is read as a string. First convert it to an integer: Hours = int(raw_input("...")) Note that Hours*60 works because that concatenates Hours with itself 60 times. But that certainly is not what you want so you have to convert to int at the first opportunity. A: Your value Hours is a string. To convert to an integer, Hours = int(raw_input("How many hours you worked for today : ")) Values in Python have a specific type, and although a string may contain only digits, you still can't treat it as a number without telling Python to convert it. This is unlike some other languages such as Javascript, Perl, and PHP, where the language automatically converts the type when needed. A: raw_input() returns a string. Convert it to a number before proceeding (since multiplying a string by an integer is a valid operation).
{ "language": "en", "url": "https://stackoverflow.com/questions/7625132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Mysql multiple insert statement not adding all records I'm inserting a max of 3000 records and for this I just wrote a single query like insert into p_code (id_user_staff,user_id,postalcode,dropDownGroup) values (187,51,'AB10',1), (187,51,'AB11',1), (187,51,'AB12',1), (187,51,'AB13',1), (187,51,'AB14',1), (187,51,'AB15',1), (187,51,'AB16',1), (187,51,'AB21',1), .........3000 This seems to be working fine, but it's not adding all records, many of them are missed. I've also tried the same with each single query in for loop but this also is not adding all records. A: I've also tried the same with each single query in for loop but this also is not adding all records. Obviously the insert statement is fine then. There is some constraint on the table that is preventing some values from being inserted. This is either a unique or primary key. On one or more of the fields: id_user_staff, user_id, dropDownGroup Or a foreign key constaint that is not met on an insert. Or a trigger that fires before the insert and that generates an error, thereby preventing the insert from being finalized. If you do the big insert statement, you can use: SHOW ERRORS; Afterwards that will give you the exact error(s) which is stopping the insert(s). See: http://dev.mysql.com/doc/refman/5.0/en/show-warnings.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7625137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Groovy - Strings with "$" replacing it by \$ How can i replace a file that contain $ to \$ e.g dollar file contains string 1Mcl0c41$ after replacing it should look like string 1Mcl0c41\$ using sed i can perform $ cat dollar string 1Mcl0c41$ $ sed "s/1Mcl0c41/1Mcl0c41\\\\/g" dollar > fixed-filename $ cat fixed-filename string 1Mcl0c41\$ the same i wan't to achieve by using groovy i want to replace all the occurence of $ with \$ A: In a groovy script / program, you can say new File('./fixed-filename') << new File('./dollar').text.replace('$','\\$') Or, from the commandline, try groovy -e "line.replace('$','\\\\$')" -p dollars > fixed-filename
{ "language": "en", "url": "https://stackoverflow.com/questions/7625140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use private frameworks in Xcode for iOS? How do I use private frameworks in Xcode 4.1 for iOS 4.0 or later? Tutorials or articles would be useful. A: The short answer is: You don't. If you plan on going through the App Store approval process at all, then you might do some careful object graph navigation and stuff and hope that Apple doesn't care too much about what you do. If on the other hand you're thinking about working with jailbroken devices, then that might be a valid question, but you better say so, otherwise it's not clear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Implicit data type conversion in JavaScript when comparing integer with string using == The code: var num = 20; if(num == "20") { alert("It works"); } else { alert("Not working"); } The question: * *In C programming we have a rule name data type promotion, where when there's a mix of data type (example: addition of integer and floating point), the integer will first converted to floating point before the addition is being carry out. *The code above will prompt me an alert box with the message "It works" that shows the if test condition is evaluate to true. *For loosely typed JavaScript, I'm just curious: is there any rule like C that determines which conversion will be carry out in which situation? Besides that, the JavaScript code above converts num variable value from an integer value to string value before making comparison or vice versa? A: In JavaScript, there are two operators that can be used to compare two values: the == and === operators. Quoted from JavaScript The Definitive Guide 6th Edition: The equality operator == is like the strict equality operator (===), but it is less strict. If the values of the two operands are not the same type, it attempts some type conversions and tries the comparison again. And The strict equality operator === evaluates its operands, and then compares the two values as follows, performing no type conversion. So I suggest that you use === all the time to avoid problems like: null == undefined // These two values are treated as equal. "0" == 0 // String converts to a number before comparing. 0 == false // Boolean converts to number before comparing. "0" == false // Both operands convert to numbers before comparing. P.S. I could post the entire "comparison guidelines" as written in the book but it's too long ;) Just tell me and I'll edit my post for you. A: Avoid implicit type conversion in JavaScript. Always take steps to test and/or convert individual values before comparing them to ensure you are comparing apples to apples. Always test explicitly for undefined to determine if a value or property has a value, use null to indicate that object variables or properties do not refer to any object, and convert & compare all other values to ensure operations are performed against values of the same type. A: Yes, all the rules of type conversion applied by the equals operator are described on the ECMA-262 specification, in The Abstract Equality Comparison Algorithm. The algorithm might look quite complex but it can be summarized to the following cases: * *The type the two operands is the same: * *For primitives (String, Number, Boolean, Null, Undefined) * *Return true if the value is exactly the same *For the Object type * *Return true if the two references point to the same object *If the types of the two operands differ * *If the type of one operand is either Null or Undefined * *Return true only if the other operand value is either null or undefined *If one of the operands is of type Boolean or Number * *(after some steps) Convert the other operand to Number and compare *If one of the operands is an Object and the other is a primitive * *Perform Object-to-Primitive conversion on the Object and compare again The Object-to-Primitive conversion is made through an abstract operation called ToPrimitive, this method will try to convert the object to a primitive value, using the internal [[PrimitiveValue]] method. This will try to ejecute the object's valueOf and toString methods, and it will take the value of the first that returns a primitive value. In the case those two methods don't return a primitive, or they aren't callable, a TypeError is thrown, e.g.: 1 == { toString:null } // TypeError! The above statement will produce a TypeError because the default Object.prototype.valueOf method doesn't do anything more than actually the same object instance (this, not a primitive value) and we are setting an own toString property that's not a function. A friend made small tool that might be interesting to you, it shows all the steps and recursive comparisons made between types: * *JS Coercion Tool A: I know the question has been answered. What I have given below is an example of few conversions. It will be useful for someone who is new to JavaScript. The below output can be compared with the general algorithm for an easy understanding. The code: var values = ["123", undefined, "not a number", "123.45", "1234 error", "", " ", null, undefined, true, false, "true", "false" ]; for (var i = 0; i < values.length; i++){ var x = values[i]; console.log("Start"); console.log(x); console.log(" Number(x) = " + Number(x)); console.log(" parseInt(x, 10) = " + parseInt(x, 10)); console.log(" parseFloat(x) = " + parseFloat(x)); console.log(" +x = " + +x); console.log(" !!x = " + !!x); console.log("End"); } The output: "Start" "123" " Number(x) = 123" " parseInt(x, 10) = 123" " parseFloat(x) = 123" " +x = 123" " !!x = true" "End" "Start" undefined " Number(x) = NaN" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = NaN" " !!x = false" "End" "Start" "not a number" " Number(x) = NaN" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = NaN" " !!x = true" "End" "Start" "123.45" " Number(x) = 123.45" " parseInt(x, 10) = 123" " parseFloat(x) = 123.45" " +x = 123.45" " !!x = true" "End" "Start" "1234 error" " Number(x) = NaN" " parseInt(x, 10) = 1234" " parseFloat(x) = 1234" " +x = NaN" " !!x = true" "End" "Start" "" " Number(x) = 0" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = 0" " !!x = false" "End" "Start" " " " Number(x) = 0" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = 0" " !!x = true" "End" "Start" null " Number(x) = 0" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = 0" " !!x = false" "End" "Start" undefined " Number(x) = NaN" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = NaN" " !!x = false" "End" "Start" true " Number(x) = 1" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = 1" " !!x = true" "End" "Start" false " Number(x) = 0" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = 0" " !!x = false" "End" "Start" "true" " Number(x) = NaN" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = NaN" " !!x = true" "End" "Start" "false" " Number(x) = NaN" " parseInt(x, 10) = NaN" " parseFloat(x) = NaN" " +x = NaN" " !!x = true" "End" A: Better use below code for understanding implicit conversion. var values = [ 0 , 123, "0", "123", -0, +0, NaN, +NaN, -NaN, false, true, "false", "true", null, undefined, "null", "undefined", "", "GoodString", " "]; for (var i = 0; i < values.length; i++){ console.log("<<<<<<<<<<<<Starting comparing: " + i + ">>>>>>>>>>>>>>>"); for (var j = 0; j < values.length; j++){ console.log(values[i],`==`, values[j]); console.log(eval(values[i] == values[j])); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7625144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Using JSTL "dynamic" parameter name JSTL Code: <c:forEach var = "currentUser" items = "${users}"> <c:out value = "${currentUser.userName}" /></p> <c:if test = "${!empty param.${currentUser.id}}"> <p>Details</p> </c:if> </c:forEach> I have a list of user objects and i display all of their names. If one wants to see the details of any user a request is sent to a servlet which will return a Attribute with the name id and a DetailUser Object Servlet: req.setAttribute(currentUSer.getId, userDetails); The problem is that, now if have to use the value of "id" in the if test not as a parameter, but a parameter name instead. I've tried that EL in EL expression but I am really sure that it isn't allowed. Any other suggestions? A: It seems to me that you're making it more complex than it could be.I would simply do req.setAttribute("userDetails", userDetails); and, in the JSP, test if the current user's ID is the same as the one being detailed: <c:if test="${userDetails.id == currentUser.id}"> <p>Details</p> </c:if> BTW, param.foo returns the value of a request parameter, not the value of a request attribute. You could do what you wanted by using <c:if test = "${!empty requestScope[currentUser.id]}"> The [] notation instead of the . operator is the way to pass a dynamic name rather than a static one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Highcharts onclick event break my web service request. Why? I am new in web development, any help will be greatly appreciated! Please give any idea if your have in my case below. So this is situation. I have a web application. Web application has ascx page and web service. I put several charts of highcharts (client javascript charting library). And script manager with reference to web service. So, when the document is ready (i use jquery for it) my javascript function (i called it makeUpdate()) with set timeout inteval 1 sec call another javascript function GetDataWrapper(). GetDataWrapper function is wrapper for web service web method GetData() that return data for charts. You know GetDataWrapper looks like: function GetDataWrapper() { MyNameSpace.WebService.GetData(function (result, userContext, methodName) { // onSuccess may be do some new requests on something else }, function (error, userContext, methodName) { // onFailed alert error message }); } Also of course i put any expressions in WebService.GetData method in try/catch. Now if i start my aplication i'll get some delay and my charts will recieve data one by one because i have async computing data (that why i need setTimeout and call javascript makeUpdate() function several times). So if i just will wait all my charts will get data, that what i need! BUT! My highcharts have method onClick to redirect toother page by 'location.href=....' for each pie area like there: http://jsfiddle.net/ggZ9Z/1/. So If i click on first pie chart with data, when others still wating for data i'll get GetDataWrapper() onFailed alert error message without any exception in WebService.GetData() (i put breack point in this way) My question is how it could be happened event and call my function onFailed in GetDataWrapper() without exception in WebService.GetData()? Any suggestions? Anyway, thank you for your time! A: I had a lot of similar issues myself. I don't have any official documented proof to direct you to but I will detail what I have found out through different tests bellow. The reason for the call of onFailed callback is that while you try to set the location of browser to another page the current page is being unloaded in which case the browser's native XMLHTTPRequest object aborts all asynchronous requests in progress and sets the status of the response to 0. In this case the javascript proxy class generated by ASP.NET to handle the web service requests invokes the onFailed handler. My solution for this problem was to create a new proxy base class by modifying the original Sys.Net.WebServiceProxy to handle the status code '0' and call an 'onCanceled' callback instead of 'onFailed'. This solution is inconvenient because each proxy class for each web service would be needed to be generated manually. Maybe there are better solutions that I am unaware of and I would be glad if somebody has such a solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# - How to use unassigned variable in try catch block crmFactory.RegisterDemoAccount throws Exception. In order to use the variable res I need to initialize it. Since AccountRegistrationResponse is not initializable, how can I declare res without getting compilation errors about using unassigned variables? I can assign it to null, but I don't think this is a good programming approach. AccountRegistrationResponse res /*=null*/; try { res = crmFactory.RegisterDemoAccount(CrmConfigRepository.CrmOwnerUserId , CrmConfigRepository.CrmOrganizationName , CrmConfigRepository.CrmBusinessUnitName , demo.getData()); } catch (Exception e) { _log.Error("Cannot create demo account", e); } _log.Debug(res.getString()); A: You shouldn't try to continue your method after catching an unknown exception. Anything could have gone wrong and it makes no sense to assume that it's safe to continue. Only bad things can happen if you try. Either return an error result, or better, just rethrow the original exception: catch (Exception e) { _log.Error("Cannot create demo account", e); throw; } Now the compiler can see that res will always be assigned after the try block completes successfully. A: I understand your reluctance to assign res to null - it feels pointless, and therefore wrong. It is a common approach in situations like this, though, when an object is needed outside the block in which it's assigned. Assuming you're doing the right thing in assigning your variable in a try/catch block (and it's not an uncommon pattern, in many cases), I wouldn't worry about it. However, what would happen if the assignment failed? The second logging call would try to dereference res, and throw a NullReferenceException. That's not good. A: You need to put the logging line inside the try/catch so that the compiler knows that res has been initialised. try { res = ... _log.Debug(res.getString()); } catch (Exception e) { _log.Error("Cannot create demo account", e); } A: It's THE right approach. Only thing, if null is a valid return value of RegisterDemoAccount, you could add a bool initialized = false that you set to true just after the RegisterDemoAccount. A: Assign it to null, like you said, if you need it outside of try/catch. It's not bad way of programming. A: but I don't think this is a good programming approach. Why? If you don't initialise res and then RegisterDemoAccount(...) (or another expression before it) throws then res will not be assigned in the try statement. Therefore execution could reach the final statement (after the catch block) with res unassigned. The problem is the use of res in that last statement – the compiler can see it can get to this point without initialisation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Function to use with multiple elements I have modified a function to meet my need. This is what I have written to restrict multiple repetition of dots: $('#title').val(){ replace(/\.{2,}/g, '.'); }); Is it correct? How can I make this in function so I can call with every element of the form? A: 1. Here is your code turned into a jQuery function/plugin. jQuery.fn.singleDotHyphen = function(){ return this.each(function(){ var $this = $(this); $this.val(function(){ return $this.val() .replace(/\.{2,}/g, '.') .replace(/-{2,}/g, '-'); }); }); } 2. Here is how you use it $('selector').singleDotHyphen(); 3. Here is the demo A: Something like this would work - $('input[type=text],textarea').blur(function () { $(this).val(function () { return $(this).val().replace(/\.{2,}/g, '.'); }); }); That would apply your RegEx to every 'text' or 'texarea' input field once it lost focus. Here's a demo - http://jsfiddle.net/xcBFx/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7625158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Conversion of Datetime from server to another server I have SQL Server 2000 in both server. We have imported existing data to new server. And also we use vb application. Now we changing our data to new server. When we run application to retrieve date wise details it shows error 'The Conversion of Datetime to varchar is out of range' And we pass our datetime from application is dd/mm/yy but values get inserted as mm/dd/yyyy. Is there any solution. please. thanks in advance A: You should check the default language of the login running the queries. Probably is configured in English in the new server and not English (maybe Spanish?) in the old server. A: They are likely to be English and British English as mm/dd/yyyy and dd/mm/yyyy respectively. Open the login properties under security in ssms object explorer on the new server and set it to British English.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: parentNode.getElementById() is not working I encountered a problem while practicing html. When I used parentNode in JavaScript, I thought it is not hard to treat. But to get some element under parentNode using getElementById or another function is not working as my thinking. var this_question = selectObj.parentNode.parentNode; alert(this_question); //it is working perfectly alert(this_question.getElementById('question')) It's not working. I can't understand... <script> function addQuestion(selectObj) { var this_question = selectObj.parentNode.parentNode; alert(this_question); //it is working perfectly alert(this_question.getElementById('question')) //It's not working. I can't understand.. } </script> <ol id="question_list"> <li> <textarea class="question" name="question" id="question"></textarea> <select name="question_type" id="question_type" onChange="javascript:selectEvent(this)"> <option>-----</option> <option value="text" >단답형</option> <option value="paragraph" >서술형</option> <option value="multiple_choice">다지선</option> <option value="checkbox">다중선택</option> <option value="scale">scale</option> </select> <div id='answer_div'><p>부가설명:<input name='top_label' id='top_label' type='paragraph' /></p> <p>답변:<input name='answer_text' id='answer_text' type='text' /></p></div> <p> <input type="button" value="Add Question" onclick="javascript:addQuestion(this)"/> <input type="button" value="Done" onclick="javascript:finish()"/> </p> </li> </ol> A: getElementById() is a method of documents, not available in elements. You may use: this_question.getElementsByTagName('textarea')[0] getElementsByTagName() is available in elements. A: You have two elements with the same id attribute but id attributes must be unique: * *<ol id="question"> *<textarea class="question" name="question" id="question"></textarea> When you duplicate id attributes strange things happen. If you change the <textarea> to have id="question_text", for example, things start working better: http://jsfiddle.net/ambiguous/67DZr/ From the HTML4 specification: id = name [CS] This attribute assigns a name to an element. This name must be unique in a document. and from the HTML5 specification: The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. A: You can use: baseElement.querySelector('#' + id) It returns: The first descendant element of baseElement which matches the specified group of selectors. See: https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector
{ "language": "en", "url": "https://stackoverflow.com/questions/7625165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: publishing Db after creating using EF Code first I have created a project in MVC 3 using code first and nugget , And I would like to clear a few thing before publishing to my shared hosting: In my project I have a class name: IchudShulContext (IchudShul is my project name) In my sql server express it has created a DB name: IchudShul.Models.IchudShulContext.dbo Does it make a different what name I give my shared hosting DB ? Or should it match one of the following : IchudShul / IchudShulContext My local connectionStrings look like this : connectionString="Data Source=MyPc-MAINPC\SQLEXPRESS;Initial Catalog=IchudShul.Models.IchudShulContext;Integrated Security=True" providerName="System.Data.SqlClient" /> Thanks A: Based on Code-First convention, Your ConnectionString name in your web.config should have the same name as your context. Database name is not important. in your scenario, in your web.config: <connectionStrings> <add name="IchudShulContext" providerName="System.Data.SqlClient" connectionString="Data Source=MyPc-MAINPC\SQLEXPRESS;Initial Catalog=WHATEVER_YOUR_DB_NAME_IS;Integrated Security=True" /> </connectionStrings> If you want to use conventions, make sure the name attribute is: IchudShulContext. That's all. Fill in WHATEVER_YOUR_DB_NAME_IS with whatever you db name is. A: Your shared hosting DB can be named anything. Your ConnectionString should be updated needs to be updated to point to your database. What that is, you will need to know from your shared hosting provider. A: you can name you DB anything, as long as it is valid with respect to your DBMS. the only this that should be matched with your datacontext name is connection name in connection strings section of your web.config file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode confusion - property and synthesize, retain? I see the property and synthesize being used without "declaring the variable" first.. and I'm a bit confused about what properties to use. I want to alloc and init my viewController in AppDelegate and then be sure it's there for the remainder of the run. Clearly I want retain-property?.. however.. since alloc returns the viewController with retain count 1, it seams a lot smarter to just use leave the retain-property out. No other class will use my setter, so I don't care then? Ex. in AppDelegate.h: @propert(nonatomic,retain) MyViewController *myViewController; in AppDelegate.m: @synthesize myViewController = _myViewController; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.myViewController = [[[EventDataController alloc] init] autorelease]; [self.window makeKeyAndVisible]; return YES; } or.. in AppDelegate.h: @propert(nonatomic) MyViewController *myViewController; in AppDelegate.m: @synthesize myViewController = _myViewController; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.myViewController = [[EventDataController alloc] init]; [self.window makeKeyAndVisible]; return YES; } Set me straight, please. A: You don't need to define instance variables for properties anymore - @synthesize does that for you. As for your other question - you can do it either way, but don't forget to release it in your -dealloc. I like (nonatomic, retain), because it is very clear and easy to use/understand. All you do is assign and it does all the rest: self.myViewController = [[[ViewController alloc] init] autorelease]; In your -dealloc: self.myViewController = nil; In the case of manually releasing you might want to forget about properties at all and only use instance variables like this: @interface MyClass: NSObject { ViewController* _myViewController; } @end In your implementation: _myViewController = [[ViewController alloc] init]; In your -dealloc: [_myViewController release]; _myViewController = nil; Note that the last assignment of nil might be unnecessary, but I've had too many hard-to-track bugs with this (and that's why I love retained properties - all you need to do is set them to nil). I try to always go with retained properties as this saves me some brain cycles and I don't care about the nanosecond I could save for the CPU otherwise. A: I would go with the first option. Why can't you explicitly release myViewController when you're done with it? I wouldn't make assumptions like "this class will never be used by anybody else". A: of the options, i prefer declaring the property with retain. this is documentation for your sake, and it can save you from silly mistakes because of tools such as static analysis. since your class owns the controller, it should be declared that it holds a reference to it, regardless of implementation details. deviation from conventional idioms is a good way to introduce bugs. you should also declare it as readonly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSRS chart to show totals by hour I have the following data: +--------------------------+---------------+ | Date Time | Number of Hit | +--------------------------+---------------+ | 2011-10-03 13:01:00 + 10 | 2 | | 2011-10-03 13:05:00 + 10 | 3 | | 2011-10-03 14:01:00 + 10 | 4 | | 2011-10-03 14:04:00 + 10 | 5 | +--------------------------+---------------+ I would like to create a Chart using Reporting Services that shows: 13 - 5 14 - 9 Basically I would like to show the number of hits by hour. Could someone show me how to do it ? A: Depends on what other requirements you have, but probably easiest to group by hour in you SQL query: SELECT DATEADD(hour, DATEDIFF(hour, 0, myDateTimeColumn, 0)) AS TimeByHour, SUM(hitCount) as Hits FROM WebRecordsTable GROUP BY DATEADD(hour, DATEDIFF(hour, 0, myDateTimeColumn, 0)) Then create a chart in SSRS and drag the Hits field to the Values section.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should I call socket::connect() from a handler invoked by resolver::async_resolve()? I'm using a wrapper class to represent a network connection. My implementation contains a method, called async_connect(), which resolves a host/service and connects to a related endpoint (if possible). Something like this: void tcp::connection::async_connect(std::string const& host, std::string const& service, protocol_type tcp = protocol_type::v4()) { std::cout << "thread [" << boost::this_thread::get_id() << "] tcp::connection::async_connect()" << std::endl; resolver(m_io_service).async_resolve(resolver::query(tcp, host, service), boost::bind(&connection::resolve_handler, this, _1, _2)); } What I want to do know, is establishing the connection from the handler, invoked by the completion of the async_resolve method. I'm not sure wheter the main thread or the a worker thread is used to invoke the handler. Thus, should I call socket::connect() (this would be the most sensible way if that code would be executed from a worker thread) or start an asynchronous operation again (socket::async_connect() - which should be used when executed by main thread). void tcp::connection::resolve_handler(boost::system::error_code const& resolve_error, tcp::resolver::iterator endpoint_iterator) { std::cout << "thread [" << boost::this_thread::get_id() << "] tcp::connection::resolve_handler()" << std::endl; if (!resolve_error) { boost::system::error_code ec; m_socket.connect(*endpoint_iterator, ec); } } I've observed - from console output - that my resolve_handler is called from a worker thread. So, is it okay to call socket::connect() here? A: IMO it is good to stick to a single programming model when using asio. You are free to use asio's synchronous (blocking) calls, where you call a number of methods (resolve, connect, etc) and each one blocks until the result or error is available. However If you're using the asynchronous programming model, your main or calling thread is typically blocked on io_service::run and the specified handlers are called from a different thread ( as is the case in what you described). When using this programming model you would typically call the next async method from the handler (worker thread), so instead of calling socket::connect, you would call socket::async_connect. It looks to me like you are trying to mix the two different models. I'm not sure what the implications are of mixing the two models (with your calling thread blocked on io_service::run) and you calling a synchronous method from the handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I deploy apps to Blackberry devices without signing? Is it necessary to sign apps before deploying them to devices? Isn't there a workaround where we can deploy apps without signing? A: It is possible to run an unsigned application on actual device, only if you did not use "signed API" classes. In RIM API javadoc for every class there is information, does it belong to signed API or not. For instance, Bitmap does not belong to "signed API". But Display class does. Excerpt from Display class description: Signed: This element is only accessible by signed clients. If you intend to use this element, please contact RIM to establish the necessary agreements that will allow you to have your COD files signed. Signing is only required for use on the device, development under the JDE can occur without signing the CODs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: dojo Show/Hide One ContentPane While Another ContentPane Is Liquid I've been struggling for weeks trying to crack this nut so I'm not sure if it's impossible, or if it's my lack of coding chops... or both. I'm not a programmer and I'm a newbie to Dojo Toolkit. I have a site using the BorderContainer layout. I'm trying to create an effect where I can use a button to open and close a dropdown type box that will contain controls. I need this dropdown to be hidden on page load, and then open when you click the button. My problem is that when I open the dropdown, it pushes the content pane below it off the bottom of the browser window. I need the lower ContentPane to stay fit within the remaining space of the browser window when the dropdown opens. Additionally, I want the dropdown to sit outside of the scrollable container for the content below it, which is why I have it set up to sit outside a nested BorderContainer below it. I've created a simplified version of the code to demonstrate my challenge (see link below). If you load the page you can see the center ContentPane scrolls the content. But, if you then click on the button, a dropdown div expands above the content. Then when you scroll, you'll notice that you can't see the full pane because it's in no-man's-land below the bottom of the browser window. I assume that because the div is set to display:none on load, it's size is not accounted for on page load. Then, when you open it by pressing the button, it's size is additive and the pane below doesn't know how to resize or account for the new element. I've tried using the visibility attribute, but that leaves a gap for the div when it's still closed. I've tinkered with some code that controls the height that shows promise, but each of my dropdown boxes will be different sizes so I'd prefer that the height be set to "auto" rather than a specified pixel size. Does anyone have any idea how I can accomplish this so that the lower pane will fit in the space without pushing off the screen? Here's a sample of the page: http://equium.com/scaffold.html (I had some problems trying to insert the full HTML page here as a code sample so if that's a preferable way to handle it, and someone can let me know the best way to embed all of that code, I'd appreciate it.) Thanks is advance, I'd really apprecaite anyone's feedback. A: You might want to take a look at dojox.layout.ExpandoPane (though be warned I think it has only worked properly for top and left regions for a while). Also, I'd suggest simplifying/altering your layout a bit. See example here: http://jsfiddle.net/taFzv/ (It'd probably need some tweaking to get exactly what you want.) The real issue you're having is probably that the BorderContainer has no idea that parts of the view resized. ExpandoPane takes care of that by telling the BorderContainer to re-layout after its animation completes. A: It works under IE8.0. When dropdown box open, just keep pressing mouse from page and drag to bottom, you could see the content was pushed to out of page. It looks the browser could not detect it and could not add it to "scroll bar" account. A: I would suggest taking out all BorderContainers except your top level one, the one with mainPage as the id. Place your {stuff here} div into the mainPage BorderContainer, after the ContentPane with the Close/Open button. Make sure you make it dojotype dijit.layout.ContentPane, set up layoutpriority, and set region to top. Set the height to 0/x when clicking the Open/Close button, instead of setting display. Try your page again. If that doesn't fix it, you probably need, a call to layout, resize, or both to indicate to the BorderContainer that it needs to evaluate all its children and size the "center" pane properly. Something like dijit.byId("mainPage").layout(); Do this any time someone presses the Close/Open button, after you have changed the height of any BorderContainer children. A: Maybe the dijit.form.DropDownButton would fit your needs. When click the button a tooltip is displayed that can be filled with any content you want. Just as you specified, the dropdown tooltip is only displayed when you click the button, and it doesn't mess with the underlying layout at all. The tooltip sits "on top" of the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE and multiple float elements i'm trying to position a number of buttons with float and it works just fine in all browsers. but the Internet Explorer adds some wird element after the 2 floating button (or before the third floating button). Can anybody help me? Here's a picture! Here's my code: <style type="text/css"> .button { width:auto; height:23px; border:1px solid #cccccc; border-radius:4px; background-image:url('bg_button.jpg'); background-position:left; background-repeat:repeat-x; font-family:Tahoma; font-size:13px; float:left; margin-right:4px; cursor: pointer; padding-right:10px; } ........... </script> <div class="button"> <a href=''> <div> &nbsp; </div> </a> </div> <div class="button"> <a href=''> <div> Button 1 aksjd fklaj sdklfaj sdlkfasdf </div> </div> <div class="button"> <a href=''> <div> Button 1 </div> </div> A: Put a full-width container around everything and float that. I can't say for sure it will work (since I can't reproduce it), but in IE floating the parent very frequently helps. Edit: Never mind. You can't put a div inside an A. If you do, the browser will close the A before the div and then you have all sorts of weird problems. (And you aren't even closing 2 of your A's.) Use span instead, and if you need to, put style="display: block;" on the span.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery - Background color not changing Possible Duplicate: jQuery animate backgroundColor Changing the background color of a <div> section I have the following code trying to change the background color of a text after pressing a button. The case is that it is not doing what it is intended to do. Why is that? What is going wrong here. HTML code <html> <head> <script type="text/javascript" src="jquery-1.6.4.js"></script> <script type="text/javascript" src="script.js"></script> <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script> <style type="text/css"> #name{ background-color: #FFFFF2; width: 100px; } </style> </head> <body> <input type="button" id="bgcolor" value="Change color"/> <div id="name"> Abder-Rahman </body> </div> </html> script.js $("#bgcolor").click(function(){ $("#name").animate( {backgroundColor: '#8B008B'}, "fast");} ); EDIT I want to notice that I have a folder called: jquery-ui-1.8.16.custom, and this is where I'm putting these files in. And, I have referenced jquery-1.6.4,js as shown above which I also have it in the same folder, in addition to referencing jquery-ui-1.8.16.custom.min.js which is in the js folder in the current folder. What am I getting wrong here? Isn't this the way to reference jQuery and jQueryUI? Browser used: Mozilla Firefox 6.0.2 Folder structure: jquery-ui-1.8.16.custom/abc.html jquery-ui-1.8.16.custom/script.js jquery-ui-1.8.16.custom/jquery-1.6.4.js jquery-ui-1.8.16.custom/js/jquery-ui-1.8.16.custom.min.js Thanks. A: <script type="text/javascript" src="jquery-1.6.4.js"></script> <script type="text/javascript" src="script.js"></script> <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script> Are the references point correct path? It is working on jsfiddle after removing the references. A: Despite the fact that (sorry) your code looks horrible (wrong order of html tags, you include jquery twice, ...) animate() doesn't work with backgroundColor out of the box and you will need the color plugin. mu is too short posted a link to a related thread in his comment on your post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could not find rack-cache-1.0.3 in any of the sources I have created a very basic Rails 3.1 app, deployed to a box that runs Ruby 1.8.7 (P334) (I can't easily go to 1.9.2. there unfortunately). After deploying and running 'bundle install' I tried to run a console: bundle exec rails console And I get: Could not find rack-cache-1.0.3 in any of the sources and the console does not come up. It seems that this particular version of rack-cache is listed as a dependency by ActionPack 3.1.0. Can someone explain to me what I need to do to resolve this, i.e. get bundler to attach this version of rack-cache to the project? Also I read that bundler stores the project-specific GEMs 'somewhere else', i.e. no longer in the global Ruby GEM path. Is there a default location for this project specific place ? Oh and I also keep getting heaps of 'invalid gemspec' warnings with Rails 3.1, i.e.: Invalid gemspec in [/usr/local/lib/ruby/gems/1.8/specifications/rack-cache-1.0.3.gemspec]: invalid date format in specification: "2011-08-27 00:00:00.000000000Z" A: Ran into this issue when upgrading my Rails 3.0 app to 3.1. Edit the /usr/local/lib/ruby/gems/1.8/specifications/rack-cache-1.0.3.gemspec file and set s.date = %q{2011-08-27}. This will fix your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to protect media content (video, audio) on Android from being saved/redistributed? What opportunities are there for regular app developers (with that I mean, you're not a million dollar content producing company or distribution channel provider, but a regular, small app development company) to secure video/audio content for the app from being saved/distributed. I mention the 'regular developer', because I had seen in the Android core code that Sony had added some code portions into it, in the DRM packages. Let's assume we're not that powerful to talk to Google to include such in their core code. Are there any real secure ways to protect video/audio (as part of an app) on Android. Assumptions (correct me if I'm wrong): * *devices could be rooted by the users, need to be aware of that *detection whether a device is rooted or not (within an app) is not really possible on Android, as a super user can basically fake any state of the device. *we cannot modify any hardware or the user's system (meaning: we don't bundle our app product with a device, the app should be available as a 'regular' app on the App Market for download) *the media files/stream could be locally on the device or come remotely from a server, both is ok I have researched this topic quite a bit, googled a lot, went through (hopefully) all related questions here on SO, I have talked to one DRM provider (which is really hard to get in touch with as a small company or freelance developer, or at least to get some real relevant information, technical docs and details). I looked into DRM as one approach, but "security-by-obscurity" does not seem to be a very good way. Besides, I haven't found any information or real solutions/APIs for regular developers. Public-key encryption was another idea, but where to store the private key really safely? Furthermore, I assume that in such case, the entire media framework & player would need to be rewritten, in order to pass a secure video stream to the player. Or am I mistaken? I would like to get some opinions from other experienced developers in the field, as it's really hard to find information about media content protection for Android anywhere. Update: In the context of my question, I found this Question and it's update interesting: Streaming to the Android MediaPlayer A: Are there any real secure ways to protect video/audio (as part of an app) on Android. If by "secure", you mean "fullproof", then no. See Analog hole. detection whether a device is rooted or not (within an app) is not really possible on Android Nor is it possible anywhere. the laws of the universe make it impossible to detect such a thing, (okay, maybe you could exploit quantum physics for this, but even then I'm not sure) you can only add code to detect known techniques, all of which are trivial to bypass. Public-key encryption was another idea, but where to store the private key really safely? There is nowhere to store it safely. Think about it, you want to encrypt content and give the user the key to decrypt it (so he can watch it), but you don't want him to be able to decrypt it (so he can't copy it). This is a contradiction. The most you can do is encrypt your stream to prevent the user from being able to just intercept it and use it. Then obfuscate the code that decodes/plays the stream. Though by implementing that you risk introducing more bugs (and worse performance), making the legitimate user's experience worse. If decide not to roll your own obfuscation, and use some automatic obfuscater product already available by some big company, it will already be generically cracked, and it will be extremely easy for someone who hardly knows what he's doing to crack your product in a small amount of time. As long as your product becomes remotely popular, one person is going to crack it and upload all the videos to torrent, then everyone will be able to pirate your product without doing any work. A: I don't think there is a solution to protect media content in apps from being ripped off. DRM is of course not suitable for regular developer. I don't see also why public key can help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: JavaScript Center Align How can I align the entire script to center? I've never actually coded before in javascript and I just want to modify a quick bookmarklet. I've tried stuff like align=center for different components of the script but no luck. Is there something like <center> (in html) for js? Thanks EDIT: basically i want this to be centered on a page function dEmbed(){ var iframe = document.createElement("iframe"); iframe.src = 'http://www.google.com'; iframe.style.width = w+'px'; iframe.style.height= h+'px'; iframe.style.border= "0"; iframe.style.margin= "0"; iframe.setAttribute("scrolling","no"); iframe.setAttribute("id","NAME"); document.body.insertBefore(iframe, document.body.firstChild); } A: You can't centre a script, it doesn't look like anything so there is nothing to centre. If the script generates some HTML, then you can to centre the generated elements. This should be done using the usual CSS techniques applied to the generated element. (<center> and the align attribute were deprecated in 1998 and shouldn't be used). A: I was able to achieve this by injecting the iframe into an existing div with text-align: center. Here is the example: http://jsfiddle.net/MarkKramer/PYX5s/4/ A: Try changing: iframe.style.margin= "0"; To: iframe.style.margin= "auto"; If it doesn't work, let me know in a comment. OK, try this change instead, change: var iframe = document.createElement("iframe"); to: var div = document.createElement("div"); div.style.width = w+'px'; div.style.margin= "auto"; var iframe = document.createElement("iframe"); And change: document.body.insertBefore(iframe, document.body.firstChild); To: div.appendChild(iframe); document.body.insertBefore(div, document.body.firstChild);
{ "language": "en", "url": "https://stackoverflow.com/questions/7625212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Draw Multiple objects in java? Hey guy's im making a java game where yellow blocks appear randomly across the game screen and you have to collect them. These objects are created from one class and i was wondering if there is a way to draw all of them? This is the code that spawns them: package OurGame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.*; public class coins extends JPanel implements ActionListener { Timer t; coin c; public coins() { t = new Timer(1000,this); t.start(); } public void actionPerformed(ActionEvent e) { System.out.println("1 Second"); Random rx = new Random(); Random ry = new Random(); c = new coin(rx.nextInt(640),ry.nextInt(480)); } } and this is the code for the coin itself. package OurGame; import java.awt.Image; import javax.swing.ImageIcon; public class coin { Image coin; int x,y; public coin(int x1, int y1) { ImageIcon i = new ImageIcon("C:/coin.png"); coin = i.getImage(); x = x1; y = y1; } public Image getImage(){ return coin; } public int getX(){ return x; } public int getY() { return y; } } Would be awesome if you could help. A: Why not create an ArrayList of Coin (class names should be capitalized) or ArrayList. Then if you need to add or remove a Coin from the display, you would add or remove it from the ArrayList. Then the paintComponent method could iterate through the array list in a for loop drawing each coin in the loop. Also, The simplest way to display a Coin would be to put it into an ImageIcon and then use that to set a JLabel's icon. e.g. with image scaling to make coin smaller and with image filter to change white background to transparent: import java.awt.Color; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.awt.image.ImageProducer; import java.awt.image.RGBImageFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.*; public class Coins extends JPanel implements ActionListener { private static final String COIN_URL_PATH = "http://cdn.dailyclipart.net/wp-content/uploads/medium/clipart0273.jpg"; private static final String COIN_URL_PATH2 = "http://content.scholastic.com/content/media/products/71/0439510171_rgb15_xlg.jpg"; private static final String COIN_URL_PATH3 = "http://uscoinstoday.com/images/e/130580876887_0.jpg"; private static final int PAN_WIDTH = 900; private static final int PAN_HT = 700; protected static final int TRANSPARENT = new Color(255, 255, 255, 0) .getRGB(); private Timer t; private BufferedImage coinImage; private ImageIcon coinIcon; private Random random = new Random(); public Coins() { setLayout(null); try { coinImage = ImageIO.read(new URL(COIN_URL_PATH)); double scaleFactor = 0.35; BufferedImage destImg = new BufferedImage((int)(coinImage.getWidth() * scaleFactor), (int) (coinImage.getHeight() * scaleFactor), BufferedImage.TYPE_INT_ARGB); AffineTransform at = AffineTransform.getScaleInstance(scaleFactor, scaleFactor); AffineTransformOp ato = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC); ato.filter(coinImage, destImg); ImageFilter whiteToTranspFilter = new RGBImageFilter() { @Override public int filterRGB(int x, int y, int rgb) { Color color = new Color(rgb); int colorSum = color.getBlue() + color.getRed() + color.getGreen(); int maxColorSum = 600; if (colorSum > maxColorSum ) { return TRANSPARENT; } return rgb; } }; ImageProducer ip = new FilteredImageSource(destImg.getSource(), whiteToTranspFilter); Image destImg2 = Toolkit.getDefaultToolkit().createImage(ip); coinIcon = new ImageIcon(destImg2); t = new Timer(1000, this); t.start(); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(-1); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } @Override public Dimension getPreferredSize() { return new Dimension(PAN_WIDTH, PAN_HT); } public void actionPerformed(ActionEvent e) { System.out.println("1 Second"); Coin c = new Coin(random.nextInt(640), random.nextInt(480), coinIcon); add(c.getCoinLabel()); revalidate(); repaint(); } public static void main(String[] args) { Coins coins = new Coins(); JFrame frame = new JFrame("Coins"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(coins); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class Coin { JLabel coinLabel = new JLabel(); public Coin(int x1, int y1, ImageIcon coinIcon) { coinLabel.setIcon(coinIcon); coinLabel.setLocation(x1, y1); coinLabel.setSize(coinLabel.getPreferredSize()); } public JLabel getCoinLabel() { return coinLabel; } } A: You have two options: 1) Save a list of all coins and override the paintComponent() method for your JPanel and call rePaint() after a coint is added. 2) Coin could extend some JComponent which provides a paintComponent method; then you could call this.add( ... ) in you JPanel; and this.rePaint(). Some side note: 1) Your Image should be static; otherwise there is an Image for every coin; although it's the same image. Example code: package OurGame; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Random; import javax.swing.*; public class coins extends JPanel implements ActionListener { private Timer t; private ArrayList<Coin> coins = new ArrayList<Coin>(); public coins() { t = new Timer(1000,this); t.start(); } public void actionPerformed(ActionEvent e) { System.out.println("1 Second"); Random rx = new Random(); Random ry = new Random(); this.coins.add(new Coin(rx.nextInt(640),ry.nextInt(480))); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); for(Coin coin : this.coins) { g.drawImage(coint.getImage(), coin.getX(), coint.getY(), observer); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7625215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Returning a reference to *this, from an anonymous object on stack Suppose the class Coord3D has a method Point2D& Coord3D::get2DPart(){ return *(Point2D*)this; } (Coord3D is just int x; int y; int z;, and Point2D is the 2D version of it with exactly int x; and int y;) Would the following be safe: Point2D x = Coord3D(1,2,3).get2DPart(); Or even something like Coord3D x = Coord3D(1,2,3).getSelf(); where getSelf() is a function which does return *this; Seems like it'll probably be safe, but people I asked aren't sure about it. Is this OK? Edit: this is what coord3D and Point2D are: struct Coord3D{ float x; float y; float z; }; struct Point2D{ float x; float y; }; A: Point2D x = Coord3D(1,2,3).get2DPart(); is equivalent to: Point2D x( Coord3D(1,2,3).get2DPart() ); The temporary Coord3D you create here will last as long as Point2D's constructor is being executed. Therefore, using Coord3D'a this in that scope is safe. Note that *(Point2D*)this smells. If Point3D inherits from Point2D, you can just return *this. If they are unrelated, it's dangerous. Edit, following the question's update regarding the types: Given Point2D and Point3D are not related, casting one into the other might work, but it's highly unadvised. A better approach would be to have Point3D inherit from Point2D. Another option would be to add, say, a GetPoint2D() to Point3D, and have it create a new 2D point out of the 3D. However, you might have then a real issue with returning references to local variables. Lastly, if you do take the risk and cast as is, at least use reinterpret_cast and not the C-style cast. A: Assuming the cast is valid in the first place (common subsequence of a standard layout type or whatever applies in your case), then yes this is valid as *this will live until ;.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: get all calls to a function in javascript Is there a way to find all the functions that call another function? (And then by extension, all the functions that call those functions, etc.) My guess is it won't be possible for all cases, but certainly it could be done for most use cases, no? Like if somebody defines their function as: new Function('a','b', 'return a'+'+b;'); it might be more tricky to find inner references. Thanks in advance. A: There is a arguments.caller but it's deprecated. Function.caller is replacement but you need function name - I'd use arguments.callee or directly the name. https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/caller A: In addition to its excellent outline view, Eclipse lets you "focus" the calls of a function in the source by selecting its declaration and then pressing F2. Appearances will be displayed in the right bar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: debugging a function in R that was not exported by a package I would like to step through, using debug() or trace(), a function that was not exported. For example, how can I do it for vcov.polr of the package MASS, which is called from the function polr. polr is exported, but vcov.polr is not. That is, when I run polr, I would like the debug browser to start once the code enters vcov.polr. A: try debug(MASS:::vcov.polr) note that three colon ::: make the hidden object in a package visible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Compile Setup project with devenv.com - "ERROR: Unable to update the dependencies of the project" I have a Setup deployment project in VS 2010. The project compiles perfectly with the GUI interface of VS 2010, but any time I trying to compile it via vs cmd (devenv.com) it comes up with this error: ERROR: Unable to update the dependencies of the project. Notice that there is NO dll that mentioned in the error (e.g. the error does NOT contain "The dependencies for the object ‘xxx’ cannot be determined"). Please do not tell me to clean all the files in this setup and start from ground up - this is not a real solution! I have 5 projects with this exact error, and I don't want to re-arrange each one. More then that, this does not promise me that the problem will not re-occur in the future. Thanks very much! A: I used to rebuild these installer projects from scratch when they stopped working (for whatever reason), but I've found a much much quicker (and less error-prone) workaround. It works for me. Maybe it will work for you. * *Remove the Installer project from your solution through the IDE interface *Add the Installer project back into your solution (Add > Existing Project...) *Rebuild It works practically every time for me... A: I fixed this by editing the vdproj by hand and removing the Hierachy and File sections and then rebuilding the vdproj see: Setup project error: Unable to update the dependencies of the project A: The hotfix didn't fix the issue on my computer (tried on two computers, rebooted all that jazz) Instead I used source control to figure out what happened to my .vdproj. It appears extra corrupt entries are added to the "File" section of the .vdproj. Suppose you are getting an error such as ERROR: Unable to update the dependencies of the project. The dependencies for the object 'AutoMapper.DLL' cannot be determined. In your .vdproj search for AutoMapper and you should come across several { } where it is used. A normal one looks like this: "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_263299FB43D185D41A44FBEE0253D3ED" { "AssemblyRegister" = "3:1" "AssemblyIsInGAC" = "11:FALSE" "AssemblyAsmDisplayName" = "8:AutoMapper, Version=1.1.0.188, Culture=neutral, PublicKeyToken=be96cd2c38ef1005, processorArchitecture=MSIL" "ScatterAssemblies" { "_263299FB43D185D41A44FBEE0253D3ED" { "Name" = "8:AutoMapper.DLL" "Attributes" = "3:512" } } "SourcePath" = "8:AutoMapper.DLL" whereas a corrupt chunk is missing the name of the dll (AutoMapper.DLL in this case) in the ScatterAssemblies section. Remove this corrupt entry, that is the entire section starting from "{9F6F8455-.. down to the next chunk. A: This worked for me: * *Run a clean solution command from VS2010 *Open source code folder in explorer *Search for *.exe files, sort by location *Manually delete all files in Release folder If there exists some_project.vshost.exe locked up file, open properties of this project in VS, and uncheck "Enable the Visual Studio hosting process" under debug. Then remove it as well. It should build now. A: This is copied from @timB33's external link, which works. All links to the MS hotfix appear to broken, so this was the only way I could find to fix without removing and recreating the setup project. I have consistently used this method to get around this bug instead of rebuilding my setup projects. This applies to both merge module projects AND setup projects. Manually remove the data in the Hierarchy and Files section of the project files. * *Open .VDPROJ file *Find the "Hierarchy" section. Delete everything so the section looks like this: "Hierarchy" { } *Find the "File" section. Delete everything so the section looks like this: "File" { } *Reload the project *Rebuild the project. *You may need to re-add project outputs if missing something A: support.microsoft.com/kb/2286556 thanks Hans, this update fixed my problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: MissingFormatArgumentException error I have been successful in compiling my inventory program: // Inventory.java part 1 // this program is to calculate the value of the inventory of the Electronics Department's cameras import java.util.*; import javax.swing.*; import java.awt.event.*; import java.io.*; public class Inventory { public static void main(String[] args) { // create Scanner to obtain input from the command window Scanner input = new Scanner (System.in); String name; int itemNumber; // first number to multiply int itemStock; // second number to multiply double itemPrice; // double totalValue; // product of number1 and number2 while(true){ // infinite loop // make new Camera object System.out.print("Enter Department name: "); //prompt String itemDept = input.nextLine(); // read name from user if(itemDept.equals("stop")) // exit the loop break; { System.out.print("Enter item name: "); // prompt name = input.nextLine(); // read first number from user input.nextLine(); } System.out.print("Enter the item number: "); // prompt itemNumber = input.nextInt(); // read first number from user input.nextLine(); while( itemNumber <= -1){ System.out.print("Enter valid number:"); // prompt itemNumber = input.nextInt(); // read first number from user input.nextLine(); } /* while statement with the condition that negative numbers are entered user is prompted to enter a positive number */ System.out.print("Enter number of items on hand: "); // prompt itemStock = input.nextInt(); // read first number from user input.nextLine(); while( itemStock <= -1){ System.out.print("Enter positive number of items on hand:"); // prompt itemStock = input.nextInt(); // read first number from user input.nextLine(); } /* while statement with the condition that negative numbers are entered user is prompted to enter a positive number */ System.out.print("Enter item Price: "); // prompt itemPrice = input.nextDouble(); // read second number from user input.nextLine(); while( itemPrice <= -1){ System.out.print("Enter positive number for item price:"); // prompt itemPrice = input.nextDouble(); // read first number from user input.nextLine(); } /* while statement with the condition that negative numbers are entered user is prompted to enter a positive number */ Cam camera = new Cam(name, itemNumber, itemStock, itemPrice); totalValue = itemStock * itemPrice; // multiply numbers System.out.println("Department name:" + itemDept); // display Department name System.out.println("Item number: " + camera.getItemNumber()); //display Item number System.out.println("Product name:" + camera.getName()); // display the item System.out.println("Quantity: " + camera.getItemStock()); System.out.println("Price per unit" + camera.getItemPrice()); System.out.printf("Total value is: $%.2f\n" + totalValue); // display product } // end while method } // end method main }/* end class Inventory */ class Cam{ private String name; private int itemNumber; private int itemStock; private double itemPrice; private String deptName; public Cam(String name, int itemNumber, int itemStock, double itemPrice) { this.name = name; this.itemNumber = itemNumber; this.itemStock = itemStock; this.itemPrice = itemPrice; } public String getName(){ return name; } public int getItemNumber(){ return itemNumber; } public int getItemStock(){ return itemStock; } public double getItemPrice(){ return itemPrice; } } C:\Java>java Inventory Enter Department name: Electronics Enter item name: camera Enter the item number: 12345 Enter number of items on hand: 8 Enter item Price: 100.50 Department name:Electronics Item number: 12345 Product name:camera Quantity: 8 Price per unit100.5 Total value is: $Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '.2f' at java.util.Formatter.format(Unknown Source) at java.io.PrintStream.format(Unknown Source) at java.io.PrintStream.printf(Unknown Source) at Inventory.main(Inventory.java:82) I seem to come to this format error and cannot see why. A: This is the problem: System.out.printf("Total value is: $%.2f\n" + totalValue); I think you meant: System.out.printf("Total value is: $%.2f\n", totalValue); In other words, specify the value to replace the placeholder with, instead of just using string concatenation to add the value to the send of the format string. In general though, when you get an exception you don't understand, you should look at the documentation for it. In this case, the docs are reasonably clear: Unchecked exception thrown when there is a format specifier which does not have a corresponding argument or if an argument index refers to an argument that does not exist. So there are two things you need to check in your code: * *Do you have a format specifier without a corresponding argument? *Do you have an argument index which refers to an argument that doesn't exist? You haven't specified any argument indexes in your format string, so it must be the first case - which indeed it is. A: If you are using printf, you need to specify the placeholders as printf parameters along with the format string. In your case you are passing a single string by appending the amount hence the error. System.out.printf("Total value is: $%.2f\n" + totalValue) should be replaced by System.out.printf("Total value is: $%.2f\n", totalValue) A: System.out.printf("Total value is: $%.2f\n", totalValue); // display product -> http://www.java2s.com/Code/JavaAPI/java.lang/Systemoutprintf2ffloatf.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7625233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Network timeouts in Android I am experiencing way too many timeouts in the communication between my app and my server.. My problem is that the server doesn't even get the message. So I guess the problem is somewhere inside my Android code and not the server code. Here is my code: HttpParams params = new BasicHttpParams(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); //configure timeouts HttpConnectionParams.setConnectionTimeout(params, 1000 * 1000); HttpConnectionParams.setSoTimeout(params, 1000 * 1000); //and finally initialize the http client this.mClient = new DefaultHttpClient(manager,params); //init the response handler this.mResponseHandler = new MyResponseHandler(ctx); final HttpPost method = new HttpPost(HttpSender.SERVER_URL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("message", s)); try { method.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Runnable sender = new Runnable(){ @Override public void run() { try { mClient.execute(method, mResponseHandler); } catch (ClientProtocolException e) { Log.v(TAG, "unable to send " + s); e.printStackTrace(); } catch (IOException e) { Log.v(TAG, "unable to send " + s); e.printStackTrace(); } } }; new Thread(sender).start(); Is there something wrong with my code? By the way it doesn't always timeout.. just about 2/3 of the time EDIT : I noticed that when i start the phone it usually works fine (no timeouts) but after a few messages i start getting the timeouts so maybe i am not closing something correctly in my code? EDIT : another thing i have noticed is that if the messages work fine and then i turn my phone (from vertical to horizontal and vice versa) the problems arise again and right after the orientation change i get: 10-03 11:47:46.920: ERROR/[FT]-Server(3563): NetworkStateReceiver :intent: android.net.conn.CONNECTIVITY_CHANGE Thanks for your help! Omri A: well i am not exactly sure what solved it but i think the problem was that i wasn't closing connection and methods anyhow here is my code if any one is interested: public class HttpSender { private ResponseHandler<String> mResponseHandler; private String TAG = "HttpSender"; static final String SERVER_URL = "http://**some ip address**/myServer"; public HttpSender(Context ctx){ //init the response handler this.mResponseHandler = new MyResponseHandler(ctx); } //TODO : see if using postSend is better and dosent cause timeouts? public void send(final String s,final Context ctx, final int type){ Log.v(TAG, "sending message : " + s + "type message of is " + Integer.toString(type)); //for testing Toast.makeText(ctx,"sending \n" + s,Toast.LENGTH_LONG).show(); //done for testing this.postSend(s, ctx, type); } public void postSend(final String s,final Context ctx,final int type){ final HttpPost method = new HttpPost(HttpSender.SERVER_URL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("message", s)); final DefaultHttpClient client = getNewClient(ctx); try { method.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Runnable sender = new Runnable(){ @Override public void run() { try { client.execute(method, mResponseHandler, new BasicHttpContext()); client.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); method.abort(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); method.abort(); Log.v(TAG, "unable to send " + s); e.printStackTrace(); } } } }; new Thread(sender).start(); } private DefaultHttpClient getNewClient(Context ctx) { HttpParams params = new BasicHttpParams(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); //and finally initialize the http client DefaultHttpClient client = new DefaultHttpClient(manager,params); return client; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7625238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: gcc compilation and Make file error I have a directory called "aos" in which i have the results of the make, namely .o file and .a file. My test case file in a directory called "test1" which is under the "aos" directory. I am in the test1 directory which has a file called main.c (this is the file I want to execute). I tried compiling the file by giving the command gcc -Wall -pedantic -I ../gtthreads.c -o main main.c ../gtthreads.a But I get these errors: ../gtthreads.c is not a directory ../gtthreads.a is not a directory What am i doing wrong here? How do I refer to the .a file and .c files which are in "aos" directory? A: The -I and -L switches are used to add directories to the #include and linker search paths respectively. So if you have headers in the parent directory, but include them without relative paths in your code, you can use: -I.. which will make gcc look in the parent directory for headers. If you want to compile main.c, and gtthreads.c from the parent directory into an executable, you can: gcc -Wall -pedantic -I.. ../gthreads.c main.c -o main If you want to compile main.c and link it with the gthreads.a file in the parent directory, just use: gcc -Wall -pedantic -I.. -o main main.c ../gtthreads.a
{ "language": "en", "url": "https://stackoverflow.com/questions/7625247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to do a Proper Escape of this Function? I have a DIV tag generated from jQuery that goes like this: $('#results') .append('<DIV id=' + A.pid + ' onmouseover=function(){google.maps.event.trigger(marker, 'mouseover');};><H3>' + A.name + '</H3></DIV>'); Firebug is giving me an error "missing ) argument after list" as it does not recognise the ) immediately after 'mouseover'. Doing a \'mouseover\' produces a syntax error upon mouseover of the DIV. The syntax error reads: function(){google.maps.event.trigger(marker, and a look at the generated DIV shows: <div id="1" 'mouseover');};="" onmouseover="function(){google.maps.event.trigger(marker,"> Doing a "mouseover" produces a blank document. How do I do a proper escape for this function? UPDATE: This should work: $('#results') .append('<DIV id=' + A.pid + ' onmouseover=\"function(){google.maps.event.trigger(marker, \'mouseover\');};\"><H3>' + A.name + '</H3></DIV>'); I need to put escaped double quotes for the function and escaped single quotes for the argument. A: You are putting data in JS in HTML in JS in HTML. Every level of encapsulation there requires a string escape, otherwise out-of-band characters will cause errors and possibly security holes. The human brain is not good at keeping track of multiple nested levels of string encapsulation. So use jQuery's element creation shortcuts to set attributes on the new div, and the event handling features to add the listener to it, instead of messing around with ugly and unsafe HTML string hacking: var div= $('<div>', {id: A.pid}).append($('<h3>', {text: A.name})); div.mouseover(function() { google.maps.event.trigger(marker, 'mouseover'); }); $('#results').append(div); A: You need to put " around the values of your html attributes. Otherwise the browser thinks the attribute ends at the next whitespace and that is exactly right after the (marker, part. $('#results') .append('<DIV id="' + A.pid + '"' + ' onmouseover="function(){google.maps.event.trigger(marker, \'mouseover\');};"><H3>' + A.name + '</H3></DIV>');
{ "language": "en", "url": "https://stackoverflow.com/questions/7625248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compression and decompression of data using zlib in Nodejs Can someone please explain to me how the zlib library works in Nodejs? I'm fairly new to Nodejs, and I'm not yet sure how to use buffers and streams. My simple scenario is a string variable, and I want to either zip or unzip (deflate or inflate, gzip or gunzip, etc') the string to another string. I.e. (how I would expect it to work) var zlib = require('zlib'); var str = "this is a test string to be zipped"; var zip = zlib.Deflate(str); // zip = [object Object] var packed = zip.toString([encoding?]); // packed = "packedstringdata" var unzipped = zlib.Inflate(packed); // unzipped = [object Object] var newstr = unzipped.toString([again - encoding?]); // newstr = "this is a test string to be zipped"; Thanks for the helps :) A: For anybody stumbling on this in 2016 (and also wondering how to serialize compressed data to a string rather than a file or a buffer) - it looks like zlib (since node 0.11) now provides synchronous versions of its functions that do not require callbacks: var zlib = require('zlib'); var input = "Hellow world"; var deflated = zlib.deflateSync(input).toString('base64'); var inflated = zlib.inflateSync(new Buffer(deflated, 'base64')).toString(); console.log(inflated); Syntax has changed to simply: var inflated = zlib.inflateSync(Buffer.from(deflated, 'base64')).toString() A: broofa's answer is great, and that's exactly how I'd like things to work. For me node insisted on callbacks. This ended up looking like: var zlib = require('zlib'); var input = new Buffer('lorem ipsum dolor sit amet', 'utf8') zlib.deflate(input, function(err, buf) { console.log("in the deflate callback:", buf); zlib.inflate(buf, function(err, buf) { console.log("in the inflate callback:", buf); console.log("to string:", buf.toString("utf8") ); }); }); which gives: in the deflate callback: <Buffer 78 9c cb c9 2f 4a cd 55 c8 2c 28 2e cd 55 48 c9 cf c9 2f 52 28 ce 2c 51 48 cc 4d 2d 01 00 87 15 09 e5> in the inflate callback: <Buffer 6c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74> to string: lorem ipsum dolor sit amet A: Update: Didn't realize there was a new built-in 'zlib' module in node 0.5. My answer below is for the 3rd party node-zlib module. Will update answer for the built-in version momentarily. Update 2: Looks like there may be an issue with the built-in 'zlib'. The sample code in the docs doesn't work for me. The resulting file isn't gunzip'able (fails with "unexpected end of file" for me). Also, the API of that module isn't particularly well-suited for what you're trying to do. It's more for working with streams rather than buffers, whereas the node-zlib module has a simpler API that's easier to use for Buffers. An example of deflating and inflating, using 3rd party node-zlib module: // Load zlib and create a buffer to compress var zlib = require('zlib'); var input = new Buffer('lorem ipsum dolor sit amet', 'utf8') // What's 'input'? //input //<Buffer 6c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74> // Compress it zlib.deflate(input) //<SlowBuffer 78 9c cb c9 2f 4a cd 55 c8 2c 28 2e cd 55 48 c9 cf c9 2f 52 28 ce 2c 51 48 cc 4d 2d 01 00 87 15 09 e5> // Compress it and convert to utf8 string, just for the heck of it zlib.deflate(input).toString('utf8') //'x???/J?U?,(.?UH???/R(?,QH?M-\u0001\u0000?\u0015\t?' // Compress, then uncompress (get back what we started with) zlib.inflate(zlib.deflate(input)) //<SlowBuffer 6c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74> // Again, and convert back to our initial string zlib.inflate(zlib.deflate(input)).toString('utf8') //'lorem ipsum dolor sit amet' A: Here is a non-callback version of the code: var zlib = require('zlib'); var input = new Buffer.from('John Dauphine', 'utf8') var deflated= zlib.deflateSync(input); console.log("Deflated:",deflated.toString("utf-8")); var inflated = zlib.inflateSync(deflated); console.log("Inflated:",inflated.toString("utf-8"))
{ "language": "en", "url": "https://stackoverflow.com/questions/7625251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: Backface culling with Molehill Using Flash 11 RC1 with the new Molehill API, I would like to enable backface culling. The beta documentation is pretty vague, but the example implies Molehill wants front-facing triangles to wind counter-clockwise, which is pretty normal. But when my polygons wind counter-clockwise, I get the exact opposite behavior - in other words, it's as if contrary to its own examples Molehill expects front-facing triangles to wind clockwise. Since the documentation never explicitly states which winding is correct, I am stumped. I don't want to just flip all my triangles around until it looks right before I am 100% on what Molehill actually wants, since that has a fair chance of hiding a fundamental misunderstanding. I am using simple perspective projection (a note regarding .transpose() below: because copyRawDataFrom expects data in column-major order, and I hated the way that looked in code, I decided to just enter it row-major and transpose the matrix afterwards - so sue me :P): var y:Number = 1.0 / Math.tan(pFOV / 2.0); var x:Number = y / pAspectRatio; _projectionMatrix.copyRawDataFrom(new<Number>[ x , 0 , 0 , 0, 0 , y , 0 , 0, 0 , 0 , pFar/(pNear-pFar) , pFar*pNear/(pNear-pFar), 0 , 0 , -1 , 0 ]); _projectionMatrix.transpose(); Any clues? A: You can use Context3D.setCulling to change the backface culling in molehill. See: http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/display3D/Context3D.html#setCulling() Which side is front or back depends on your model input data, so trial and error is really yur best bet here. There are only two options :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7625261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using variables in object property names I have a variable called direction that stores either: left, right. I need to change the affected margin based on that variable. Right now I'm using conditions, is it possible to replace "left" with the output of the variable direction? $("#map").animate({"margin-left": "+=50px"}, 500); A: Not directly, but you can create an object and manipulate it before using it in animate(): var direction = "left"; var property = {}; property[ "margin-"+direction ] = "+=50px"; $("#map").animate( property, 500); A: Use this. Since there's no margin-up or margin-down, you have to "manually" translate it: var dir = "left"; dir = dir == "up" ? "top" : dir == "down" ? "bottom" : dir; var obj = {}; obj["margin-" + dir] = "+=50px"; $("#map").animate(obj, 500); The second line is a legitimate, shorter way to write: if(dir == "up"){ dir = "top"; } else if(dir == "down"){ dir = "bottom"; } else { dir = dir; } A: eval('props = {"margin-' + direction + '": "+=50px"}') $("#map").animate(props, 500);
{ "language": "en", "url": "https://stackoverflow.com/questions/7625262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery as AMD module and optimizing with r.js Allright, he is the thing. I am using curl.js for my AMD loader, but i don't like much of "cram" because it needs to be run on unix and i am developing on Windows. So the r.js adapter for nodeJS from RequireJS library comes in mind, because node has already binary for Windows. Now jQuery in current version (1.6.4) is not valid AMD module (coming in version 1.7) and there is dependencies in jQueryUI components, so i had to fake like this: curl( [js!Core/jquery.js] ) .then( function() { define('jquery', function() { return jQuery; }); }) My application is happy with this. However using r.js (version 0.26.0) fails on this part with following error: Tracing dependencies for: boot function (){return jQuery} node.js:207 throw e; // process.nextTick error, or 'error' event on first tick ^ ReferenceError: jQuery is not defined at eval at <anonymous> (r.js:7468:30) at main (r.js:770:33) at callDefMain (r.js:840:18) This is my app.build.js ({ appDir: '../', baseUrl: 'Scripts/', paths: { 'link': '../../../Lib/@Javascript Libs/curl.js/src/curl/plugin/link.js' }, dir: 'built', optimize: 'none', modules: [ { name: 'boot' } ] }) And here is complete boot.js for reference (coffeescript): require([ 'link!styles/main.css' 'js!Core/jquery.js!order' 'js!Core/underscore.js!order' 'js!Core/backbone.js!order' ]).then -> define 'jquery', -> jQuery .next(['Router/MainRouter']) .then (MainRouter) -> new MainRouter() Backbone.history.navigate('home') unless Backbone.history.start( pushState: false ) Thank you in advance for any hint where the catch can be... A: Correct. RequireJS uses a different syntax on its global requirejs() (aka require()) function. RequireJs also doesn't have the "js!" plugin built-in. You may have to include a path to it in your config. You could also use RequireJS's syntax for non-module javascript files. Also: cram 0.2 will support Windows environments using Rhino. We're writing tests for cram 0.2 and will be releasing it shortly. RequireJS syntax (remove js! prefix and include .js extension): require([ 'link!styles/main.css' 'order!Core/jquery.js' 'order!Core/underscore.js' 'order!Core/backbone.js' ], function (maincss, jQuery, underscore, backbone) { // do something here });
{ "language": "en", "url": "https://stackoverflow.com/questions/7625264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using Jquery to get XML and put into html table I know this has been asked before, but I can't figure out what's wrong, I'm trying to load in a XML file with a list of shows using jQuery so that the shows can be updated in one file, and upload onto multiple pages. To me it seems like I'm doing everything right, but my knowledge jquery is fragile at best. Most of it is just pieced together from answers to others questions. my HTML <aside id="shows"class="aside shadow"> <div class="text" id="table"> <div class="more low"> MORE SHOWS </div> <div class="less"> LESS SHOWS </div> </div> </aside> my Jquery function showData() { $.ajax({ type: "GET", url: "shows.xml", dataType: "xml", success: function getShows(a) { $('#table').append('<h2>SHOWS</h2>'); $('#table').append('<table>'); $(a).find('show').each(function(){ var $show = $(this); var date = $show.find('date').text(); var place = $show.find('place').text(); var location = $show.find('location').text(); var time = $show.find('time').text(); var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr></table>'; $('<table>').append(html); }); } }); } and XML <shows> <show> <date>9/8</date> <place>Toads Place</place> <location>New Haven, CT</location> <time>9PM</time> </show> </shows> This does NOTHING and This looks totally right to me, so I'm super confused. Knowing me, I'm missing a semi colon. >< Thanks!! A: Try to put the exact url... url: "shows.xml", ...maybe the shows.xml isn't in the same folder than the Jquery ajax function A: Can you confirm the ajax call works fine and the success method is called. You can check the ajax call and the response on firebug. If the xml is returned fine, you may want to try below, modified the success method a little e.g. http://jsfiddle.net/Jayendra/2PFxr/ Try - $.ajax({ type: "GET", url: "shows.xml", dataType: "xml", success: function(xml){ $('#table').append('<h2>SHOWS</h2>'); $('#table').append('<table id="show_table">'); $(xml).find('show').each(function(){ var $show = $(this); var date = $show.find('date').text(); var place = $show.find('place').text(); var location = $show.find('location').text(); var time = $show.find('time').text(); var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>'; $('#show_table').append(html); }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7625266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is there any benefits for using ORDBMS instead RDBMS behind JPA Today I reviewed postgreSQL wiki and I found it is a ORDBMS (object-relational database management system), so I want to know is there any benefits for using postgreSql (RDBMS) behind the JPA (hibernate, eclipselink, ....) instead of a RDBMS (Mysql, ...) for performance issues or not? As you know JPA use ORM and use JQL (java query language) Regards A: I would say no. JPA is targeted at RDBMSs, and doesn't use the additional capabilities offered by ORDBMSs. Now, PostgreSQL is also a very good RDBMS (you're not forced to use its object-oriented features, and my guess would be that most of its users don't), and you may use it with JPA without problem. A: JPA is the translator between "thinking in objects" (Java) and "thinking in relations" (SQL). Therefore a JPA implementation will always speak to the DB in terms of relations. "Object Relational" stuff is ignored here. Ignoring JPA and talking directly to the DB in "ORDBMS" speak won't buy you performance benefits in the most common cases, because ORDBMS are still RDBMS with some glue logic to look a little bit object-stylish. The data is stored in relations, all access paths are the same as pure relational access path. If you really want to see performance benefits by switching not only the database product but the database technology (or philosophy) you should look at real Object Databases or even NoSQL. A: Object-Relational data is defined as structured data, which is user defined types in the database. OR data types include: * *Structs - structured types *Arrays - array types These types are defined differently in each database, in Oracle they are OBJECT types, VARRAY types, and NESTED TABLE, and REF types. JDBC standardizes access to OR data types using the Struct, Array and Ref interfaces. With OR data-types you can have more complex database schemas, such as a TABLE of Employee_Type that has a Varray of Phone_Types and a Ref to it manager. JPA does not have any direct support for mapping OR data-types, but some providers do. EclipseLink has support for mapping OR data-types including, Structs, Ref, and Arrays. Custom mappings and annotations are used to map these, but the runtime JPA API is the same. I would not normally recommend usage of OR data-types, as they are less standard than traditional relational tables, and do not give much benefit. Some database defined OR data-types, such as spatial data-types do offer advantages as they have integrated database support. See, http://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Structured_Object-Relational_Data_Types
{ "language": "en", "url": "https://stackoverflow.com/questions/7625267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Copy Directory Function I'm working on a Minecraft Server Dashboard, and one of it's functions is to backup and restore your world (a directory). I already have a function (see below), but, as you can probably see, it's pretty bad code. Anyone know of a better, cleaner function? function backupOrRestoreWorld($source,$target){ foreach(glob($target.'*.*')as$v){ unlink($v); } if(is_dir($source)){ @mkdir($target); $d=dir($source); while(FALSE!==($entry=$d->read())){ if($entry=='.'||$entry=='..'){ continue; } $Entry=$source.'/'.$entry; if(is_dir($Entry)){ backupOrRestoreWorld($Entry,$target.'/'.$entry); continue; } copy($Entry,$target.'/'.$entry); } $d->close(); } else{ copy($source,$target); } if($source == "server/world"){ return "World backed up."; } else { return "World restored from backup."; } } A: I wouldn't do this in PHP. Just use system("cp -a $source $dest"). (And make sure the user can not in any way control the contents of $source and $dest or you will be hacked.) A: I would create more functions out of it, each one doing a distinctive job, probably encapsulated into a class, like * *empty_directory *copy_directory You can still maintain your single function then making use of the subroutines / objects to provide a façade into your application, for example dealing with exceptions for error handling and such. Next to that you're having not really bad code. It's a recursive function for copying the data which might stress the file-system a bit - which presumably can be neglected. If you move the decent functionality into units of it's own, you can change that over time if you run into actual problems. But the first benefit would be to make use of exceptions in subroutines I think: function backupOrRestoreWorld($source, $target) { empty_directory($target); copy_directory($source, $target); if($source == "server/world"){ return "World backed up."; } else { return "World restored from backup."; } } function empty_directory($path) { $path = rtrim($path, '/'); if (!is_dir($path)) { throw new InvalidArgumentException(sprintf('Not a directory ("%s").', $path)); } if (!is_writable($path)) { throw new InvalidArgumentException(sprintf('Directory ("%s") is not a writeable.', $path)); } $paths = glob($path.'/*.*'); if (false === $paths) { throw new Exception(sprintf('Unable to get path list on path "%s" (glob failed).', $path)); } foreach ($paths as $v) { unlink($v); } } function copy_directory($source, $target) { $source = rtrim($source, '/'); $target = rtrim($target, '/'); if (!is_dir($source)) { throw new InvalidArgumentException(sprintf('Source ("%s") is not a valid directory.', $source)); } if (!is_readable($source)) { throw new InvalidArgumentException(sprintf('Source ("%s") is not readable.', $source)); } if (!is_dir($target)) $r = mkdir($target); if (!is_dir($target)) { throw new InvalidArgumentException(sprintf('Target ("%s") is not a valid directory.', $target)); } if (!is_writable($target)) { throw new InvalidArgumentException(sprintf('Target ("%s") is not a writeable.', $target)); } $dirs = array(''); while(count($dirs)) { $dir = array_shift($dirs) $base = $source.'/'.$dir; $d = dir($base); if (!$d) { throw new Exception(sprintf('Unable to open directory "%s".', $base)); } while(false !== ($entry = $d->read())) { // skip self and parent directories if (in_array($entry, array('.', '..')) { continue; } // put subdirectories on stack if (is_dir($base.'/'.$entry)) { $dirs[] = $dir.'/'.$entry; continue; } // copy file $from = $base.'/'.$entry; $to = $target.'/'.$dir.'/'.$entry; $result = copy($from, $to); if (!$result) { throw new Exception(sprintf('Failed to copy file (from "%s" to "%s").', $from, $to); } } $d->close(); } } This example is basically introducing two functions, one to empty a directory and another one to copy the contents of one directory to another. Both functions do throw exceptions now with more or less useful descriptions what happens. I tried to reveal errors early, that's by checking input parameters and by performing some additional tests. The empty_directory function might be a bit short. I don't know for example, if there a subdirectories and those aren't empty, if unlink would work. I leave this for an exercise for you. The copy_directory function is working non-recursive. This is done by providing a stack of directories to process. In case there is a subdirectory, the directory is put on the stack and processed after the all files of the current directory are copied. This helps to prevent switching directories too often and is normally faster. But as you can see, it's very similar to your code. So these functions concentrate on the file-system work. As it's clear what they do and for what they are, you can concentrate inside your function on the main work, like the logic to determine in which direction the copying has been done. As the helper functions now throw exceptions, you can catch those, too. Additionally you could verify that $source and $target actually contain values that you explicitly allow. For example, you don't want to have .. or / inside of them probably, but just characters from a-z. This will help you as well to find other causes of error, like overwriting attempts etc.: function backupOrRestoreWorld($source, $target) { $basePath = 'path/to/server'; $world = 'world'; $pattern = '[a-z]+'; try { if (!preg_match("/^{$pattern}\$/", $source)) { throw new InvalidArgumentException('Invalid source path.'); } if (!preg_match("/^{$pattern}\$/", $target)) { throw new InvalidArgumentException('Invalid target path.'); } if ($source === $target) { throw new InvalidArgumentException('Can not backup or restore to itself.'); } $targetPath = $basePath.'/'.$target; if (is_dir($targetPath)) empty_directory($targetPath); copy_directory($basePath.'/'.$source, $targetPath); if($source === $world) { return "World backed up."; } else { return "World restored from backup."; } } catch(Exception $e) { return 'World not backed up. Error: '.$e->getMessage(); } } In the example backupOrRestoreWorld still acts as the original function but now returns an error message and more specifically checks for error conditions in it's own logic. It's a bit borked because it converts exceptions to the return value, which are two sorts of error handling (which you might not want), but it's a compromise to interface with your existing code (the façade) while covering itself's input validation with exceptions. Additionally, the values it works on (parameters) are specified at the top of the function instead of later on in the function's code. Hope this helps. What's left? * *The copy_directory function could check if a directory already exists, that it is empty. Otherwise it would not truly copy a world, but mix two worlds. *The empty_directory function should be properly checked if it actually does the job to empty a directory in a fail-safe manner, especially while dealing with subdirectories. *You can make up your mind about a general way of doing error handling inside your application so that you can more easily deal with errors inside your application. *You can think about creating objects to deal with storing and retrieving worlds so things can be extended easily in the long run. A: .1. Using @ operator will lead you to trouble. NEVER use it. If there is a possibility of unexisting file - CHECK IT first! if (!file_exists($target)) mkdir($target); .2. I am quite surprised why you're using glob in the first part and don't use it in the second. .3. Your "clean target directory code first" code won't clean subdirectories. A: I used, from here: http://codestips.com/php-copy-directory-from-source-to-destination/ <? function copy_directory( $source, $destination ) { if ( is_dir( $source ) ) { mkdir( $destination ); $directory = dir( $source ); while ( FALSE !== ( $readdirectory = $directory->read() ) ) { if ( $readdirectory == '.' || $readdirectory == '..' ) { continue; } $PathDir = $source . '/' . $readdirectory; if ( is_dir( $PathDir ) ) { copy_directory( $PathDir, $destination . '/' . $readdirectory ); continue; } copy( $PathDir, $destination . '/' . $readdirectory ); } $directory->close(); }else { copy( $source, $destination ); } } ?> Works so long as you don't try to copy a directory inside itself and go into an infinite loop.. A: I have some recursive copying code that follows, but first a few thoughts. Conversely to what some others think - I believe the file system functions are about the only place where the @ operator makes sense. It allows you to raise your own exceptions rather than having to handle the functions built in warnings. With all file system calls you should check for failure conditions. I would not do something that was suggested to you: if (!file_exists($target)) mkdir($target); (which assumes that mkdir will succeed). Always check for failure (the file_exists check does not match the complete set of possibilities where mkdir would fail). (e.g broken sym links, inaccessible safe mode files). You must always decide how you will handle exceptions, and what are the initial conditions required for your function to succeed. I treat any operation that fails with the file system as an exception which should be caught and dealt with. Here is the recursive copying code that I use: /** Copy file(s) recursively from source to destination. * \param from \string The source of the file(s) to copy. * \param to \string The desitination to copy the file(s) into. * \param mode \int Octal integer to specify the permissions. */ public function copy($from, $to, $mode=0777) { if (is_dir($from)) { // Recursively copy the directory. $rDir = new RecursiveDirectoryIterator( $from, FilesystemIterator::SKIP_DOTS); $rIt = new RecursiveIteratorIterator( $rDir, RecursiveIteratorIterator::SELF_FIRST); // Make the directory - recursively creating the path required. if (!@mkdir($to, $mode, true)) { throw new Exception( __METHOD__ . 'Unable to make destination directory: ' . var_export($to, true)); } foreach ($rIt as $file) { $src = $file->getPathname(); $dest = $to . $rIt->getInnerIterator()->getSubPathname(); if (is_dir($src)) { if (!@mkdir($dest, $mode)) { throw new Exception( __METHOD__ . 'From: ' . $from . ' To: ' . $to . ' Copying subdirectory from:' . $src . ' to: ' . $dest); } } else if (!@copy($src, $dest)) { throw new Exception( __METHOD__ . 'From: ' . $from . ' To: ' . $to . ' Copying file from: ' . $src . ' to: ' . $dest); } } } } else { if (!@copy($from, $to)) { throw new Exception( __METHOD__ . 'Copying single file from: ' . $from . ' to: ' . $to); } } } A: Before copy all files, you must to make "/destination" permission to be 0777 $dst = '/destination'; // path for past $src = '/source'; // path for copy $files = glob($src.'/*.*'); foreach($files as $file){ $file_to_go = str_replace($src, $dst, $file); copy($file, $file_to_go); } $dir_array = array(); $dir_array[] = $src; while ($dir_array != null) { $newDir = array (); foreach ($dir_array as $d) { $results = scandir($d); foreach ($results as $r) { if ($r == '.' or $r == '..') continue; if (is_file($d . '/' . $r)) { } else { $path = $d.'/'.$r; $newDir[] = $path; $new = str_replace($src, $dst, $path); mkdir($new, 0777, true); $files = glob($path.'/*.*'); foreach($files as $file) { $file_to_go = str_replace($src, $dst, $file); copy($file, $file_to_go); } continue; } } } $dir_array = $newDir; } all done. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CakePHP: How can redirect to a new web page with html anchor ... ? The comment form => echo $this->Form->create('Comment',array('url'=>array('controller' => 'comments', 'action' =>'add', $listposts['Post']['id']) ) ); echo $this->Form->input('post_id',array('type'=>'hidden','style'=>'width:30%','value'=>$listposts['Post']['id'])); echo $this->Form->input('name',array('style'=>'width:30%')); echo $this->Form->input('email',array('style'=>'width:30%')); echo $this->Form->input('body',array('rows'=>'5')); echo $this->Form->end('Comment'); In the body field of the comment form if i type like this => <a href="www.google.com"> google </a> I get a link "google" in that web page but if i click that link it doesn't redirect to www.google.com. Why doesn't redirect ? If i hover that link i see => http://www.mysite.com/posts/view/www.google.com How can i redirect to www.google.com clicking that link ? A: You need to make the url "http://www.google.com". Because there's no protocol specifier it interprets the href field as a relative link instead of a link to another domain. A: You can use html help of Cakephp: <?php echo $this->Html->link('google', 'http://www.google.com'); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7625276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why variadic functions require at least two arguments? I'm trying to plug a hole in my knowledge. Why variadic functions require at least two arguments? Mostly from C's main function having argc as argument count and then argv as array of arrays of chars? Also Objective-C's Cocoa has NSString methods that require format as first argument and afterwards an array of arguments ([NSString stringWithFormat:@"%@", foo]). Why is it impossible to create a variadic function accepting only a list of arguments? A: argc/argv stuff is not really variadic. Variadic functions (such as printf()) use arguments put on the stack, and don't require at least 2 arguments, but 1. You have void foo(char const * fmt, ...) and usually fmt gives a clue about the number of arguments. That's minimum 1 argument (fmt). A: C has very limited reflection abilities so you must have some way to indicate what it is that the variable arguments contain - either specifying the number of arguments or the type of them (or both), and that is the logic behind having one more parameter. It is required by the ISO C standard so you can't omit it. If feel you don't need any extra parameters because the number and type of the arguments is always constant then there is no need for variable arguments in the first place. You could of course design other ways to encode the number / type information inside the variable arguments such as a sentinel value. If you want to do this, you can just supply a dummy value for the first argument and not use it in the method body. And just to be pedantic about your title, variadic functions only require one argument (not two). It's perfectly valid to make a call to a variadic function without providing any optional arguments: printf("Hello world"); A: I think, that the reason is the following: in the macro va_start(list, param); you specify the last fixed argument - it is needed to determine the address of the beginning of the variable arguments list on the stack. A: How would you then know if the user provided any arguments? There has to be some information to indicate this, and C in general wasn't designed to do behind-your-back data manipulation. So anything you need, it makes you pass explicitly. A: I'm sure if you really wanted to you could try to enforce some scheme whereby the variadic function takes only a certain type of parameter (a list of ints for example) - and then you fill some global variable indicating how many ints you had passed. Your two examples are not variadic functions. They are functions with two arguments, but they also highlight a similar issue. How can you know the size of a C array without additional information? You can either pass the size of the array, or you describe a scheme with some sentinel value demarcating the end of the array (i.e. '\0' for a C string). In both the variadic case and the array case you have the same problem, how can you know how much data you have legitimate access to? If you don't know this with the array case, you will go out of bounds. If you don't know this with the variadic case you will call va_arg too many times, or with the wrong type. To turn the question around, how would you be able to implement a function taking a variable number of arguments without passing the extra information?
{ "language": "en", "url": "https://stackoverflow.com/questions/7625284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can I know a radiosity linear system can be implemented using the iterative method? That is, I want to check if the linear system derived from a radiosity problem is convergent. I also want to know is there any book/paper giving a proof on the convergence of the radiosity problem? Thanks. A: I assume you're solving B = (I - rho*F) B (based on the wikipedia article) Gauss-Seidel and Jacobi iteration methods are both guaranteed to converge if the matrix is diagonally dominant (Gauss-Seidel is also guaranteed to converge if the matrix is symmetric and positive definite). The rows of the F matrix (view factors) sum to 1, so if rho (reflectivity) is < 1, which physically it should be, the matrix will be diagonally dominant.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to create a fade-in/fade-out effect using CSS 3 only? Is there a way to create a fade-in/fade-out effect on mouse over/out respectively that only uses CSS 3? If there is, would you say that it is a good way to implement such an effect with CSS only or not? To me, it seems like a presentation only issue so I'm not sure why JavaScript should be involved? A: Are you looking for something like this: http://jsfiddle.net/hRuR9/2/ ? It's pretty simple... .box{ opacity: 0.0; -webkit-transition: 0.5s all; -moz-transition: 0.5s all; } .box:hover{ opacity: 1.0; } As for whether using it or not is a good idea, it depends on your target audience and which browsers you expect them to use or want to support. Recent versions of Safari, Chrome, and Firefox (and I believe Opera) support it. No idea about recent versions of IE, but you can pretty much forget about the older ones.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why BOOLEAN of winapi uses 1 for true and 2 for false? I didn't know. just saw it in my debug window a BOOLEAN from STORAGE_DEVICE_DESCRIPTOR was resolving to 2 instead of of 1. I got panicked thinking 2 means false. then I realized its 1 for true. But why this kind of odd design ? Or I am doing something wrong in my side ? never heard of anything like multibyte boolean. (BTW I am using MinGW and Qt Creator IDE's Debugger) A: There are historical reasons for why many types of boolean exist which is discussed here. Essentially any non-zero values are true, and zero is false. This means you shouldn't do comparisons like so: if( x == TRUE ) But instead: if( x )
{ "language": "en", "url": "https://stackoverflow.com/questions/7625299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do they want an 'unsigned char*' and not just a normal string or 'char*' EDIT: After taking adivce I have rearranged the parameters & types. But the application crashes when I call the digest() function now? Any ideas whats going wrong? const std::string message = "to be encrypted"; unsigned char* hashMessage; SHA256::getInstance()->digest( message, hashMessage ); // crash occurs here, what am I doing wrong? printf("AFTER: n"); //, hashMessage); // line never reached I am using an open source implementation of the SHA256 algorithm in C++. My problem is understanding how to pass a unsigned char* version of my string so it can be hashed? This is the function that takes a unsigned char* version of my string: void SHA256::digest(const std::string &buf, unsigned char *dig) { init(); update(reinterpret_cast<const unsigned char *>(buf.c_str()), static_cast<unsigned int>(buf.length())); final(); digest(dig); } How can I convert my string(which I want hashed) to an unsigned char*? The following code I have made causes a runtime error when I go to print out the string contents: const std::string hashOutput; char message[] = "to be encrypted"; printf("BEFORE: %s bb\n", hashOutput.c_str()); SHA256::getInstance()->digest( hashOutput, reinterpret_cast<unsigned char *>(message) ); printf("AFTER: %s\n", hashOutput.c_str()); // CRASH occurs here PS: I have been looking at many implementations of SHA256 & they all take an unsigned char* as the message to be hashed. Why do they do that? Why not a char* or a string instead? A: You have the parameters around the wrong way. Buf is the input (data to be hashed) and dig is the output digest ( the hash). Furthermore, a hash is binary data. You will have to convert said binary data into some string representation prior to printing it to screen. Normally, people choose to use a hexadecimal string for this. A: The reason that unsigned char is used is that it has guaranteed behaviours under bitwise operations, shifts, and overflow. char, (when it corresponds to signed char) does not give any of these guarantees, and so is far less useable for operations intended to act directly on the underlying bits in a string. The answer to the question: "why does it crash?" is "you got lucky!". Your code has undefined behaviour. In short, you are writing through a pointer hashMessage that has never been initialised to point to any memory. A short investigation of the source code for the library that you are using reveals that it requires the digest pointer to point to a block of valid memory that is at least SHA256_DIGEST_SIZE chars long. To fix this problem, all that you need to do is to make sure that the pointer that you pass in as the digest argument (hashMessage) is properly initialised, and points to a block of memory of sufficient size. In code: const std::string message("to be encrypted"); unsigned char hashMessage[SHA256_DIGEST_SIZE]; SHA256::getInstance()->digest( message, hashMessage ); //hashMessage should now contain the hash of message. A: I don't know how a SHA256 hash is produced but maybe it involves some sort of arithmetic that needs to be done on a unsigned data type. Why does it matter? Get a char* from your string object by calling the c_str() method then cast to unsigned char*.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HTML Page Title in Excel VBA Given an url, how can I get the title of the html page in VBA in Excel? For example suppose I have three urls like : * *http://url1.com/somepage.html *http://url2.com/page.html *http://url3.com/page.html Now I need to get the title of these html pages in another column. How do I do it? A: Remou's answer was VERY helpful for me, but it caused a problem: It doesn't close the Internet Explorer process, so since I needed to run this dozens of times I ended up with too many IEs open, and my computer couldn't handle this. So just add wb.Quit and everything will be fine. This is the code that works for me: Function GetTitleFromURL(sURL As String) Dim wb As Object Dim doc As Object Set wb = CreateObject("InternetExplorer.Application") wb.Navigate sURL While wb.Busy DoEvents Wend GetTitleFromURL = wb.Document.Title wb.Quit Set wb = Nothing End Function A: I am not sure what you mean by title, but here is an idea: Dim wb As Object Dim doc As Object Dim sURL As String Set wb = CreateObject("InternetExplorer.Application") sURL = "http://lessthandot.com" wb.Navigate sURL While wb.Busy DoEvents Wend ''HTML Document Set doc = wb.document ''Title Debug.Print doc.Title Set wb = Nothing A: if you use Selenium : Sub Get_Title() Dim driver As New WebDriver debug.print driver.Title End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7625316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there any API which can detect GPS location is changed in the iPhone native application? I want to show gps coordinates in the Label, is there any default API which can observe/detect that GPS location is changed,so we that I should be able to take and show new GPS location in the label. A: You should take a look the Location Awareness Programming Guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cant compare two files. while loopsdont work EDIT: i have to files, FileOne and FileTwo, which in every line there is a word or more. and i want to compare these two file, and see if every line of fileOne is exact the same or piece of a line of FileTwo. I made the code below with your ideas, but i my result is to small that means that it is not ckecking all the lines of fileOne. The code below, isn't going to the next object of it1? int index1 = 0; int index2 = 0; ArrayList <String> File1 = File2List(FileOne); Iterator it1 = File1.listIterator(); ArrayList <String> File2 = File2List(FileTwo); Iterator it2 = File2.listIterator(); while (it1.hasNext()) { String outer = it1.next().toString(); while (it2.hasNext()) { String inner = it2.next().toString(); index1 = outer.indexOf(inner); if(index1 != -1) { //Or compareIgnoreCase index2++; it1.next(); break; } } it1.next(); } System.out.println("Result: "+ index2); A: First (before offering the solution to the actual issue): index1 = check.indexOf(toCheck); if(index1 != -1){ index2++; break; //mass1; } by if(check.equals(checkTo)) { //Or equalsIgnoreCase index2++; break; } Because the line Same start and Same start, diff end are certainly not the same. Actual issue: You're reading the whole contents of file2 at each line of file1. Possible solution * *Read the contents of file1 (line by line), and store it in an ArrayList File1 *Read the contents of file2 (line by line), and store it in another ArrayList File2. *Compare the size of these ArrayLists with each other *If the're not equal, return (the files are definitely different). *Else, loop through each element of ArrayList File1, and compare using the previously described function to ArrayList File2. A: You are one line from file one with every line from file two. That does not work. You have to get the next lines from file one in the second loop. Example: while (it1.hasNext()) { String outer = it1.next().toString(); if(!it2.hasNext()) { // FALSE! } else { String inner = it2.next().toString(); if(!inner.compare(outer)) { //Or compareIgnoreCase // FALSE } } } if(it2.hasNext()) { // FALSE } A: Is that what you want? package so7625322; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class FindWords { private static List<String> loadLines(String fname) throws IOException { InputStream is = new FileInputStream(fname); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> lines = new ArrayList<String>(); String line; while ((line = rd.readLine()) != null) { lines.add(line); } return lines; } finally { is.close(); } } private boolean contains(Iterable<String> haystack, String needle) { for (String s : haystack) { if (s.contains(needle)) { return true; } } return false; } public boolean containsAll() throws IOException { List<String> words = loadLines("./NetBeansProjects/StemmerListComp/StemmedUnTunedQueries.txt"); List<String> tocheck = loadLines("words-to-check"); for (String s : tocheck) { if (!contains(words, s)) { return false; } } return true; } } Some remarks: * *I have split the task into several small tasks, so that the main method containsAll looks as similar to your requirement as possible. *Using the loadLines helper method the code also becomes simpler, since you don't need to be concerned about closing the files in the containsAll method anymore. A: This method will do the work. private bool IsIdentical(string filePath1, string filePath2) { int file1Byte, file2Byte; FileStream fileStream1, fileStream2; //Open a stream to both files fileStream1 = new FileStream(filePath1, FileMode.Open); fileStream2 = new FileStream(filePath2, FileMode.Open); // Check the file sizes to determine if the files are identical. if (fileStream1.Length != fileStream2.Length) { fileStream1.Close(); fileStream2.Close(); return false; } //Read one byte from each file and compare them until either a non-matching //set of bytes is found or until the end of the file. do { // Read one byte from each file. file1Byte = fileStream1.ReadByte(); file2Byte = fileStream2.ReadByte(); } while ((file1Byte == file2Byte) && (file1Byte != -1)); fileStream1.Close(); fileStream2.Close(); return ((file1Byte - file2Byte) == 0); } A: It appears that you not only want to check is all the line sin file1 against file2 but also determine the line where they differ. List<String> file1 = File2List(fileOne); List<String> file2 = File2List(fileTwo); for(int i=0;i<file1.size() && i<file2.size();i++) if(!file2.get(i).contains(file1.get(i))) { System.out.println("mismatch at line "+i); return; } if (file1.size()<file2.size()) { System.out.println("file1 is shorter than file2"); return; } if (file2.size()<file1.size()) { System.out.println("file2 is shorter than file1"); return; } System.out.println("no mismatches found");
{ "language": "en", "url": "https://stackoverflow.com/questions/7625322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) I'm using XAMPP on Windows 7. and when I try to open a login.php of current project I get this error Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) in E:\xampplite\htdocs\newfule\mcp\clientlist.php on line 19 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in E:\xampplite\htdocs\newfule\mcp\clientlist.php on line 19 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in E:\xampplite\htdocs\newfule\mcp\clientlist.php on line 21 Sorry No entries for the Records of Student ...... this is config file <?php $link = mysql_connect('127.0.0.1', 'root', ''); if (!$link) { die('Not connected : ' . mysql_error()); } // make foo the current db $db_selected = mysql_select_db('fueldb', $link); if (!$db_selected) { die ('Can\'t use foo : ' . mysql_error()); } ?> This is one warning is at phpmyadmin A: Using phpmyadmin you cannot have a user with an empty password which instead is allowed in mysql. A: The error doesn't seem to be in the config file. ODBC is the default user when none is specified, so since everything seems good in the config file it appears it's either not being included before the call to mysql_query or that the mysql_query call itself is being done wrong. Without more code there's no real way to know. A: i think you don't have problem with config file.i think problem with adding a config file or including a config file.i suggest u to check link that include or add config file. A: Use localhost instead of 127.0.0.1 127.0.0.1 uses TCP instead of unix sockets Also stop using mysql for PHP. It has been removed. Use mysqli or pdo A: Your error and your config file are not appling the same users Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) Error about query the user "ODBC" from host "localhost" mysql_connect('127.0.0.1', 'root', ''); Connecting with the user 'root' to '127.0.0.1' ¿Is your configuration applied? It seems that "clientlist.php" is using other $link resource Also take in cosideration that the users in mysql user table contains by default the host reference. This meants that root@localhost could be correct to access without password but [email protected] could be denied. You could view in the user table of the "mysql" database the registered users, if they have password and the host (or hosts) allowed. Each user could appear more than once if the host is different. Also is possible to use the character "%" in the host to allow all hosts or a subnet (but i dont recommend this for production environments) In all cases is recommended to create a proper user and assing privileges to the desired database to operate it. A: try to given access table to user : grant all On [tabelName] to [userName]; example grant all On mysql.* to root;
{ "language": "en", "url": "https://stackoverflow.com/questions/7625324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you use a variable as an index when slicing strings in Python? I've been trying to slice two characters out of a string using a loop, but instead of grabbing two characters, it only grabs one. I've tried: input[i:i+1] and input[i:(i+1)] but neither seems to work. How do I use a variable for slicing? The full routine: def StringTo2ByteList(input): # converts data string to a byte list, written for ascii input only rlist = [] for i in range(0, len(input), 2): rlist.append(input[i:(i+1)]) return rlist A: The slice values aren't the start and end characters of the slice, they're the start and end points. If you want to slice two elements then your stop must be 2 greater than your start. input[i:i+2] A: A nice way to remember slice indexing is to think of the numbers as labeling the positions between the elements. So for example to slice ba you would use fruit[0:2]. When thinking of it this way, things no longer seem counter-intuitive, and you can easily avoid making off-by-one errors in your code. A: Reasoning on the basis of the in-between positions works when we do a left-to-right iteration: li = [10, 20, 55, 65, 75, 120, 1000] print 'forward slicing li[2:5] ->',li[2:5] # prints forward slicing li[2:5] -> [55, 65, 75] because pos 2 is between 20 / 55 and pos 5 is between 75 / 120 . But it doesn't work when we do right-to-left iteration: li = [10, 20, 55, 65, 75, 120, 1000] print li print 'reverse slicing li[5:2:-1] ->',li[5:2:-1] # prints reverse slicing li[5:2:-1] -> [120, 75, 65] We must think of li[ 5 : 2 : -1 ] as : from element li[5] (which is 120) as far as uncomprised element li[2] (which is 55) that is to say from element li[5] (which is 120) only as far as li[3] included (which is 65) . . That makes dangerous reverse slicing from the very end: li = [10, 20, 55, 65, 75, 120, 1000] print li[ -1 : 2 : -1 ] # prints [1000, 120, 75, 65] not [120, 75, 65, 55] # the same as: print li[ None : 2 : -1 ] # prints [1000, 120, 75, 65] print li[ : 2 : -1 ] # prints [1000, 120, 75, 65] and li = [10, 20, 55, 65, 75, 120, 1000] print li[ 4 : 0 : -1] # prints [75, 65, 55, 20] , not [65, 55, 20, 10] . In case of difficulty to think like that, a manner to prevent errors is to write print list(reversed(li[2:5])) # prints [75, 65, 55] print list(reversed(li[2:-1])) # prints [120, 75, 65, 55] print list(reversed(li[0:4])) # prints [65, 55, 20, 10] . Note that the only way to obtain a reverse slicing as far as the first element INCLUDED is print li[ 4 : : -1] that stands for print li[ 4 : None : -1]
{ "language": "en", "url": "https://stackoverflow.com/questions/7625326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Algorithm - find the minimal subtraction between sum of two arrays I am hunting job now and doing many algorithm exercises. Here is my problem: Given two arrays: a and b with same length, the subject is to make |sum(a)-sum(b)| minimal, by swapping elements between a and b. Here is my though: assume we swap a[i] and b[j], set Delt = sum(a) - sum(b), x = a[i]-b[j] then Delt2 = sum(a)-a[i]+b[j] - (sum(b)-b[j]+a[i]) = Delt - 2*x, then the change = |Delt| - |Delt2|, which is proportional to |Delt|^2 - |Delt2|^2 = 4*x*(Delt-x), Based on the thought above I got the following code: Delt = sum(a) - sum(b); done = false; while(!done) { done = true; for i = [0, n) { for j = [0,n) { x = a[i]-b[j]; change = x*(Delt-x); if(change >0) { swap(a[i], b[j]); Delt = Delt - 2*x; done = false; } } } } However, does anybody have a much better solution ? If you got, please tell me and I would be very grateful of you! A: This problem is basically the optimization problem for Partition Problem with an extra constraint of equal parts. I'll prove that adding this constraint doesn't make the problem easier. NP-Hardness proof: Assume there was an algorithm A that solves this problem in polynomial time, we can solve the Partition-Problem in polynomial time. Partition(S): for i in range(|S|): S += {0} result <- A(S\2,S\2) //arbitrary split S into 2 parts if result is a partition: //simple to check, since partition is NP. return true. return false //no partition Correctness: If there is a partition denote as (S1,S2) [assume S2 has more elements], on iteration |S2|-|S1| [i.e. when adding |S2|-|S1| zeros]. The input to A will contatin enough zeros so we can return two equal length arrays: S2,S1+{0,0,...,0}, which will be a partition to S, and the algorithm will yield true. If the algorithm yields true, and iteration k, we had two arrays: S2,S1, with same number of elements, and equal values. by removing k zeros from the arrays, we get a partition to the original S, so S had a partition. Polynomial: assume A takes P(n) time, the algorithm we produced will take n*P(n) time, which is also polynomial. Conclusion: If this problem is solveable in polynomial time, so does the Partion-Problem, and thus P=NP. based on this: this problem is NP-Hard. Because this problem is NP-Hard, for an exact solution you will probably need an exponential algorith. One of those is simple backtracking [I leave it as an exercise to the reader to implement a backtracking solution] EDIT: as mentioned by @jpalecek: by simply creating a reduction: S->S+(0,0,...,0) [k times 0], one can directly prove NP-Hardness by reduction. polynomial is trivial and correctness is very similar to the above partion's correctness proof: [if there is a partition, adding 'balancing' zeros is possible; the other direction is simply trimming those zeros] A: Just a comment. Through all this swapping you can basically arrange the contents of both arrays as you like. So it is unimportant in which array the values are at start. Can't do it in my head but I'm pretty sure there is a constructive solution. I think if you sort them first and then deal them according to some rule. Something along the lines If value > 0 and if sum(a)>sum(b) then insert to a else into b
{ "language": "en", "url": "https://stackoverflow.com/questions/7625329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Encrypting the user credentials using SHA1 algorithm I am creating a blackberry application which sends the request to the server. So authentication of the user is required. So for doing this i want to encrypt UserID and password using SHA1 in blackberry. The encrypted data which is made using SHA1 algorithm on UserID and password is then passed to the server. My problem is how do i implement this. Can someone give the sample code for implementing this in blackberry. A: SHA1 is not an encryption algorithm. It is hash-function. http://en.wikipedia.org/wiki/SHA1 If you are talking about Basic Authentication, then you need to use Base64 algorithm to hash username and password. Here is discussed topic about this issue: HTTP authentication in J2ME A: add this class public class Sha1 { private static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } public static String SHA1(String text) { SHA1Digest sha1Digest = new SHA1Digest(); sha1Digest.update(text.getBytes(), 0, text.length()); byte[] hashValBytes = new byte[sha1Digest.getDigestLength()]; hashValBytes = sha1Digest.getDigest(); return convertToHex(hashValBytes); } } then on your code , Write sha1 = Sha1.SHA1(email);
{ "language": "en", "url": "https://stackoverflow.com/questions/7625342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the list of options of a linux kernel module? For example, there is a max_loop option for the loop module. Generally, how can I know what options are supported by a kernel module? Or, where can I find the list, should I dive into the source codes? A: Documentation/kernel-parameters.txt in the kernel documentation will give you many of them, and any in modules can be gleaned from modinfo. # modinfo radeon ... parm: no_wb:Disable AGP writeback for scratch registers (int) parm: modeset:Disable/Enable modesetting (int) parm: dynclks:Disable/Enable dynamic clocks (int) parm: r4xx_atom:Enable ATOMBIOS modesetting for R4xx (int) parm: vramlimit:Restrict VRAM for testing (int) parm: agpmode:AGP Mode (-1 == PCI) (int) parm: gartsize:Size of PCIE/IGP gart to setup in megabytes (32,64, etc) (int) parm: benchmark:Run benchmark (int) parm: test:Run tests (int) parm: connector_table:Force connector table (int) parm: tv:TV enable (0 = disable) (int) parm: new_pll:Select new PLL code (int) parm: audio:Audio enable (0 = disable) (int) parm: disp_priority:Display Priority (0 = auto, 1 = normal, 2 = high) (int) parm: hw_i2c:hw i2c engine enable (0 = disable) (int) parm: pm:enable power management (0 = disable) (int)
{ "language": "en", "url": "https://stackoverflow.com/questions/7625350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to deal with uncompilable source code in web app projects that need to be deployed for testing? I have a web app project under development using Maven 2 that I want to deploy on server to be able to view the webpages for testing purposes while developing. Howver there is also a lot of uncompilable code in the project because of which I am getting Compilation failure errors while trying to build & package the project as war for deployment. How can I deploy such project with uncompileable classes, or better say, how do I view my webpages while keeping aside the uncompilable java classes in the source packages of the project ? Using Maven 2 for a JSF2.0(facelets) project with Netbeans 6.9 & glassfish 3.01. A: Check compiler plugin and compile mojo which is called during at compile phase. Default value for failOnError is true. You should make it false. http://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#failOnError <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <failOnError>false</failOnError> </configuration> </plugin> </plugins> </build> I think that this configuration will be enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android upload photo to facebook illegal threadexception in my app i give the user otion to share using action_send intent. during the upload to facebook my app crashes but the photo uploading succeeds. this is my code and the logcat. what do you suggest? Intent sharingIntent = new Intent(Intent.ACTION_SEND); Uri screenshotUri = Uri.fromFile(file); sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); sharingIntent.setType("image/*"); sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri); getContext().startActivity(Intent.createChooser(sharingIntent, "Share image using")); Stacktrace: 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): FATAL EXCEPTION: main 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): java.lang.IllegalThreadStateException: Thread already started. 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at java.lang.Thread.start(Thread.java:1322) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at tomer.idunku3.GameView$1.surfaceCreated(GameView.java:103) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.view.SurfaceView.updateWindow(SurfaceView.java:532) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:206) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.view.View.dispatchWindowVisibilityChanged(View.java:3891) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:719) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:719) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:719) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.view.ViewRoot.performTraversals(ViewRoot.java:744) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.os.Handler.dispatchMessage(Handler.java:99) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.os.Looper.loop(Looper.java:123) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at android.app.ActivityThread.main(ActivityThread.java:4627) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at java.lang.reflect.Method.invokeNative(Native Method) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at java.lang.reflect.Method.invoke(Method.java:521) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 10-01 23:06:59.649: ERROR/AndroidRuntime(7273): at dalvik.system.NativeStart.main(Native Method) A: try: Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE); extracted from here
{ "language": "en", "url": "https://stackoverflow.com/questions/7625355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Translate and scale animation I have a wpf application and image inside a canvas. The image is placed in 0,0. I need to animate the image moving from 0,0 to 500,200 and in the same time growing (I like to make an effect like coming from far to near). If I do this: TranslateTransform ttx = new TranslateTransform(); TranslateTransform tty = new TranslateTransform(); DoubleAnimationUsingKeyFrames dax = new DoubleAnimationUsingKeyFrames(); dax.KeyFrames.Add(new LinearDoubleKeyFrame(500, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1)))); DoubleAnimationUsingKeyFrames day = new DoubleAnimationUsingKeyFrames(); day.KeyFrames.Add(new LinearDoubleKeyFrame(200, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1)))); TransformGroup tg = new TransformGroup(); tg.Children.Add(ttx); tg.Children.Add(tty); krug.RenderTransform = tg; ttx.BeginAnimation(TranslateTransform.XProperty, dax); tty.BeginAnimation(TranslateTransform.YProperty, day); And this works fine. It animates the translation of the image "krug" from 0,0 to 500,200. But when I add logic for zooming the image while translating like this: ScaleTransform zoom = new ScaleTransform(); DoubleAnimationUsingKeyFrames zoomTimeline = new DoubleAnimationUsingKeyFrames(); zoomTimeline.KeyFrames.Add(new LinearDoubleKeyFrame(2, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1)))); tg.Children.Add(zoom); zoom.BeginAnimation(ScaleTransform.ScaleXProperty, zoomTimeline); zoom.BeginAnimation(ScaleTransform.ScaleYProperty, zoomTimeline); Then the image does not stop to 500, 200 but goes more far. If the zoom factor is bigger, the translation goes more future. How can I control the animation to stop at 500,200 ? A: The problem you run into when combining scale and translate transforms is that it will scale the translate transform from the point of origin(ScaleTransform.CenterX, ScaleTransform.CenterY) For example, if you want to slide it to the right by 50, and double it's scale, it will actually move a net distance of 100. Try animating the ScaleTransform.CenterX and ScaleTransform.CenterY to match your translate transform. I believe that would let you scale on the fly like you want. A: Put the animations in a single storyboard and set the duration of the storyboard to control the length of the animations. Then start the storyboard. A: I found a solution. I created separate user control that only does ScaleTransform. Then I apply TranslateTransform on the user control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GWT, Maven and AspectJ: RequestFactory validation for AOPed code? To use GWT 2.4.0 RequestFactory, you have to run request factory validation tool. Otherwise, it just won't work. [Google says][1], that it's enough just to add 2 plugins to pom.xml: <!-- requestfactory-apt runs an annotation processor (APT) to instrument its service interfaces so that RequestFactoryServer can decode client requests. Normally you would just have a dependency on requestfactory-apt with <scope>provided</scope>, but that won't work in eclipse due to m2e bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=335036 --> <plugin> <groupId>org.bsc.maven</groupId> <artifactId>maven-processor-plugin</artifactId> <version>2.0.5</version> <executions> <execution> <id>process</id> <goals> <goal>process</goal> </goals> <phase>generate-sources</phase> </execution> </executions> <dependencies> <dependency> <groupId>com.google.web.bindery</groupId> <artifactId>requestfactory-apt</artifactId> <version>${gwtVersion}</version> </dependency> </dependencies> </plugin> <!-- Google Plugin for Eclipse (GPE) won't see the source generated above by requestfactory-apt unless it is exposed as an additional source dir--> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>${project.build.directory}/generated-sources/apt</source> </sources> </configuration> </execution> </executions> </plugin> The problem is, I have quite a complicated server-side code that uses AOP, so when validation tool is ran against that code, it fails because "there's no method xxx()", "class xxx doesn't implement interface yyy", etc. So, my question is, is it possible to fix this issue on pom.xml level, rather then moving all AOP code into separate project that will be compiled separately? A: Solved by moving all AOPed code to another project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get the name of the Focused element in C# Is there a function in C# that can return the Name of the Focused element and display it in a text-box or something? A: or you can do something like this... using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(GetFocusControl()); } [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)] internal static extern IntPtr GetFocus(); private string GetFocusControl() { Control focusControl = null; IntPtr focusHandle = GetFocus(); if (focusHandle != IntPtr.Zero) focusControl = Control.FromHandle(focusHandle); if (focusControl.Name.ToString().Length == 0) return focusControl.Parent.Parent.Name.ToString(); else return focusControl.Name.ToString(); } } } A: Assuming WinForms, you can find the active (focused) control using the Form.ActiveControl property and get the name. Otherwise if this is a WPF project, you could use the FocusManager.GetFocusedElement() method to find it. A: this function will return the index of Focused control in Form private int GetIndexFocusedControl() { int ind = -1; foreach (Control ctr in this.Controls) { if (ctr.Focused) { ind = (int)this.Controls.IndexOf(ctr); } } return ind; } when you find the index of focused control you can access this control from control collection int indexFocused = GetIndexFocusedControl(); textBox1.Text = this.Controls[indFocused].Name; // access the Name property of control A: I just found that there's a way easier way of doing this if you're not using nested controls. You just reference Form1.ActiveControl.Name A: Worked for me in c#. string name = ActiveForm.ActiveControl.Name;
{ "language": "en", "url": "https://stackoverflow.com/questions/7625361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Set objectAtIndex to be the integer in an NSString? I've got this: if ([[currentPlayer rankicon] isEqualToString:@"0"]) { self.casteImage.image = [casteImages objectAtIndex:0]; } Which works. However, I have some 16 images to assign, and since the NSString and the index id are the same, I'd like to find a more efficient way to do this. I've also tried: NSInteger i = [[currentPlayer rankicon] integerValue]; self.casteImage.image = [casteImages objectAtIndex:[i]]; But that doesn't work. Could be a bug elsewhere in my code(or some syntax error in the above), of course, but was wondering if I'm anywhere near the right track. A: Remove [] around iin the second line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query about Properties Vectors in C++ I am kind of a beginner and just came across the concept of vectors in C++. I have a few questions about it 1. Is there a concept of 2-D vectors in C++? if yes, then how do i declare corresponding to a 2-D Matrix a[n][m]? Here, n and m are variables. 2. How are vectors passed as arguments to functions? By default are they passed by reference or by value? 3. Are there any performance benifits of vectors over arrays in C++? A: 1 - There's no real concept of dimensions per se. But you can create "nested" types. For example: std::vector <int> intVec; std::vector < std::vector <int> > doubleIntVec; Here, intVec can be compared to single-dimension vector, doubleIntVec to double dimension, and so on. The types don't have to be the same, you can do std::vector < std::vector <char> > doubleIntVec for example, which is why "dimension" is not the right term here. 2 - Like any other type, there's no specific treatment of vectors. 3 - Yes, for example if you need resizing them, but you can implement arrays to behave similarly. Other than that the benefit is the standardization, the memory management that comes built in, the additional methods, and the various STL algorithms that can be run on vectors (being it a standard container). A: vector in C++ is just a sequence container. So, it's possible using it to hold a 2D array. * *Using std::vector <std::vector<int>> *It depends on the purpose. *Not perfomance wise, but unlike array, std::vector is growable. A: There's no 2-D vectors in C++, to create a matrix, you can use vectors of vectors. using namespace std; int m, n; // ... vector<vector<int> > v(n); for (int y = 0; y < n; y++) v[n].resize(m); // ... Computing libraries won't implement them this way, though. To pass a vector by reference to a function, use: void function(vector & v); Omitting the & will result in the vector being copied during the function call. Vectors have the same performance as C arrays, but are much more practical to use. No need to manually manage the memory, and the vector size is always accessible. You also have automatic copy and guarantees on contiguity of values (raw data can be accessed by vector::data()
{ "language": "en", "url": "https://stackoverflow.com/questions/7625371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way to handle events with multiple classes? So I have a class that is basically a manager for 20+ copies of another class. What is the best way of handling the same event fired from each one of them? And is this the best way of unregistering the events? Or should I be using a single EventHandler somehow? I put together a simple example that basically does what I'm doing in my actual project. class Manager { List<Child> children = new List<Child>(); public Manager() { for (int i = 0; i < 10; i++) { Childchild = new Child(); child.Done += child_Done; items.Add(child); child.DoStuff(); } } public void RemoveAll() { foreach (Child child in items) { child.Done -= child_Done; } items.Clear(); } void child_Done(string sometext) { Console.WriteLine("child done: " + sometext); } } class Child { public delegate void _Done(string sometext); public event _Done Done; public Child() { } public void DoStuff() { if (Done != null) { Done("finally!"); } } } A: Assuming you want the It might be better to add the Manager object to respond to each child when the child object raises the event: It might be better to register for the event when adding a child and unregister when removing a child. A quick way to do that would be to switch from List to ObservableCollection. This collection will raise an event as soon as the collection changes. So in the constructor of the Manager, instantiate the ObservableCollection and register for the CollectionChanged event. In the handler check the event argument to see what children have been added, and removed so the manager can register for (or unregister) their event(s). A: The unregistration should be fine - as long as the target instance and method match it will work. I will, however, strongly advise you use a more regular event pattern, with a sender - then you will know which child is talking. For example: public class MessageEventArgs : EventArgs { public MessageEventArgs(string message) { this.message = message; } private readonly string message; public string Message { get { return message; } } } and an: public event EventHandler<MessageEventArgs> Done; protected virtual void OnDone(string message) { var handler = Done; if(handler != null) handler(this, new MessageEventArgs(message)); } A: This is more or less the way. A few suggestions to make it work a little better: * *Create a function that adds a Child, and at the same way registers the event. The same can be done with removing child + unregistering the event. *Also, you can make the event get a "sender" parameter, and make the Child pass "this" to it. This way the event handler will be able to know which child is done, and remove it from the list, and/or whatever else needs to be done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Margin menu in IE Faced with the problem. Made a menu on Jquery. All browsers good show site, except of course Internet Explorer. Tell me, what can be done to remove the padding in IE, the site address http://edusf.ru/project/ A: First you are missing a doctype <!DOCTYPE html> Your page shows up in Quirks mode in IE9. Once you do that, your document will be in IE9 standard mode and the problem will be fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gallio test suite installation I am using MbUnit test framework and Gallio. I need to create an installer that install it and run some test on silent mode. I noticed that Gallio got a quiet installation mode 'GallioInstall.msi /quiet'. My problem is how to know when the installation is done? because when i run on command line it installs it on the background and i can continue working. A: That's not really got anything to do with Gallio, it's an MSI feature: http://msdn.microsoft.com/en-us/library/windows/desktop/aa372024(v=vs.85).aspx I would assume control doesn't return to the command line until the installation has completed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java - splitting a string onto a new string? E.g. String s = "You should always brush your teeth before every meal in the day."; but I want do split part of it into a new sentence like so: String s = "You should always brush your teeth/nbefore every meal in the day."; so the result is this: String s = "You should always brush your teeth"; String s2 = "before every meal in the day."; Basically, I want it to search for the "/n" and then separate the next sentence from the present one. A: String[] str = s.split("/n"); if(str.length == 2) { s = str[0]; s2 = str[1]; } A: You can split your string into an array of strings doing String[] chunks = s.split("\\n");
{ "language": "en", "url": "https://stackoverflow.com/questions/7625382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How could I stop spam if my form is using ajax submit method (with no reload)? I have a form which uses ajax for data submitting. Here is the html: <form> <input type="text" id="content" name="content"> <input type="submit" class="button" name="button"> </form> and the JavaScript (jQuery): $(function() { //Update Message... $(".button").click(function() { var boxval = $("#content").val(); var dataString = 'content='+ boxval; if(boxval=='') { alert("Please Enter Some Text"); } else { $("#flash").show(); $("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>'); $.ajax({ type: "POST", url: "update_data.php", data: dataString, cache: false, success: function(html){ $("ol#update").prepend(html); $("ol#update li:first").slideDown("slow"); document.getElementById('content').value=''; document.getElementById('content').focus(); $("#flash").hide(); } }); } return false; }); }); It is all working fine, but there is a big problem: I cannot stop spam. Last time I used spam filters, it was in PHP (I used a hidden input and then checked in the PHP file if it is filled out). But that was totally in PHP, no JS. So here is my question: How could I stop spam in this form submission? Also, can I create an if statement in the update_data.php file? A: I you do not like to add Captcha here is a good solution: First add input that is hidden with css in the form. If the bot submits the form the hidden field will have some value filled by the bot. In normal cases the human will not see it and will be empty. In the case of a bot you will check it and if it has some value you will discard. Also you need to add input (also hidden with css) with javascript on document ready. If it is browser it will execute the javascript and will insert the input in the form. If it is a bot then the bots do not execute js and there will be no input field generated by js and on the server side you will see that there is no such field and you will discard the request. So on the server side you will check if the first hidden field has value or the second hidden field does not exist discard the request. A: First fast answer is putting inside the form something that could help you to understand if the user submitting your form is a bot or not. Captcha for sure, or just a question not easy to answer for a bot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JavaScript for (pasting!) only numbers in a textfield I'm using this script to have a textfield with only numbers, and it works just fine, only my users cant past a number, and as I need 7+ digits, I guess a lot of people will be using copy paste. I saw some solutions which use jquery, but seams a bit too heavy for me, and there mus be some light elegant solution which allows pasting? A: You can use the number type introduced in HTML5: <input type="number" min="0" max="9999999"> It’s not supported everywhere, but you can add a fallback for IE using the input.onpropertychange event and check for window.event.propertyName == 'value' inside the handler to listen for any changes in the input field. For other browsers, you can try the "input" event. Or simply validate and modify on blur to be nicer to the user. As others have mentioned, it’s considered bad practice to do this as the user types. The number attribute adds a pretty decent way of handling this on it’s own.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to build an Object array out of JSON array using Javascript overlay types? My JSON response is an array of Object (Folder for example). I would like to generate an array of Folder objects using Javascript overlay types. I tried the following method: public static final native Folder[] buildFoldersArray(String json) /*-{ return eval('(' + json + ')'); }-*/; And the usage: Folder[] folders = Folder.buildFoldersArray(myJSON); Note: Folder extends JavaScriptObject as it should. And the error I get: java.lang.ClassCastException: com.google.gwt.core.client.JavaScriptObject$ cannot be cast to [Lcom.cnario.project.client.Folder; at com.cnario.project.client.Folder$.buildFoldersArray(Folder.java) at com.cnario.project.client.view.TreeView.FillTree(TreeView.java:51) at com.cnario.project.client.ManageContent$1.onResponseReceived(ManageContent.java:89) at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:287) at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:395) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337) at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218) at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136) at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91) at com.google.gwt.core.client.impl.Impl.apply(Impl.java) at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292) at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546) at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363) at java.lang.Thread.run(Unknown Source) What is the right way of retrieving objects array using JS Overlay types? A: Problem solved: evaluation should return JsArrey<E> instead of E[]: public static final native JsArray<Folder> buildFoldersArray(String json) /*-{ return eval('(' + json + ')'); }-*/; Example usage: JsArray<Folder> folder = Folder.buildFoldersArray(json); item = new TreeItem(folder.get(0).getName());
{ "language": "en", "url": "https://stackoverflow.com/questions/7625389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: delete contacts from windows phone 7.1 c# Can I delete contact from windows phone 7.1 using windows phone 7.1 sdk and c# ? example : I have "mero" contact and I want to delete it to make new one with some new information A: Due to internal restrictions, you cannot alter or delete user information on the phone (in this case - contact information) through the Windows Phone SDK. Certainly, you can do this if you try working outside the sandbox, but that will have its own barriers. TL,DR: No.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hover event to occur independently on separate images Alright, so I have some code hurr: $(document).ready(function(){ $("div.post.photo img").hover(function () { $("div.show").slideToggle("fast"); }); }); Now, it works like a champ. Except for the fact that it occurs on all images simultaneously. I tried to find out how to get it to work on each image separately, but I don't have the darnest clue. What I am trying to do specifically is have a hover event on an image occur only when you hover over that specific image. When you hover over an image a div pops up with some fancy caption and so on. However, when I hover on one image all the other images show the same thing (I understand why, just not how to fix it). I figure it has something to do with adding this to it, but I'm new to JQuery and I'm lost. HTML: <div class="post photo"> <img src="source" /> <div class="show"> <div class="caption"> Caption </div> </div> </div> Thanks for the help. A: $(document).ready(function(){ $("div.post.photo img").hover(function () { $(this).next("div.show").slideToggle("fast"); }); }); A: With this you can disregards from what position you have put your "show" div into "post photo" class div : $(document).ready(function(){ $("div.post.photo img").hover(function () { $(this).parent().children("div.show").slideToggle("fast"); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7625397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swap elements when you drag one onto another using jQuery UI I have an arrangement of elements on a page: <div> <div class="dragdrop" style="top:0px; left: 0px; ">1</div> <div class="dragdrop" style="top:40px; left: 0px; ">2</div> <div class="dragdrop" style="top:60px; left: 0px; ">3</div> <div class="dragdrop" style="top:0px; left: 100px;">4</div> <div class="dragdrop" style="top:40px; left: 100px;">5</div> <div class="dragdrop" style="top:60px; left: 100px;">6</div> </div> How can I use jQuery UI (Draggable / Droppable) to make it so that if one div is dropped onto another, they swap positions? (And if it's dragged anywhere else, it reverts back to its old position.) Thanks. A: Here is an example of how you can swap elements with drag and drop http://jsfiddle.net/76yRN/1/ Another question about swapping elements in jquery jQuery draggable items lose their draggability after being swapped (with jsfiddle example) Hope this helps A: You just replace the elements from one to another. Some time ago i have created a demo for swapping elements between to UL list. check this: http://www.authorcode.com/swap-elements-when-drag-one-onto-another-using-jquery-ui/ A: I used a combination of solutions to arrive at this, with #large_tiles and #small_tiles being two lists: $(function() { $("#large_tiles li, #small_tiles li").draggable({ zIndex: 2, appendTo: "body", }); initDroppable($("#large_tiles li, #small_tiles li")); initSwap(); function initSwap() { initDroppable($("#large_tiles li, #small_tiles li")); initDraggable($("#large_tiles li, #small_tiles li")); } function initDraggable($elements) { $elements.draggable({ zIndex: 2, appendTo: "body", helper: "clone", start: function(e, ui) { $(ui.helper).addClass("clone"); }, cursorAt: { left:50, top:75 } }); } function initDroppable($elements) { $elements.droppable({ activeClass: "active-tile", hoverClass: "hover-tile", over: function(event, ui) { var $this = $(this); }, drop: function(event, ui) { var $this = $(this); var linew1 = $(this).after(ui.draggable.clone()); var linew2 = $(ui.draggable).after($(this).clone()); $(ui.draggable).remove(); $(this).remove(); initSwap(); } }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7625401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Error trying to assigning __block ALAsset from inside assetForURL:resultBlock: I am trying to create a method that will return me a ALAsset for a given asset url. (I need upload the asset later and want to do it outside the result block with the result.) + (ALAsset*) assetForPhoto:(Photo*)photo { ALAssetsLibrary* library = [[[ALAssetsLibrary alloc] init] autorelease]; __block ALAsset* assetToReturn = nil; NSURL* url = [NSURL URLWithString:photo.assetUrl]; NSLog(@"assetForPhoto: %@[", url); [library assetForURL:url resultBlock:^(ALAsset *asset) { NSLog(@"asset: %@", asset); assetToReturn = asset; NSLog(@"asset: %@ %d", assetToReturn, [assetToReturn retainCount]); } failureBlock:^(NSError *error) { assetToReturn = nil; }]; NSLog(@"assetForPhoto: %@]", url); NSLog(@"assetToReturn: %@", assetToReturn); // Invalid access exception coming here. return assetToReturn; } The problem is assetToReturn gives an EXC_BAD_ACCESS. Is there some problem if I try to assign pointers from inside the block? I saw some examples of blocks but they are always with simple types like integers etc. A: A few things: * *You must keep the ALAssetsLibrary instance around that created the ALAsset for as long as you use the asset. *You must register an observer for the ALAssetsLibraryChangedNotification, when that is received any ALAssets you have and any other AssetsLibrary objects will need to be refetched as they will no longer be valid. This can happen at any time. *You shouldn't expect the -assetForURL:resultBlock:failureBlock:, or any of the AssetsLibrary methods with a failureBlock: to be synchronous. They may need to prompt the user for access to the library and will not always have their blocks executed immediately. It's better to put actions that need to happen on success in the success block itself. *Only if you absolutely must make this method synchronous in your app (which I'd advise you to not do), you'll need to wait on a semaphore after calling assetForURL:resultBlock:failureBlock: and optionally spin the runloop if you end up blocking the main thread. The following implementation should satisfy as a synchronous call under all situations, but really, you should try very hard to make your code asynchronous instead. - (ALAsset *)assetForURL:(NSURL *)url { __block ALAsset *result = nil; __block NSError *assetError = nil; dispatch_semaphore_t sema = dispatch_semaphore_create(0); [[self assetsLibrary] assetForURL:url resultBlock:^(ALAsset *asset) { result = [asset retain]; dispatch_semaphore_signal(sema); } failureBlock:^(NSError *error) { assetError = [error retain]; dispatch_semaphore_signal(sema); }]; if ([NSThread isMainThread]) { while (!result && !assetError) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } } else { dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); } dispatch_release(sema); [assetError release]; return [result autorelease]; } A: You should retain and autorelease the asset: // ... assetToReturn = [asset retain]; // ... return [assetToReturn autorelease];
{ "language": "en", "url": "https://stackoverflow.com/questions/7625402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: use of parent's function (inheritance c++) I have four .cpp files, Animal, Cattle, Sheep, DrugAdmin. Animal is parent class of Cattle, and it has calcDose(), which calculates the amount of dose. DrugAdmin is main function. The thing is, I want to use calcDose() function differently (Cattle, Sheep) and no calcDose() function is needed for Animal class. However, every time I try to use calcDose(), it automatically calls function in Animal class even when I want to use under Cattle class. This is the code I have done so far. (I've cut it down) Animal.cpp #include "Animal.h" #include <string> using namespace std; Animal::Animal(int newid, double newweight, int yy, int mm, int dd, char newsex, vector<Treatment> treatArray) { id = newid; weight = newweight; yy = yy; mm = mm; dd = dd; accDose = 0; sex = newsex; } double Animal::calcDose(){ return 0; } Cattle.cpp #include "Cattle.h" using namespace std; Cattle::Cattle(int newid, double newweight, int yy, int mm, int dd, char newsex, vector<Treatment> newtreatArray, string newcategory) : Animal(newid, newweight, yy,mm,dd, newsex, newtreatArray) { id = newid; weight = newweight; accDose = 0; sex = newsex; Cattle::category = newcategory; } Cattle::~Cattle(){} double Cattle::calcDose(){ if(getDaysDifference() < 90 || getCategory() == "Meat"){ accDose = 0; return accDose; } else if(getCategory() == "Dairy"){ if (weight < 250 || accDose > 200){ accDose = 0; } else{ accDose = weight * 0.013 + 46; } return accDose; } else if(getCategory() == "Breeding"){ if (weight < 250 || accDose > 250){ accDose = 0; } else{ accDose = weight * 0.021 + 81; } return accDose; } else { //cout << "It is not valid category" << endl; } } Sheep class is pretty much same but the contents of calcDose() DrugAdmin.cpp #include "DrugAdmin.h" using namespace std; vector<Animal*> vec_Animal; void addAnimal(){ int select=0; int id; double weight; int yy; int mm; int dd; char sex; string category; vector<Treatment> treatArray; //user inputs all the values (i've cut it down) Animal* c1 = new Cattle(id,weight,yy,mm,dd,sex,treatArray,category); vec_Animal.push_back(c1); } void administerDose(int id) //Main Problem { vector<Animal*>::iterator ite_Animal = vec_Animal.begin(); for(ite_Animal; ite_Animal != vec_Animal.end(); ++ite_Animal) cout<<"\nVector contains:"<< (*ite_Animal)->calcDose(); } I'm sorry for the long and messed up question. Final question is, Cattle has extra data member which is category but the system doesn't recognise this as well. It recognises as if it is Animal object. Can I have a piece of advice please? Cheers A: every time I try to use calcDose(), it automatically calls function in Animal class Sounds like you forgot to make calcDose a virtual member function. Final question is, Cattle has extra data member which is category but the system doesn't recognise this as well. It recognises as if it is Animal object. I'm not sure what you mean by the "system" "recognizing" anything, but if you access a Cattle object through an Animal*, then you can't get to the Cattle-specific members. You'd have use either a Cattle* or, again, polymorphism/virtual. A: Unlike Java (and many other languages), C++ uses what is called "static binding" by default. Static binding means the function called is based on the declared type of the object (or pointer) at compile time, rather than what the object actually is (or what the pointer is actually pointing to). The alternative to static binding is "dynamic binding". In dynamic binding, the function called is based on what the object actually is (or what the pointer is actually pointing to) at runtime. To enable dynamic binding, which is what you'll want if you have an inheritance hierarchy set up and are maintaining base class pointers (Animal*s), you have to use the keyword virtual. virtual makes a function dynamically bound, so that calls to that function will reflect the actual runtime type of the object (Cattle) rather than the compile time declared pointer type (Animal*). To declare a function virtual, you put the virtual keyword before the return value on the function declaration (in the class declaration / .h file): class Animal { virtual void calcDose(); // ... }; It is also good style to put virtual on the overridden function in the derived class (calcDose() in Cattle), although the virtual is implied for inherited functions, so putting it there is not strictly necessary. The one last thing to make sure you to get dynamic binding, is to make sure you always have pointers (or references) to objects rather than objects on the stack (when you want dynamic binding). An object on the stack (i.e. Animal a) can only be it's declared type, it can't point to a derived class type. So the vector<Animal*> you have is perfect, because those pointers can point to Cattle objects (or Animal objects), while a vector could only hold actual animal objects. A: You should make your calcDose function virtual and redefine it in each subclass: Cattle, etc. Also to recognize your Animal as a Cattle you have to cast it to Cattle class. But you are supposed to use the common base type interface most of the time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to maintain JavaScript function variable states (values) between calls? I am looking for getters and setters functionality but cannot rely on __defineGetter__ and __defineSetter__ yet. So how does one maintain a function variable's value between function calls? I tried the obvious, but myvar is always undefined at the start of the function: FNS.itemCache = function(val) { var myvar; if( !$.isArray(myvar) myvar = []; if( val === undefined) return myvar; .. // Other stuff that copies the array elements from one to another without // recreating the array itself. }; I could always put another FNS._itemCache = [] just above the function, but is there a way to encapsulate the values in the function between calls? A: You can store the value on the function by using arguments.callee as a reference to the current function: FNS.itemCache = function(val) { if( !$.isArray(arguments.callee._val) arguments.callee._val = []; if(val === undefined) return arguments.callee._val; .. // Other stuff that copies the array elements from one to another without // recreating the array itself. }; However, this will break if the function is stored in a prototype and thus used by more than one object. In this case you have to use a member variable (e.g. this._val). A: this is a standard pattern for creating your static variable and for creating private members of an object FNS.itemCache = (function() { var myvar; if( !$.isArray(myvar) myvar = []; return function(val) { if( val === undefined) return myvar; .. // Other stuff that copies the array elements from one to another without // recreating the array itself. } })(); A: An alternative way to set a private variable is by wrapping the function definition in an anonymous function: (function(){ var myvar; FNS.itemCache = function(val) { if( !$.isArray(myvar)) myvar = []; if( typeof val == "undefined") return myvar; .. // Other stuff that copies the array elements from one to another without // recreating the array itself. }; })(); This way, myvar is defined in the scope of FNS.itemCache. Because of the anonymous function wrapper, the variable cannot be modified from elsewhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Render template to variable in expressjs Is there a way to render template to a variable instead to output? res.render('list.ejs', { posts: posts }); something like this var list = render('list.ejs', { posts: posts }); A: The easiest way to do that is to pass a callback to res.render, in your example: res.render('list.ejs', {posts: posts}, function(err, list){ // }); But if you want to render partial templates in order to include them in another template you definitely should have a look at view partials. A: I am quite a newbie on express.js, anyway I am not sure you can access the rendered string that way, although if you look at express' "view.js" source on github (here) you see that it's accepting a callback as second argument, if that may help: you may access the rendered string there. Otherwise, I think it's quite easy to patch the code to add a method returning the rendered string without sending it: on line #399 you have the very call that gives the string you are looking for. A: This wasn't the question originally asked, but based on comments from the OP and others, it seems like the goal is to render a partial via json (jsonp), which is something I just had to do. It's pretty easy: app.get('/header', function (req, res) { res.render('partials/header', { session: req.session, layout: null }, function (err, output) { res.jsonp({ html: output }); }); }); Note: In my case, the header partial required the session, and my template library (express-hbs) needed layout: null to render the partial without using the default layout. You can then call this from Javascript code in the client like any other JSONP endpoint.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How to view a Collada mesh in a Qt application? How do I create a small 3D viewport and show there a Collada mesh? Also, mesh has textures, and user would want to rotate and zoom in/out with a mouse. A: I believe that OpenSceneGraph supports the Collada file format, and provides a choice of Qt widgets. You may need to install the OSG Collada Plugin. I used OpenSceneGraph with Qt nearly 3 years ago, and it was a very good experience. I found the mouse control to be very pleasing. They released version 3.0.0 in June this year, and 3.0.1 in July, suggesting that it is still being actively worked on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: minimize app to system tray I have a Windows forms app powered by C# and Visual Studio 2010. How can I minimize my app to system tray (not taskbar), then bring it back when doubled click in the system tray? any idea? also, how can I make some menu in the icon in system tray and when I right click it, it shows a menu like Login, Disconnect, Connect, something like that. Also, are there any methods to show like a baloon popping up from the system tray? PS: I already added a notifyIcon, but I do not know how to use it. A: I found this to accomplish the entire solution. The answer above fails to remove the window from the task bar. private void ImportStatusForm_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { notifyIcon.Visible = true; notifyIcon.ShowBalloonTip(3000); this.ShowInTaskbar = false; } } private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) { this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; notifyIcon.Visible = false; } Also it is good to set the following properties of the notify icon control using the forms designer. this.notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; //Shows the info icon so the user doesn't think there is an error. this.notifyIcon.BalloonTipText = "[Balloon Text when Minimized]"; this.notifyIcon.BalloonTipTitle = "[Balloon Title when Minimized]"; this.notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon.Icon"))); //The tray icon to use this.notifyIcon.Text = "[Message shown when hovering over tray icon]"; A: This is the method I use in my applications, it's fairly simple and self explanatory but I'm happy to give more details in answer to your comments. public Form1() { InitializeComponent(); // When window state changed, trigger state update. this.Resize += SetMinimizeState; // When tray icon clicked, trigger window state change. systemTrayIcon.Click += ToggleMinimizeState; } // Toggle state between Normal and Minimized. private void ToggleMinimizeState(object sender, EventArgs e) { bool isMinimized = this.WindowState == FormWindowState.Minimized; this.WindowState = (isMinimized) ? FormWindowState.Normal : FormWindowState.Minimized; } // Show/Hide window and tray icon to match window state. private void SetMinimizeState(object sender, EventArgs e) { bool isMinimized = this.WindowState == FormWindowState.Minimized; this.ShowInTaskbar = !isMinimized; systemTrayIcon.Visible = isMinimized; if (isMinimized) systemTrayIcon.ShowBalloonTip(500, "Application", "Application minimized to tray.", ToolTipIcon.Info); } A: don't forget to add icon file to your notifyIcon or it will not appear in the tray. A: I'd go with private void Form1_Resize(object sender, EventArgs e) { if (FormWindowState.Minimized == this.WindowState) { notifyIcon1.Visible = true; notifyIcon1.ShowBalloonTip(500); this.Hide(); } else if (FormWindowState.Normal == this.WindowState) { notifyIcon1.Visible = false; } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; } A: * *C# System Tray Minimize To Tray With NotifyIcon *Minimize window to system tray Handle the form’s Resize event. In this handler, you override the basic functionality of the Resize event to make the form minimize to the system tray and not to the taskbar. This can be done by doing the following in your form’s Resize event handler: Check whether the form’s WindowState property is set to FormWindowState.Minimized. If yes, hide your form, enable the NotifyIcon object, and show the balloon tip that shows some information. Once the WindowState becomes FormWindowState.Normal, disable the NotifyIcon object by setting its Visible property to false. Now, you want the window to reappear when you double click on the NotifyIcon object in the taskbar. For this, handle the NotifyIcon’s MouseDoubleClick event. Here, you show the form using the Show() method. private void frmMain_Resize(object sender, EventArgs e) { if (FormWindowState.Minimized == this.WindowState) { mynotifyicon.Visible = true; mynotifyicon.ShowBalloonTip(500); this.Hide(); } else if (FormWindowState.Normal == this.WindowState) { mynotifyicon.Visible = false; } } A: try this private void Form1_Load(object sender, EventArgs e) { notifyIcon1.BalloonTipText = "Application Minimized."; notifyIcon1.BalloonTipTitle = "test"; } private void Form1_Resize(object sender, EventArgs e) { if (WindowState == FormWindowState.Minimized) { ShowInTaskbar = false; notifyIcon1.Visible = true; notifyIcon1.ShowBalloonTip(1000); } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { ShowInTaskbar = true; notifyIcon1.Visible = false; WindowState = FormWindowState.Normal; } A: At the click on the image in System tray, you can verify if the frame is visible and then you have to set Visible = true or false A: ...and for your right click notification menu add a context menu to the form and edit it and set mouseclick events for each of contextmenuitems by double clicking them and then attach it to the notifyicon1 by selecting the ContextMenuStrip in notifyicon property. A: this.WindowState = FormWindowState.Minimized;
{ "language": "en", "url": "https://stackoverflow.com/questions/7625421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "123" }
Q: How to include a php script in all HTTP requests coming to the server I have a file called init.php which I want to get automatically included in each and every HTTP request coming to my server. My server is on LAMP configuration with PHP 5.3 and fast CGI. Any method to achieve this is welcome. What I have already tried: I have already tried the auto_prepend_file method with .htaccess file but no success. I have done the following. .htaccess File: php_value auto_prepend_file /home/user/domain.com/init.php init.php file: <?php echo "statement 2"; ?> index.php file: statement 1 So, now if I visit http://domain.com/ I find only statement 1 getting printed. statement 2 is not getting printed. Kindly let me know how to correct this or if there is any other way to achieve this. A: My server is on LAMP configuration with PHP 5.3 and fast CGI. You can not set PHP ini directives with the .htaccess method with FCGI/CGI. You need to apply the changes within the php.ini or better the user ini files Docs instead. Place a file called .user.ini into the document root and add the auto_prepend_fileDocs directive in there: auto_prepend_file = /home/user/domain.com/init.php This should do the job for you. A: My server is on LAMP configuration with PHP 5.3 and fast CGI. fast CGI means no .htaccess directive would work. Change your php.ini instead. automatically included in each and every HTTP request with auto_prepend_file you obviously can't include a php file to "each and every HTTP request", but to requests routed to PHP files only.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: UITableView with live data also has user interaction same time I'm working on proof of concept project. That is using a UITableView to display some live data. "live data" is beeing merging with sensor information on real time in the the app. After UITableView rendered with some NSMutableArray data, that NSMutableArray is updating with sensor data appprox each 1 sec, also UITableView has user interaction same time. My question is, according to above, what is the best approach consume live data on UITableView ? Any suggestions, samples would be appreciated. A: The SeismicXML parser sample code in the apple documentation does something similar. It gets 'live' (i.e. changing) information about earthquakes from a server and updates the datasource via an NSNotification when new information arrives. The UITableView reloads its data based on key-value observing of when the NSMutableArray changes. The reload is done with [tableView reloadData]. There is also user interaction with the table: the user can select a tableViewCell and choose to follow a link to further information. If you're worried about controlling coordination:What you want to avoid is that the user taps on the table, the dataArray gets changed, and the -tableView:didSelectRowAtIndexPath: method tries to access the data at the same time. There are two choices: either prevent selection in the table while the data updates or prevent the data from updating while the row selection was occurring. You can prevent interaction with the table by setting tableView.allowsSelection=NO. You can find out when the data is about to update by using the key-value-observing option: NSKeyValueObservingOptionPrior. This approach generally loses points though because you may interrupt what the user wanted to do. The other choice would be to delay the data update by setting up a couple of booleans: isSelecting and dataNeedsReloading. Flow would be something like: the user taps the table, isSelecting=YES If new data come in, if (isSelecting) { [tempArray addObject:newData]; dataNeedsReloading=YES; } Then when the selection process finishes, reset isSelecting=NO, check the dataNeedsReloading flag, combine the arrays and reload the table if needed. When finished, reset dataNeedsReloading=NO. Also reset the tempArray with -removeAllObjects. A: If you want to update the UITableView every time the datasource changes, send it a reload message. A: Call addData method on main thread whenever new data is available from Sensor. -(void) addData:(NSString*)newDataFeild{ @synchronized(self){ NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[_data count] inSection:0]; [_data addObject:line]; [self reloadData]; [self scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO]; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } cell.textLabel.text = [_data objectAtIndex:indexPath.row]; return cell; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7625431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to call a server-side ASP.NET event from the client-side I have an asp.net button in the gridview footer, and I wanna to call the server-side ASP.NET button event in the client side (JavaScript). How to do this please code details if possible. My .aspx: <FooterTemplate> <asp:ImageButton ID="ibtn_add" ImageUrl="~/Images/accord_plus.png" runat="server" OnClick="ibtn_add_Click" /> </FooterTemplate> I wanna to know how to call the ibtn_add_Click in the client side. in the following code: var isShift = false; document.onkeyup = function(e) { if (e.which == 16) isShift = false; } document.onkeydown = function(e) { if (e.which == 16) isShift = true; if (e.which == 13 && isShift == true) { //Here I wanna to call ibtn_add_Click return false; } } Note : The gridview in an update panel, and I execute the JavaScript through: <asp:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <asp:ScriptReference Path="~/Scripts/Shortcut.js" /> </Scripts> </asp:ScriptManager> A: Use OnClientClick button's attribute. OnClientClick="ibtn_add_Click()" MSDN A: I think you want something like this ... if (e.which == 13 && isShift == true) { __doPostBack('ibtn_add','OnClick'); return false; } A: You might use ajax and make a call to webservice or web method or you can use or you can use __doPostBack(‘btntest','OnClick') or $('btntest').trigger('click'); chck this link : http://codethatworkedforme.blogspot.com/2011/08/some-tricks-for-asynchronous-postback.html A: <asp:ImageButton ID="ibtn_add" ImageUrl="~/Images/accord_plus.png" runat="server" OnClick="ibtn_add_Click" /> This is the problem I have faced but I used only for OnClientClick
{ "language": "en", "url": "https://stackoverflow.com/questions/7625437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update json in database mysql I want comparison between two table (table_foreign, table_submits) in database that if not existing some data from table table_foreign in table table_submits on database, deletded it data in table table_foreign or updated. $query_tfhi = $this->db->query("SELECT * FROM table_foreign ORDER BY id desc"); foreach ($query_tfhi->result() as $row) { $data_hi = json_decode($row->how_id, true); foreach ($data_hi as $hitf) { foreach ($hitf['howinto_id'] as $val_hitf) { //echo $val_hitf.'<br>'; $query_delhi = $this->db->query("SELECT * FROM table_submits WHERE id LIKE '$val_hitf'"); if ($query_delhi->num_rows() == 0) { //echo $val_hitf; $this->db->query("DELETE how_id = array('howinto_id'=>$val_hitf) FROM tour_foreign WHERE id LIKE '$row->id'"); } else { } } } } I have in table table_foreign on column how_id as(this data store(inserted) with json_encode on a column in row database table): [{ "howinto_id": ["14"] },{ "howinto_id": ["5"] },{ "howinto_id": ["4"] }, { "howinto_id": ["3"] }, { "howinto_id": ["2"] }, { "howinto_id": ["1"] }] in table table_submits on column id: 1, 2, 3, 4 With comparison between two table in table_foreign value 14,5` should deleted. after this it is as: [{ "howinto_id": ["4"] }, { "howinto_id": ["3"] }, { "howinto_id": ["2"] }, { "howinto_id": ["1"] }] In output above PHP code have error: A Database Error Occurred Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('howinto_id'=>14) FROM tour_foreign WHERE id LIKE '1'' at line 1 DELETE how_id = array('howinto_id'=>14) FROM table_foreign WHERE id LIKE '1' Filename: D:\xampp\htdocs\system\database\DB_driver.php Line Number: 330 How can fix they? A: Well i think your problem should be fixed like this: * *First , you need to retrieve data of two tables as arrays (anyhow) from json obj as it returns array *Second you can use array_diff($array1 , $array2) which returns array of differences between those tow arrays *Third you can select Ids from the difference array ( $ids ) and use $this->db->where_in("Id",$ids)->delete("table_submits") Like this you have deleted the diff between the tow tables from the database , and tell me if this is ok with you
{ "language": "en", "url": "https://stackoverflow.com/questions/7625440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JTable removeRow(), removing wrong row I have a JTable and I need to remove a row, namely, the selected row. So first, I get the the table model : DefaultTableModel model = (DefaultTableModel) table.getModel(); Then the selected row (if the second row is selected, this returns 1, which is understandable because rows start from zero): int selectedRow = table.getSelectedRow(); Then I try to remove the row: model.removeRow(selectedRow); Then I set the table model again: table.setModel(model); What this achieves is removing a completely random row. I simply can't understand why. I have sorted the table at some point, using table.setRowSorter(sorter), but I don't know why that should be a problem. If an SSCCE is absolutely needed please let me know, because I have a lot of code to modify before I can produce one. NOTE: The values returned by these two lines differ: System.out.println(table.getValueAt(selectedRow, 1)); System.out.println(model.getValueAt(selectedRow, 1)); A: The index returned by JTable.getSelectedRow is a view index : it's the index of the row as seen by the end-user in the table. It's not the same as the model index, because if you sort the table, the indices in the model don't change, but the indices in the view do change. So, you must always use JTable.convertRowIndexToModel to get the model index from the view index. Note that the same must be done for columns, because the user might choose to reorder columns to its taste. Also, you shouldn't have to set the model again each time you remove a row. Instead, your model should fire a TableModelEvent to inform the view about the removal. See AbstractTableModel.fireTableRowsDeleted. A: If is JTable filtered or sorted then you can convert int modelRow = convertRowIndexToModel(row);
{ "language": "en", "url": "https://stackoverflow.com/questions/7625448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I access contacts list in Nokia mobiles using Qt Application? I want to make a program using Qt that can access the contacts list of Nokia mobiles. I mean by accessing changing the contacts telephone numbers "not viewing them only". A: Look here: http://doc.qt.nokia.com/qtmobility-1.1.0-beta/qcontactmanagerengine.html. Maybe it will help you. And learn about Qt Mobility of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaFX alternatives as Java and Linux mind coders? What are the Linux user alternatives for JavaFX powered by Oracle? (without switching to Mac/Windows platform). A: * *Flash, Flex *Microsoft Silverlight (Moonlight port)
{ "language": "en", "url": "https://stackoverflow.com/questions/7625453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Has facebook changed its image rendering logic recently? Since the past few months, I've been noticing that they tend to some kind of pixelated image first which then gets replaced by a much better image. Is this some kind of trick to reduce perceived latency by facebook? Or is it Chrome doing it? A: i think it's progressive image rendering. Quote from the linked blog Images already render progressively in a web browser -- but you can do even better. Simply save your GIF or PNG images with the "interlaced" option, or your JPEG images with the "progressive" option. A: This blog might answer your query - checkout following links - Image Optimization Part 3: Four Steps to File Size Reduction Image Optimization Part 4: Progressive JPEG…Hot or Not?
{ "language": "en", "url": "https://stackoverflow.com/questions/7625455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Determining the location of Top Of Stack I am trying to create an array based implementation of Stacks. I am a bit confused with where should the Top Of Stack (a variable in my implementation) be when, * *The list is empty *The list is full *The list is neither empty and not full Please help me out. Thanks. A: That depends only how you define TopOfStack: is it the first unused slot? Or is it the last thing pushed onto the stack. As soon as you choose one of those two options the rest can be deduced easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using sql rowcount in limit query My Table looks like this: id | Value ----------- 1 | High 2 | Medium 3 | Low 4 | Low My php query looks like this: $sqlquery = "select id from db_name order by id desc limit 3"; $fetchres = mysql_query($sqlquery); if(mysql_num_rows($fetchres)>0){ while($result = mysql_fetch_array($fetchres)) { if($result['history']=='High'){?> <div style="background:#FF0000; width:50px; height:50px; vertical-align:middle;float:left;margin:0 10px 0 0"> </div>&nbsp; <?php } else if($result['history']=='Medium') {?> <div style="background:#FF0; width:50px; height:50px; vertical-align:middle;float:left;margin:0 10px 0 0"> </div>&nbsp; <?php } else if($result['history']=='Low') {?> <div style="background:#090; width:50px; height:50px; vertical-align:middle;float:left;margin:0 10px 0 0"> </div> &nbsp; But it displays the results wrong block 1 should be at block 3 and vice versa, block 2 stays where it currently is. making sql query "asc" does not help, it only shows first 3 results and i need this to keep history of last three. So my question is can you use something like rowcount within the sql query limit, if not how to correct the code to display it correctly. A: In your SQL query yuo are selecting only id column select id from Then you are comparing string values with non-existing index history from your result. Correct this first and see if this will produce your desired result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Can you reference a non-static method in a static context? Use of delegates follows the same rules as calling methods - you can only refer to a method via a delegate if you are allowed to call that method explicitly, which means you cannot reference a non-static method from a static method, even if you don't actually call it. Is there a way around that? Here is some code used in performing the Bowling Kata, with my ideal lines of code shown in comments. I was forced to go through a static call (and anonymous static method declarations) to make the Frame Class code declarative to my liking: public int FrameScore() { return scorer[FrameType()](this); // I would like it to be // return this.scorer[FrameType()](); } static Dictionary<LinkedFrame.FrameTypeEnum, Func<LinkedFrame, int>> scorer = new Dictionary<LinkedFrame.FrameTypeEnum, Func<LinkedFrame, int>>() { {LinkedFrame.FrameTypeEnum.Strike, frame => frame.StrikeScore()}, {LinkedFrame.FrameTypeEnum.Spare, frame => frame.SpareScore()}, {LinkedFrame.FrameTypeEnum.Regular, frame => frame.RegularScore()} // I would like an element to be // {LinkedFrame.FrameTypeEnum.Strike, StrikeScore} }; private int RegularScore() { return this.Sum; } private int SpareScore() { ... } private int StrikeScore() { ... } So in some contexts it would make sense to reason about non-static methods in a static context. Is there a way to do this? A: Maybe open instance delegates will help? According to MSDN: Delegate Class: When a delegate represents an instance method closed over its first argument (the most common case), the delegate stores a reference to the method's entry point and a reference to an object, called the target, which is of a type assignable to the type that defined the method. When a delegate represents an open instance method, it stores a reference to the method's entry point. The delegate signature must include the hidden this parameter in its formal parameter list; in this case, the delegate does not have a reference to a target object, and a target object must be supplied when the delegate is invoked. What it comes down to, is that you can sneakily convert an instance method to a static method with an explicit this parameter. You can see how it's done here: Simon Cooper: Introduction to open instance delegates A: An instance method always requires an instance to be invoked with. If you want to invoke an instance method through a delegate, you have two options: * *The delegate captures the instance in some way. *You need to pass the instance to the delegate. You seem to want to have a delegate that does not capture an instance and does not require an instance to be passed. That's not possible in C#.
{ "language": "en", "url": "https://stackoverflow.com/questions/7625474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }