text
stringlengths
8
267k
meta
dict
Q: Android custom WebView is failing to find javascript functions defined in loaded HTML I have an Android WebView. I pass HTML to it (as a String). This HTML contains some basic javascript. Upon load, the HTML attempts to call a javascript function (defined in the <head></head>). This works fine in my browser desktop so I'm sure the HTML/Javascript itself is fine, but it fails to work when I load the same HTML into my WebView. Here is how I instantiate the WebView: WebView view = new WebView(context); WebSettings settings = view.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(false); view.setWebChromeClient(new CustomWebChromeClient()); view.setWebViewClient(new CustomWebViewClient()); view.loadData(ARBITRARY_HTML, "text/html", "utf-8"); The loaded HTML is: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>My head hurts from head-desking</title> <style type="text/css"> #content { display: none; } </style> <script type="text/javascript"> //<!-- function ShowContent() { document.getElementById('content').style.display = 'block'; } //--> </script> </head> <body onload="ShowContent()"> <div id="content"> This content should be shown, but isn't! </div> <div id="other"> All I see is this content... and that makes me question my self worth. </div> </body> </html> This produces (on Android only) the runtime javascript error: "Uncaught ReferenceError: ShowContent is not defined". A: I have an assumption. The //<!-- ... //--> technique which is a made up hack for really old browsers is so out of date. Try to remove that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Prime numbers iterator I wrote a piece of code to print n prime numbers: class PrimeGen: def __init__(self): self.current = 2 def genPrime(self, num): for i in range(num): while 1: for j in range(2, self.current/2 + 1): if self.current % j == 0: self.current = self.current + 1 break else: break print self.current, self.current = self.current + 1 if __name__ == '__main__': p = PrimeGen() p.genPrime(5) The code works fine. I get 2 3 5 7 11 as output. I tried to make the class iterable. Code below. But the output is 0 1 2 3 4. I could not quite figure out where I am going wrong. Any help is appreciated. Thanks class PrimeIter: def __init__(self): self.current = 1 def next(self): self.current = self.current + 1 while 1: for i in range(2, self.current/2 + 1): if self.current % i == 0: self.current = self.current + 1 break # Break current for loop else: break # Break the while loop and return return self.current def __iter__(self): return self if __name__ == '__main__': p = PrimeIter() for p in range (5): print p, A: You're using this code to print out the values: for p in range (5): print p, If you look at that, it's printing the values of the range. You probably want to print things from the prime iterator. itertools has some functions that may help: for prime in itertools.islice(p, 5): print prime, Additionally, you may want to consider using a generator: def primes(): current = 1 while True: current += 1 while True: for i in xrange(2, current // 2 + 1): if current % i == 0: current += 1 break else: break yield current A: Your problem is that you are reusing the variable p in your test code: if __name__ == '__main__': p = PrimeIter() # first declaration of p for p in range (5): # second declaration of p print p, # uses second declaration of p I'd recommend using itertools.islice to get the first 5 elements of an iterator: if __name__ == '__main__': p = PrimeIter() for x in itertools.islice(p, 5): print x, A: Iterator for generating prime numbers upto some maximum m: class PrimeIter: def ___init__(self, m): self.max = m def __iter__(self): self.n = 1 return self def __next__(self): if self.n < self.max: self.n += 1 i = 2 while i < (self.n//2+1): if self.n % i == 0: self.n = self.n+1 if self.n > self.max: raise StopIteration i = 1 i += 1 else: return self.n else: raise StopIteration p = PrimeIter (100) for i in p: print(i, end=' ')
{ "language": "en", "url": "https://stackoverflow.com/questions/7536655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript - accessing elements from an unopened page My question is somewhat difficult to explain. What I am trying to do is, I have a button on a certain page. When I press that button, I must be able to access elements of a form that is located on another page (without having the other page open). Pressing that button will edit some of the elements in the form from that "unopened" page, and then post it, all this without opening any extra popup/tab/window. After the form has been posted, the button will disappear. The form in question contains unique parameters that can't be retrieved without accessing its particular page, so I cannot emulate the form in standalone. Some of my guesses are to use a dynamic iframe set to "display: none", or Ajax, but otherwise I'm not exactly sure if it is possible and how to do it. Would anybody have some ideas? (sorry if the question isn't very clear, I tried my best to describe the problem) A: Try using frameset. given below sample code which have 3 pages 1. page 1 is the parent document which contains two frames. 2.frame1 refers to page2 3.frame2 refers to page3 test1.htm <html> <head> <title>test</title> <frameset rows="25px,*" frameborder="0" framespacing="0" > <frame name="Frame2" id="Frame2" src="test2.htm"/> <frame name="Frame1" id="Frame1" src="test3.htm"/> </frameset> </head> </html> test2.htm <html> <script> var global="testing" </script> </html> test3.htm <html> <script> alert(parent.window.frames[0].global); parent.window.frames[0].global="local" function test() { alert(parent.window.frames[0].global); } </script> <body> <input type="button" onclick="test()" /> </body> </html> In the page test2 the value of global can be change from the page test3.htm. A: I did it this way, using jQuery: * *Acquire HTML code from the form page using $.get() *Extract the form node from the HTML string *Create an hidden iframe *Parse the form's HTML inside the new iframe *Modify the form's values; *"URLEncode" the form's data using jQuery's .serialize(); *Post the serialized data to the target using $.post(), with a callback function receiving the response *If response indicates success, hide the button and remove the hidden iframe I decided to extract the form out of the HTML string returned by $.get(), since parsing it won't require to load the whole form page before using the actual form as an object. Using an hidden iframe for parsing is probably not the most "professional" way, but it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hibernate is ignoring my persist calls? i have one weird problem. No matter what i do, i cant put new record in database via hibernate. I'm using Hibernate with Tapestry and MySQL. Please someone help me! I have UserDAO class with this piece of code: @CommitAfter public boolean saveUser(User user){ try { session.persist(user); return true; }catch(Exception e){ return false; } } And then i call it here: @OnEvent(component="add") Object onAdd(){ if(username!=null && password!=null){ User user = new UserBean(); user.setUsername(username); user.setPassword(password); userService.saveUser(user); } if(eventName!=null){ Event event = new EventBean(); event.setName(eventName); eventService.saveEvent(event); } return this; } But its not working, i dont know why, please help! Here is full project: http://www.mediafire.com/?pqb2aaadhbukuav I added this piece of code in AppModule.java and now it works @Match("*DAO") public static void adviseTransactions(HibernateTransactionAdvisor advisor, MethodAdviceReceiver receiver) { advisor.addTransactionCommitAdvice(receiver); } Can anyone explain to me what is this code doing? This is not my first time working with hibernate and tapestry, and i never saw this before, so i don't understand? Please anyone A: The @CommitAfter annotation only works in page/component classes by default. To get the same behaviour in service objects, you need that extra piece of code. This is covered by the second half of this page from the user guide. Can anyone explain to me what is this code doing That code looks for @CommitAfter annotations in any services having a name that matches @Match("*DAO"). It then applies the HibernateTransactionAdvisor, which adds a commit() call if the annotated method exits successfully. This is done using some of Tapestry's AOP-like meta-programming features. A: Can you log the exception in the saveUser method - if something is going wrong in the persist you won't know about it because you are ignoring the exception. If an exception is being thrown it might help find the problem. The other problem could be transaction management - if you are using hibernate directly you will need to call the persist method inside a transaction. Without it the changes might be ignored.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to make cursor move backward/forward in QT? I am with an input method project by QT on meego. here is a case: if user input "(" in inputing widgets, a ")" should displayed too. you know, at that moment, cursor is in the position after ")", but it should be between brackets. what should I do ? with QT A: OK, I found the right way: QEvent *movePress= new QKeyEvent(QEvent::KeyPress, Qt::Key_Left, Qt::NoModifier); QApplication::sendEvent (focusWidget, movePress); QEvent *moveRelease= new QKeyEvent(QEvent::KeyRelease, Qt::Key_Left, Qt::NoModifier); QApplication::sendEvent(focusWidget,moveRelease);
{ "language": "en", "url": "https://stackoverflow.com/questions/7536660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to build Android kernel to use DS-5 streamline? I am tying to use ARM DS5 Streamline for Android. To use Streamline with your Android target, you must build the Gator driver, gator.ko and place it in the same directory as the Gator daemon, gatord, on the target file system. Transfer the gator driver module sources from your host to the target. They are located on your host here: installdir/arm/gator/src/gator-driver.tar.gz Assuming that you have unzipped the file and that you have all of the required tools for building kernel modules, enter the following command on your target to create the gator.ko module: make -C kernel_build_dir M=pwd ARCH=arm CROSS_COMPILE=<...> modules I got this from ARM website. They say "target", are they meaning Android devices? Do I go through these steps on Android devices? Also what do they mean by kernel_build_dir? I know I could find kernel dir for my desktop linux machine. But I don't think I should pass my desktop machine's kernel directory as the parameter. A: target is the device on which you are going to use Android. host is the machine on which you are compiling this driver/Android. No, you have to compile kernel with drivers on your host machine and then upload it to your target device. Kernel build directory is the directory that contains Linux kernel source codes. You will probably have to use some specific kernel version to be sure you are able to successfully compile your drivers, but your kernel would be okay too. Just read the how-to. I hope, I have answered all your questions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are there any SMS gateways for only sending messages that don't require buying a short code? I need to send SMS messages from my app to users with status updates, but I don't like the "send an email to their phone numbers" route because the messages typically includes lots of cruft (like "FRM" and "MSG" and other random things). I know I could get my own short code and use a service like Twilio or Clickatell, but short codes are out of my price range right now. So are there any SMS gateways that let me use some sort of generic, random short code for only sending messages? I don't need any ability for users to reply to the text. A: At work we use RedOxygen for sending SMS messages. They don't require you to have a short code and sending using their gateway uses a phone number on their side. They do allow you to obtain responses to your SMS's via a limited API as well. Feel free to shop around though, this isn't an endorsement. A: Here are a few options for you, all with varying APIs: * *tropo.com *torpedeiro.com *twilio.com *springedge.com Probably also depends on where your users are, pretty sure Twilio only service US & Canada. A: Global SMS delivery doesn't rely on having short codes available in each country you're targetting so many SMS Gateways will allow you to send from a 'broadcast' account without the necessity to rent a shortcode. Renting a shortcode would only be really necessary if you wanted inbound traffic too which you've stated you don't. Sending an SMS using an 11 character alphanumeric identifier is possible in many countries and for those with delivery restrictions requiring sending through shortcodes then the SMS Gateway should do the work for you to ensure your message is delivered whatever the restrictions. [Disclaimer: I work for Esendex, a global SMS Gateway] A: You can connect to any of the SMS Providers or SMS Gateways (either local or Global), and ask them to provide you an HTTP or XML API. Then you can make your system capable of sending auto SMS using these APIs. This must work
{ "language": "en", "url": "https://stackoverflow.com/questions/7536663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fetching multiple rows with specific IDs? I want to fetch some specific rows from MySQL database using multiple ids, for example if I have to select only rows 201,567,991 etc... like this $sql_query = "SELECT * from tbl_name WHERE id = '201', '567', 'id-etc.'"; is it possible in MySQL? A: IN() should do the trick. Just put your list of numbers inside the brackets like so: $sql_query = "SELECT * from tbl_name WHERE id IN(1, 2, 3, ...)"; You don't need to quote numbers going into INT fields, however it's a very good idea to cast any variables to int, to minimise security vulnerability: $var = (int)$var; If you're using strings, however, do quote them as you normally would. A: Yes. Use IN Link $sql_query = "SELECT * from tbl_name WHERE id IN ('201', '567')"; A: Use tge "IN" operator as in:| SELECT * from tbl_name WHERE id In ('201', '567', 'id-etc.')
{ "language": "en", "url": "https://stackoverflow.com/questions/7536666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple hasMany relationships to same domain class in Grails I'm using Grails, and I have a domain model with multiple hasMany attributes to the same domain class, which looks like this: static hasMany = [ posts : Post, likes : Post, dislikes : Post ] The problem that I'm running into is that when I add something to the posts list, it also somehow makes it into the likes and dislikes lists. At least, that's how it looks when I iterate through each of those lists. I think that the issue is that I also have the following relationship in my Post domain: static belongsTo = [ contributer : Contributer ] What is the best way of going about configuring these relationships to make my model work? Any suggestions? @Wayne, I tried using your test as well, and it passed successfully. So, the only thing that I can think of is that there is something wrong with my save method in my PostController. I have pasted the relavent code below (I am using the Spring Security Core plugin, and my Contributer class extends the User class that is created with that plugin): @Secured(['IS_AUTHENTICATED_FULLY']) def save = { def props = [title:params.title, post:params.post, category:Category.get(params.category.id)] def user = Contributer.get(springSecurityService.principal.id) def postInstance = new Post(props) postInstance.contributer = user if (postInstance.save(flush: true)) { flash.message = "${message(code: 'default.created.message', args: [message(code: 'post.label', default: 'Post'), postInstance.id])}" redirect(action: "show", id: postInstance.id) } else { render(view: "create", model: [postInstance: postInstance]) } } Is there anything that stands out here? A: Use static mappedBy in your domain class For example: In many side domain object (Contributer.groovy): static hasMany = [ posts : Post, likes : Post, dislikes : Post ] static mappedBy = [posts: "postsContributer", likes: "likesContributer", dislikes: "dislikesContributer"] In one side domain object (Post.groovy): Class Post { static belongsTo = [ contributer : Contributer ] Contributer postsContributer Contributer likesContributer Contributer dislikesContributer ... } A: Though, standard way for multi-M:M is to use joinTable, as recommended in GRAILS-4884. A: The problem is that you have a one to many between Post and Contributor (post has an author, author has many posts) as well as two many to many relationships between Post and Contributor (post has many likers, likers like many posts) (post has many dislikers, dislikers dislike many posts). The belongsTo in Post does explain the behavior, but removing it will not fix the problem, just create different ones. The end result is that GORM conventions are going to fall short so you have to tell GORM how to behave or model things differntly. There are several options, but the one that jumps to mind is to model Vote separately from Post and make it so that a Contributor hasMany likeVotes and hasMany dislikeVotes class Vote { // for illustration here, you need to think about the // cascading behavior that makes sense and model it if you decide // to go this route. belongsTo = [post, contributor] } class LikeVote extends Vote { } class DislikeVote extends Vote { } GORM will model this as one vote table with a discriminator column to separate likes and dislikes; this will let you eliminate the conflicts between likes, dislikes, and authored posts. Then in Contributor hasMany = [likes:LikeVote, dislikes:DislikeVote, posts:Post] The relationships are cleared up now: * *Post has many likeVotes *Post has many dislikeVotes *Contributor has many likeVotes *Contributor has many dislikeVotes *Post has one contributor *Contributor has many posts GORM can understand these relationships and will behave appropriately. If you don't like this option, the next step would be to specify custom mappings for your database structure and then use mappedBy to differentiate the various relationships. This is the approach to take if you absolutely want to have a Contributor relate directly to Post in three different ways. A: Can you show the test case that fails? I put what I think is your case into a grails 1.3.7 project, and the test passes: class Post { String text ="postal" static belongsTo = [ contributor : Contributor ] static constraints = { } } class Contributor { String name = "Big C" static hasMany = [ posts : Post, likes : Post, dislikes : Post ] static constraints = { } } // integration test void testMultipleRel() { Contributor c = new Contributor().save() assertNotNull c Post p1 = new Post(text:"neutral") Post p2 = new Post(text:"like") Post p3 = new Post(text:"dislike") [p1,p2,p3].each {c.addToPosts(it).save()} assertNotNull p1 assertNotNull p2 assertNotNull p3 assertNull c.likes assertNull c.dislikes c.addToLikes(p2) c.addToDislikes(p3) assertEquals ([p1, p2, p3] as Set, c.posts as Set) assertEquals ([p2] as Set, c.likes as Set) assertEquals ([p3] as Set, c.dislikes as Set) } A: Try switching to a many-to-many relationship and define a mapping domain class. In this mapping domain class you can then specify the type of relationship; like, dislike, or author. class Contributor { static hasMany = [contributorPosts:ContributorPost] } class ContributorPost { Post post Contributor contributor Boolean like Boolean dislike Boolean author } class Post { static hasMany = [contributorPosts:ContributorPost] } You can look here http://www.grails.org/Many-to-Many+Mapping+without+Hibernate+XML for further information on a many-to-many mapping domain class. A: This should works: static hasMany = [ posts : Post, likes : Post, dislikes : Post ] static mapping = { posts joinTable: [name: 'contributor_posts'] likes joinTable: [name: 'contributor_likes'] dislikes joinTable: [name: 'contributor_dislikes'] }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Data Frames in R - NA values I'm trying to remove all the rows from my data frame in which the 3rd column is NA: new.frame <- data[(!is.na(data$z)),] But I'm getting an error. Warning message: In is.na(data$z) : is.na() applied to non-(list or vector) of type 'NULL' How can I accomplish this? A: Reproducible examples, please. Here is one that works: R> set.seed(42) R> DF <- data.frame(a=rnorm(10), b=sample(LETTERS, 10, replace=TRUE), +> z=cumsum(runif(10))) R> DF[c(2,4,6),"z"] = NA R> DF a b z 1 1.3709584 X 0.737596 2 -0.5646982 D NA 3 0.3631284 Z 1.936759 4 0.6328626 Y NA 5 0.4042683 C 2.625877 6 -0.1061245 N NA 7 1.5115220 K 3.466127 8 -0.0946590 X 3.673786 9 2.0184237 L 4.580388 10 -0.0627141 V 5.192166 R> new.frame <- DF[(!is.na(DF$z)),] R> new.frame a b z 1 1.3709584 X 0.737596 3 0.3631284 Z 1.936759 5 0.4042683 C 2.625877 7 1.5115220 K 3.466127 8 -0.0946590 X 3.673786 9 2.0184237 L 4.580388 10 -0.0627141 V 5.192166 R> A: There's also complete.cases() which may be easier to read. Using Dirk's data: new.frame2 <- DF[complete.cases(DF) ,] > all.equal(new.frame, new.frame2) [1] TRUE A: You can also use na.omit function on the whole dataset. A: Try this: new.frame.nonull <- data[(!is.null(data$z)),] new.frame <- new.frame.nonull[(!is.na(new.frame.nonull$z)),]
{ "language": "en", "url": "https://stackoverflow.com/questions/7536683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php url error code I define encoding in php file: header("Content-Type:text/html;charset=utf-8"); Now I write a link in my template file ( smarty ) <a href="http://www.test.cn/maternal_and_child/lists/中文测试">Link</a> By the way, '中文测试' is chinese.But when I click the link, it return error like this: The requested URL /maternal_and_child/app/webroot/lists/准备怀孕-优生优育 was not found on this server. How can I fix it? A: http://www.test.cn/maternal_and_child/lists/中文测试 is not a valid url. You should encode the url: http://www.test.cn/maternal_and_child/lists/%E4%B8%AD%E6%96%87%E6%B5%8B%E8%AF%95 A: Encode the URL with Smarty by using: {* assuming the template variable $url holds your url *} {$url|escape:'url'} Smarty escape docs
{ "language": "en", "url": "https://stackoverflow.com/questions/7536687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Core Java and Advance Java (what's the difference?) I was googling Java tutorials and related news to Java, until I saw this "Core Java" now I am wondering what really is core Java? And what's the difference with Advanced Java? Is that another Java programming language? What are the topics under Core Java? And Advanced Java? BTW can you suggest a good book for learning Advanced Java and Core Java? My first book was Java how to program 8th edition, and basically I know the fundamentals already. So all I need is another book to learn Core Java and Advanced Java. And is core Java the same as Java EE? What is a good book to learn Java EE? A: This Core / Advanced distinction in the tutorials should be viewed as being purely about learning about Java, and what order it is advisable to learn things. I am wondering what really is Core Java? It is the basic stuff you should learn first. and what's the difference with Advanced Java? Advanced Java is the stuff that you shouldn't try to understand until you are comfortable with the basics. is that another Java programming language? No. And it is not a different library. In fact, you won't see the core/advanced distinction in the documentation or packaging of the language or libraries. (According to one interpretation, "Core Java" is everything in Java SE ... but frankly, that is not a useful classification; see below.) what are the topics under Core Java? and Advanced Java? There is no absolute answer to this. It depends on who has made the classification. The best thing is to look at the table of contents for the book, tutorial, course syllabus, whatever. Independently of the above, Oracle also uses the phrase "Core Java technologies" in marketing / PR documents to refer to the stuff in Java SE. Here is an example: * *Java SE Core Technologies This says: The Core Java technologies and application programming interfaces (APIs) are the foundation of the Java Platform, Standard Edition (Java SE). ... without saying clearly what they are referring to. The take-away (for me is that "Java Core" versus other things is an imprecise classification. Some of the stuff that is included in the "core" technologies (see above link) are either specialized or (more or less) legacy technology. With Java 8 they have started to modularizing the Java APIs (c.f. the "compact profiles") and this is moving forward with Java 9 modules, and the deprecation of parts of CORBA support. Then if you look in the various official Oracle Java Glossaries; e.g. * *Oracle Technology Network > Java > Glossary *J2EE 1.4 Glossary you probably won't find a definition for "Core Java". (I couldn't!) All of this means that in reality when you see a Job or Position Description that calls for "Core Java", it probably means that person who wrote it probably does not mean "Core Java" in the sense of the Java SE Core Technologies page. (Or if they do mean that, then they are unrealistic about the actual job requirements!) A: Note that core!=basic. * *Core Java - J2SE *Non-core Java - everything else that is not J2SE (J2EE, JAI, JOGL, JMF, ..) *Advanced Java - made up term with a different meaning for everyone that is asked. A: For Java EE I would start with an online tutorial, just so you can get familiar with parts, and decide if you need a book, and what parts of Java EE you want to get more information on. http://java.sun.com/javaee/6/docs/tutorial/doc/ For Core java I think this is nice: http://download.oracle.com/javase/tutorial/ As to which books to get, once you have gone through these you will get an idea where you want to focus more. For example, do you want to get better at graphics or concurrency? There are books more geared toward these. Perhaps you want to understand JavaServer Faces, then you can get a book on that. You stated you know the fundamentals, but that is a pretty broad area, so you may want to first go through and not only have read about these topics, but experiment with them, so you can know what you do and don't know.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Recommended method to load application drop down / look ups / reference data in Spring What method do you recommend to load application data such as list of medications or countries or states or other typically reference data into a database? Currently I'm using spring and an in memory database (HSQL) however, I will move to a more traditional relational database. I'm relatively new to spring/java so don't assume to0 much. In .net I typically had a cmd script to create and reload the database wheneverI needed..but that might be difficult to do with an in memory database and I also wonder if there a typical spring/java means of getting this done. Thanks A: http://www.dbunit.org/ is a good option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AS3: Cannot type in an input TextField with an embedded pixel font In order to use a pixel font in my textfields, I have created a font class in the Flash IDE. Then, I created a TextField instance with the font embedded with the anti aliasing set to bitmap. I export an SWC with all those things. I created a class with a nice API to be able to deal with this stuff easily. In FDT, I use class and this all works properly. The issue here is that I now want to use one of these textfields as an input. I tried setting the textfield type to TextFieldType.INPUT, however the only thing that this does is allow me to select the text, I cannot type. I also created another asset with the type already set to input, does not work either. I tried with just the asset, not with my class, and then I can type ok. Is there something that prevents a textfield from being editable once it is part of a sprite? Here is the code of my class with the API: package net.jansensan.as3fflikeui.text { // + ---------------------------------------- // [ IMPORTS ] // + ---------------------------------------- import flash.display.MovieClip; import flash.display.Sprite; import flash.events.Event; import flash.text.StyleSheet; import flash.text.TextField; import flash.text.TextFieldType; /** * @author Mat Janson Blanchet */ public class BitmapTextfield extends Sprite { // + ---------------------------------------- // [ CONSTANTS ] // + ---------------------------------------- [Embed(source="../assets/css/ui.css", mimeType="application/octet-stream")] private const CSS :Class; // + ---------------------------------------- // [ VARIABLES ] // + ---------------------------------------- // display objects private var _textfieldAsset :MovieClip; private var _textfield :TextField; private var _shadow :BitmapTextfieldAsset; // private / protected private var _styleSheet :StyleSheet; // + ---------------------------------------- // [CONSTRUCTOR ] // + ---------------------------------------- public function BitmapTextfield(type:String = TextFieldType.DYNAMIC) { switch(type) { case TextFieldType.DYNAMIC: _textfieldAsset = new BitmapTextfieldAsset(); _textfield = _textfieldAsset.textfieldTXT; _textfield.selectable = false; break; case TextFieldType.INPUT: _textfieldAsset = new BitmapInputTextfieldAsset(); _textfield = _textfieldAsset.textfieldTXT; _textfield.selectable = true; break; } _textfield.htmlText = ""; _shadow = new BitmapTextfieldAsset(); _shadow.textfieldTXT.htmlText = ""; _shadow.x = 1; _shadow.y = 1; _styleSheet = new StyleSheet(); _styleSheet.parseCSS(new CSS()); setStyle(_styleSheet); addChild(_shadow); addChild(_textfieldAsset); } // + ---------------------------------------- // [ PUBLIC METHODS ] // + ---------------------------------------- public function setWidth(newWidth:int):void { _textfield.width = newWidth; _shadow.textfieldTXT.width = newWidth; } public function setHeight(newHeight:int):void { _textfield.height = newHeight; _shadow.textfieldTXT.height = newHeight; } public function setStyle(newStyle:StyleSheet):void { _styleSheet = newStyle; _textfield.styleSheet = _styleSheet; } public function setText(newText:String):void { _textfield.htmlText = newText; _shadow.textfieldTXT.htmlText = newText; } public function getText():String { return _textfield.text; } public function getHTMLText():String { return _textfield.htmlText; } public function getTextNumLines():uint { return _textfield.numLines; } } } Any guidance would be useful, thanks in advance! -mat. A: A text field with a style sheet is not editable. In other words, a text field with the type property set to TextFieldType.INPUT applies the StyleSheet to the default text for the text field, but the content will no longer be editable by the user. Consider using the TextFormat class to assign styles to input text fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extjs store.save() not recognize update I follow instruction in writer to create grid with CRUD ability, but the problem is when I edit existing row and save() it recognize that dirty row as create, I think the problem may lie in my idProperty as in link, but can't figure out how. Here is my code Column model var xsmWin = new Ext.grid.CheckboxSelectionModel({checkOnly:true}); var xcmWin = new Ext.grid.ColumnModel([ xsmWin, new Ext.grid.RowNumberer(), {header: 'id', dataIndex: 'finCol0', align: 'left', hidden: true, hideable: false, sortable: false, width: 70}, {header: 'column name', dataIndex: 'finCol2', align: 'left', hidden: false, hideable: false, sortable: true, width: 100, editor: new samart.form.xTextField({allowBlank: false})}, {header: 'input type', dataIndex: 'finCol3', align: 'left', hidden: false, hideable: false, sortable: true, width: 100}, {header: 'approve', dataIndex: 'approveFlag', align: 'center', hidden: false, hideable: false, sortable: true, width: 50}, ]); Proxy var proxyWin = new Ext.data.HttpProxy({ api : { read : { url : SERVLET_URL + '&action=loadInnerDataGrid', method: 'POST' }, create : { url : SERVLET_URL + '&action=createInnerData', method: 'POST' }, update : { url : SERVLET_URL + '&action=updateInnerData', method: 'POST' }, destroy : { url : SERVLET_URL + '&action=destroyInnerData', method: 'POST' } } }); Reader and Writer var writerWin = new Ext.data.JsonWriter({ encode: true, writeAllFields: false }); var readerWin = new Ext.data.JsonReader( { idProperty: 'finCol0', root: 'data' },[ {name: 'finCol0',mapping:'fundHeadSeq'}, //{name: 'finCol1',mapping:'fundType'}, {name: 'finCol2',mapping:'headLabel'}, {name: 'finCol3',mapping:'objectName'}, {name: 'approveFlag',convert: function(v, record){ if (record.approveFlag == 'Y') { return 'Yes'; } else if (record.approveFlag == 'N') { return 'No'; } }}, ] ) Store var xstoreWin = new Ext.ux.data.PagingStore({ storeId : 'xstoreWin', proxy : proxyWin, reader : readerWin, writer : writerWin, autoSave : false, autoLoad : true }); A: I have change idProperty : 'finCol0' to idProperty : 'fundHeadSeq' and {name: 'finCol0',mapping:'fundHeadSeq'}, to {name: 'fundHeadSeq',mapping:'fundHeadSeq'}, in JSONWriter and change {header: 'id', dataIndex: 'finCol0', align: 'left', hidden: true, hideable: false, sortable: false, width: 70}, to {header: 'id', dataIndex: 'fundHeadSeq', align: 'left', hidden: true, hideable: false, sortable: false, width: 70}, in column model and everything work as expected. A: I have a problem similar to yours. My IdProperty was 'user_id' and the writer create was never called. I changed to 'userId' and it work now. Very strange. I'm under Extjs 3.4.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: problem with an abstract type as class member variable I try to use a abstract class type as a member variable in my class definition, but somehow it has some problem. Here is the abstract class type: class POINT{ public: virtual int point_dim() = 0; /*other virtual functions...*/ } And here is the inherited class: class POINTX : public POINT{ public: int point_dim(){return 10;} } I create another class to use POINT as a member variable, since POINT is a pure virtual class, I can only declare it as a pointer: class SPACE{ public: POINT* m_point; /*some other declarations*/ } But when I use it in my main, it does not work as I expect: int main(){ POINTX *ptx = new POINTX(); SPACE space; space.m_point = (POINT*)ptx; //some function call use POINT as parameter(pass by reference): func(*space.m_point, ....); } error happened when func(space.m_pint) is invoked. However, if I do this without class SPACE, it's ok. e.g.: int main(){ POINTX *ptx = new POINTX(); POINT *m_point = (POINT*)ptx; //some function call use POINT as parameter(pass by reference): func(*m_point, ....); } Anyone knows what's wrong? A: POINT declares: virtual int point_dim() const = 0; Therefore POINTX must have a const method called point_dim: int point_dim() const {return 10;} Without this, it will have two point_dim() methods, one non-const and one const but pure virtual, leaving POINTX as abstract. As long as func() takes a reference to a POINT: int func(const POINT& pt) { const int dim = pt.point_dim(); // ... } You'll be able to call it like this: func(*space.m_point); Also, note that you don't need the C-style cast here: space.m_point = ptx; And don't forget to delete ptx when you're done!
{ "language": "en", "url": "https://stackoverflow.com/questions/7536711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Php MP3 Tag Processing I have a php script that I want to provide a list of music from. The files are named 01.mp3 02.mp3 and 03.mp3 and so on. They all have tag info. My question is how do I access that in my php script. A: You need a script to parse the mp3 file to acces to the data. From google: http://getid3.sourceforge.net http://www.codediesel.com/pear/reading-mp3-file-tags-in-php/ ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7536713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: FetchedResultsController-problem i've got a problem, that drives me crazy. I guess it should be fairly easy to solve, but i don't get it... I'm trying to setup a tableview with a fetchedResultsController, but for some reason the frc is returning a section-count of zero. Here is my code for the frc: - (NSFetchedResultsController *)fetchedResultsController { if (_fetchedResultsController != nil) { return _fetchedResultsController; } NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Kundendaten" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Kundenname" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"Kundenname" cacheName:@"Root"]; aFetchedResultsController.delegate = self; self._fetchedResultsController = aFetchedResultsController; [aFetchedResultsController release]; [fetchRequest release]; [sortDescriptor release]; [sortDescriptors release]; return _fetchedResultsController; } And here i'm trying to get the section-count: int count = [[[self fetchedResultsController] sections] count]; // at this point the count-variable is 0. the following is just to prove, that my moc isnt empty... Even if i set the sectionNameKeyPath to nil, it returns 0. NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Kundendaten" inManagedObjectContext:self.managedObjectContext]; NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; [request setEntity:entityDescription]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Kundenname" ascending:YES]; [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; [sortDescriptor release]; NSError *error = nil; NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error]; count = [array count]; return count; In this case, the count is 5... Does someone see, where the problem is? thx A: Well, looks like you've set up the fetch nicely, but you should probably actually DO the fetch.... NSError *error = nil; if (![aFetchedResultsController performFetch:&error]) { NSLog(@"Bad Fetch %@", error); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to install bitly on heroku running rails 2.3.5 I added this to environment.rb config.gem 'bitly' And I added this to .gems bitly But when I do "git push heroku" I get this error: -----> Installing gem bitly from http://gemcutter.org, http://rubygems.org ERROR: Error installing bitly: multi_json requires RubyGems version >= 1.3.6 ! Heroku push rejected, failed to install gem Any help is appreciated. A: .gems is deprecated on Heroku. As per the docs, you should be using Bundler instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting BAD ACCESS error when trying to insert an int into NSMutableArray I have this method here that turns integer inputs from two UITextFields into binary code: //assume anything that isn't allocated here has been taken care of in the header file -(IBAction)valuesChanged { while ((![input1.text isEqualToString:@""]) && (![input2.text isEqualToString:@""])) { if (bitRange.selectedSegmentIndex == 0) {flowLimit = 8;} else if (bitRange.selectedSegmentIndex == 1) {flowLimit = 16;} else {flowLimit = 32;} NSMutableArray* bin1 = [[NSMutableArray alloc] initWithCapacity:32]; NSMutableArray* bin2 = [[NSMutableArray alloc] initWithCapacity:32]; NSMutableArray* resBin = [[NSMutableArray alloc] initWithCapacity:32]; input1Decimal = [input1.text intValue]; input2Decimal = [input2.text intValue]; int decimalDummy = input1Decimal; while (decimalDummy > 0) { if (decimalDummy == 1) { [bin1 addObject:1]; decimalDummy--; } else { [bin1 addObject:(decimalDummy % 2)]; //this is where I get the error decimalDummy = decimalDummy/2; } } decimalDummy = input2Decimal; while (decimalDummy > 0) { if (decimalDummy == 1) { [bin2 addObject:1]; decimalDummy--; } else { [bin2 addObject:(decimalDummy % 2)]; decimalDummy = decimalDummy/2; } } while ([bin1 count] < flowLimit) {[bin1 addObject:0];} while ([bin2 count] < flowLimit) {[bin2 addObject:0];} NSString* string1 = @""; NSString* string2 = @""; for (int i = 0; i < flowLimit; i++) { string1 = [[bin1 objectAtIndex:i] stringByAppendingString:string1]; string2 = [[bin2 objectAtIndex:i] stringByAppendingString:string2]; } [output1 setText:string1]; [output2 setText:string2]; [bin1 release]; [bin2 release]; [resBin release]; } } I labeled the spot where I'm getting a bad access error. Anyone know why it's happening? A: Sure! You have to put objects in NSArrays. Plain ints aren't objects, they're primitive types. You can wrap them in NSNumbers if you want to put them in an NSArray: NSNumber *wrappedInt = [NSNumber numberWithInt:(decimalDummy % 2)]; [array addObject:wrappedInt];
{ "language": "en", "url": "https://stackoverflow.com/questions/7536724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ringtone is playing the default ringtone This has been changed from the original post. Basically what is happening is I have gotten this to display the ringtone in the ringtone list on the phone. It also selects it. In this code it plays the ringtone after it has been selected (I have taken it out to reduce the size). It seems to be playing the phones default ringtone. Any ideas why? Thanks private void ringtone(int p){ File newSoundFile = new File("/sdcard/media/ringtone", "raven.wav"); Uri mUri = Uri.parse("android.resource://com.fs.hh/"+R.raw.raven); ContentResolver mCr = getContentResolver(); AssetFileDescriptor soundFile; try { soundFile= mCr.openAssetFileDescriptor(mUri, "r"); } catch (FileNotFoundException e) { soundFile=null; } try { byte[] readData = new byte[1024]; FileInputStream fis = soundFile.createInputStream(); FileOutputStream fos = new FileOutputStream(newSoundFile); int i = fis.read(readData); while (i != -1) { fos.write(readData, 0, i); i = fis.read(readData); } fos.close(); soundFile.close(); } catch (IOException io) { } ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, "my ringtone"); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/wav"); values.put(MediaStore.MediaColumns.SIZE, newSoundFile.length()); values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name); values.put(MediaStore.Audio.Media.IS_RINGTONE, true); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); values.put(MediaStore.Audio.Media.IS_ALARM, true); values.put(MediaStore.Audio.Media.IS_MUSIC, false); Uri uri = MediaStore.Audio.Media.getContentUriForPath(newSoundFile.getAbsolutePath()); mCr.delete(uri, MediaStore.MediaColumns.DATA + "=\"" + newSoundFile.getAbsolutePath() + "\"", null); Uri newUri = mCr.insert(uri, values); RingtoneManager.setActualDefaultRingtoneUri(Soundboard.this, RingtoneManager.TYPE_RINGTONE, newUri); } I have also tried adding a / after ringtone and making it get the byte size. Neither have worked. I have also tried this piece of code instead and it causes the same problem. It shows up selected in the notification section, but the sound being played is not the correct sound. It sounds like a default ringer. private boolean setRingtone(int p){ int ressound = whichSound(p); //The R.raw.sound String fileTitle = fileTitle(p); // sound String soundTitle = soundTitle(p); // Sound byte[] buffer=null; InputStream fIn = getBaseContext().getResources().openRawResource(ressound); int size=0; try { size = fIn.available(); buffer = new byte[size]; fIn.read(buffer); fIn.close(); } catch (IOException e) { // TODO Auto-generated catch block return false; } String path="/sdcard/media/notification"; String filename=fileTitle+".wav"; boolean exists = (new File(path)).exists(); if (!exists){new File(path).mkdirs();} FileOutputStream save; try { save = new FileOutputStream(path+filename); save.write(buffer); save.flush(); save.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block return false; } catch (IOException e) { // TODO Auto-generated catch block return false; } sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename))); File k = new File(path, filename); ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, soundTitle); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/wav"); values.put(MediaStore.Audio.Media.ARTIST, "HH"); values.put(MediaStore.Audio.Media.IS_RINGTONE, false); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); values.put(MediaStore.Audio.Media.IS_ALARM, false); values.put(MediaStore.Audio.Media.IS_MUSIC, false); //Insert it into the database Uri newUri= this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values); RingtoneManager.setActualDefaultRingtoneUri( this, RingtoneManager.TYPE_NOTIFICATION, newUri ); return false; } A: Here is what finally fixed it. private boolean setRingtone(int p){ int ressound = whichSound(p); String fileTitle = fileTitle(p); String soundTitle = soundTitle(p); byte[] buffer=null; InputStream fIn = getBaseContext().getResources().openRawResource(ressound); int size=0; try { size = fIn.available(); buffer = new byte[size]; fIn.read(buffer); fIn.close(); } catch (IOException e) { // TODO Auto-generated catch block return false; } String path=Environment.getExternalStorageDirectory().getPath()+"/media/ringtone/"; String filename=fileTitle+".wav"; boolean exists = (new File(path)).exists(); if (!exists){new File(path).mkdirs();} FileOutputStream save; try { save = new FileOutputStream(path+filename); save.write(buffer); save.flush(); save.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block return false; } catch (IOException e) { // TODO Auto-generated catch block return false; } sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename))); File k = new File(path, filename); ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, soundTitle); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/wav"); values.put(MediaStore.Audio.Media.ARTIST, ""); values.put(MediaStore.Audio.Media.IS_RINGTONE, true); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); values.put(MediaStore.Audio.Media.IS_ALARM, false); values.put(MediaStore.Audio.Media.IS_MUSIC, false); //Insert it into the database Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()); getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null); Uri newUri = getContentResolver().insert(uri, values); RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri); return false; } In the path String by adding Environment.getExternatStorageDirectory().getPath() instead of just the sdcard it was actually able to play the sound and work properly. A: Uri mUri = Uri.parse("android.resource://com.packange.name/"+R.raw.raven); "com.packange.name" should be the name of your package, I assume you haven´t called it like that. Hardcode your package name, or call getPackageName() from a proper context. Update: You can get an uri out of your newSoundFile object, just do Uri.fromFile( newSoundFile ).
{ "language": "en", "url": "https://stackoverflow.com/questions/7536726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unable to add domain users to Sql Server login I have configured SQL Server 2008 R2 for mixed mode authentication on a Windows Server 2008 R2 box. I have logged in using domain administrator account into Windows as well as into Sql Server. Now I am trying to add another domain user account as a new login but I am getting the error saying "Windows NT user or group '\' not found. Check the name again. (Microsoft SQL Server, Error: 15401)" though this user is present in domain. I am adding using Management Studio -> Logins -> New Login. When I search for the domain user using the search button the system searches successfully for the user but when I click ok button to create the login I get the above error. I have tried using T-SQL also to create the login but with the same error. Need help!! A: The problem was with SIDs. As we were using VMs the SID was the same and this was causing the error. After changing the SID using sysprep the problem got resolved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does my [HttpPost] method not fire? I have created one page in MVC 3.0 Razor view. Create.cshtml @model LiveTest.Business.Models.QuestionsModel @*<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>*@ @using (Html.BeginForm()) { @Html.ValidationSummary(true) <table cellpadding="1" cellspacing="1" border="0"> <tr> <td>@Html.LabelFor(model => model.TestID) </td> <td> @Html.DropDownListFor(model => model.TestID, (IEnumerable<SelectListItem>)ViewBag.ItemIDList)@Html.ValidationMessageFor(model => model.TestID) </td> </tr> <tr> <td>@Html.LabelFor(model => model.Question) </td> <td>@Html.EditorFor(model => model.Question)@Html.ValidationMessageFor(model => model.Question) @Html.HiddenFor(model => model.QuestionsID) </td> </tr> <tr> <td>@Html.LabelFor(model => model.IsRequired) </td> <td>@Html.CheckBoxFor(model => model.IsRequired)@Html.ValidationMessageFor(model => model.IsRequired) </td> </tr> <tr> <td> </td> <td> <input type="submit" value="Submit" /> </td> </tr> </table> } QuestionsController.cs public class QuestionsController : Controller { #region "Attributes" private IQuestionsService _questionsService; #endregion #region "Constructors" public QuestionsController() : this(new QuestionsService()) { } public QuestionsController(IQuestionsService interviewTestsService) { _questionsService = interviewTestsService; } #endregion #region "Action Methods" public ActionResult Index() { return View(); } public ActionResult Create() { InterviewTestsService _interviewService = new InterviewTestsService(); List<InterviewTestsModel> testlist = (List<InterviewTestsModel>)_interviewService.GetAll(); ViewBag.ItemIDList = testlist.Select(i => new SelectListItem() { Value = i.TestID.ToString(), Text = i.Name }); return View(); } [HttpPost] public ActionResult Create(QuestionsModel questions) { if (ModelState.IsValid) { _questionsService.Add(questions); return RedirectToAction("Index"); } InterviewTestsService _interviewService = new InterviewTestsService(); List<InterviewTestsModel> testlist = (List<InterviewTestsModel>)_interviewService.GetAll(); ViewBag.ItemIDList = testlist.Select(i => new SelectListItem() { Value = i.TestID.ToString(), Text = i.Name }); return View(questions); } #endregion } QuestionsModel.cs public class QuestionsModel : IQuestionsModel { [ReadOnly(true)] public Guid QuestionsID { get; set; } [Required] [DisplayName("Question")] public string Question { get; set; } [DisplayName("Test ID")] public Guid TestID { get; set; } [DisplayName("Is Required")] public bool IsRequired { get; set; } [DisplayName("Created By")] public Guid CreatedBy { get; set; } } Problem: <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> If I am adding the above two lines in Create.cshtml page and then I press submit button then it will fire validation message "Question is required!" if I am entering value in *Question field and then press submit button my [HttpPost]Create Method never execute.* If I remove the above two lines from page then press submit button then it will execute [HttpPost]Create Method and fire validation from server side if I am entering value in Question field then also [HttpPost]Create executed. Please help me. A: I would check if any client side errors occurred when trying to submit the form. Check it from the browser console. Also, make sure that you have completed your code with no validation errors before submitting the form. A: Are you saying that the form doesn't validate client side and nothing ever get's POSTed back to your server? Meaning, you click the submit button and nothing happens in the browser, correct? The problem might be that your form isn't validating with the unobtrusive javascript library validation. A: The QuestionsModel class includes a property CreatedBy which is not included in your View. Try either adding CreatedBy as a hidden field, or (better yet) remove CreatedBy from the QuestionsModel class, since it is not an attribute which should be exposed in the view. I suspect that this missing property is the cause of the problem. UPDATE I ran some tests on your code, and it was not the CreatedBy property. Rather, your problem is that you are not supplying a QuestionsID value, but you included a hidden field for QuestionsID on the form. Because QuestionsID is a value type, by default, the DataAnnotationsModelValidatorProvider adds a Required validator to the QuestionsID field. Because the field did not have a ValidationMessage, you could not see the validation error. You can override the behavior of the default DataAnnotationsModelValidatorProvider by following the instructions in my answer here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: A script im robot with xmpppy of python, how to detect network failure? I am using xmpppy libary to write a XMPP IM robot. I want to act on disconnects, but I don't know how to detect disconnects. This could happen if your Jabber server crashes or if you have lost your internet connection. I found the callback, RegisterDisconnectHandler(self, DisconnectHandler), but it didn't work for the network failure, it only works when I explicitly call the method "disconnect". How do I detect a network failure or server crash? A: Did you try waiting 30 minutes after the network failure? Depending on your network stack's settings, it could take this long to detect. However, if you're not periodically sending on the socket, you may never detect the outage. This is why many XMPP stacks periodically send a single space character, using an algorithm like: * *Set timer to N seconds *On sending a stanza, reset the timer to N *When the timer fires, send a space.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android pick random images? How can i load a random image out of 2 ? I tried this code final Random rgenerator = new Random(); Integer [] mImageIds = { R.drawable.mantrans, R.drawable.womentrans, }; Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)]; gBall1 = BitmapFactory.decodeResource(getResources(), q); but it did not work... Please help A: this is useful to you.. /////*****Random numbers with out repetation*****////// final int[] imageViews = { R.id.imgview11, R.id.imgview12, R.id.imgview13 }; final int[] images = { R.drawable.i1, R.drawable.i2, R.drawable.i3 }; Random rng = new Random(); List<Integer> generated = new ArrayList<Integer>(maxNoOfImages); for (int i = 0; i < maxNoOfImages; i++) { while(true) { Integer next = rng.nextInt(maxNoOfImages); if (!generated.contains(next)) { ImageView iv = (ImageView)findViewById(imageViews[i]); iv.setImageResource(images[next]); generated.add(next); break; } } } A: This is kind of a too much for such a simple task. But I haven't really used the Random class. This is an alternative method. ArrayList<Integer> ids = new ArrayList<Integer>(); ids.add(R.drawable.mantrans); ids.add(R.drawable.womentrans); Collections.shuffle(ids); gBall1 = BitmapFactory.decodeResource(getResources(), ids.get(0)); You may need to add a bit more id's as getting random in 2 options might not seem much random like pents90 mentioned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: fastest way to display mysql db records I have slow query problem, may be i am wrong, here is what i want, i have to display more than 40 drop down lists at a single page with same fields , fetched by db, but i feel that the query takes much time to execute and also use more resources.. here is an example... $sql_query = "SELECT * FROM tbl_name"; $rows = mysql_query($sql_query); now i use while loop to print all records in that query in drop down list, but i have to reprint same record in next drop down list up to 40 lists, so i use mysql_data_seek() to move to first record and then reprint the next list and so on till 40 lists. but this was seems slow to me so i use the second method like this same query for all 40 lists $sql_query2 = "SELECT * FROM tbl_name"; $rows2 = mysql_query($sql_query2); do you think that i wrong about the speed of query, or do you suggest me the another way that is faster than these methods.... A: Try putting the rows into an array like so: <?php $rows = array(); $fetch_rows = mysql_query("SELECT * FROM table"); while ($row = mysql_fetch_assoc($fetch_rows)) { $rows[] = $row; } Then just use the $rows array in a foreach ($rows as $row) loop. A: There is considerable processing overhead associated with fetching rows from a MySQL result resource. Typically it would be quite a bit faster to store the results as an array in PHP rather than to query and fetch the same rowset again from the RDBMS. $rowset = array(); $result = mysql_query(...); if ($result) { while ($row = mysql_fetch_assoc($result)) { // Append each fetched row onto $rowset $rowset[] = $row; } } If your query returns lots of rows (thousands or tens of thousands or millions) and you need to use all of them, you may reach memory limitations by storing all rows into an array in PHP. In that case it may be more memory-conservative to fetch rows individually from MySQL, but it will still probably be more CPU intensive. A: Instead of printing the records, going back, and printing them again, put the records in one big string variable, then echo it for each dropdown. $str = ""; while($row = mysql_fetch_assoc($rows)) { // instead of echo... $str .= [...]; } // now for each dropdown echo $str; // will print all the rows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to hide a div if user clicks anywhere but a link and the div itself using jQuery? Ok, so simple question. I have a link which when clicked shows a div. If the user blurs off that link the div is hidden. This is good, but I don't want the div to be hidden if the user clicks on it. So if the user clicks anywhere other than the link or div itself only then should the div be hidden. Right now my code doesn't do this. JSFiddle: http://jsfiddle.net/gTkUG/ jQuery: $('#myLink').click(function(e) { $('#myDiv').show(); e.preventDefault(); }); $('#myLink').blur(function() { $('#myDiv').hide(); }); HTML: <div style="display:none;width:100px;height:100px;border:1px solid red" id="myDiv"></div> <a href="" id="myLink">Click Me</a> So I guess the question is, how to detect blur on two or more events instead of just one? A: $('#myLink, #myDiv').click(function(e) { $('#myDiv').show(); e.preventDefault(); e.stopPropagation(); }); $(document).click(function() { $('#myDiv').hide(); }); http://jsfiddle.net/gTkUG/3/
{ "language": "en", "url": "https://stackoverflow.com/questions/7536748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSPredicate with multiple comparisons for one query string I was wondering if there is a way to simplify an NSPredicate that takes in a single query string for multiple comparison targets. I'm searching multiple attributes of a core data entity for the same query string. My current query looks something like this... [NSPredicate predicateWithFormat:@"(attributeA contains[cd] %@) OR (attributeB contains[cd] %@) OR (attributeC contains[cd] %@)", searchString, searchString, searchString]; Note that this works perfectly, but it does look a bit unsightly. Especially the searchString, searchString, searchString part. Any tips on how I could possibly simplify this would be great! thanks! A: You can use NSCompoundPredicate for your OR & AND operations like this. Obj-C - OR // OR Condition // NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"X == 1"]; NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"X == 2"]; NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicate1, predicate2]]; Obj-C - AND NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"X == 1"]; NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"X == 2"]; NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate1, predicate2]]; Swift - OR let predicate1:NSPredicate = NSPredicate(format: "X == 1") let predicate2:NSPredicate = NSPredicate(format: "Y == 2") let predicate:NSPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicate1,predicate2] ) Swift - AND let predicate1:NSPredicate = NSPredicate(format: "X == 1") let predicate2:NSPredicate = NSPredicate(format: "Y == 2") let predicate:NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2] ) Swift 3 - OR let predicate1 = NSPredicate(format: "X == 1") let predicate2 = NSPredicate(format: "Y == 2") let predicateCompound = NSCompoundPredicate.init(type: .or, subpredicates: [predicate1,predicate2]) Swift 3 - AND let predicate1 = NSPredicate(format: "X == 1") let predicate2 = NSPredicate(format: "Y == 2") let predicateCompound = NSCompoundPredicate.init(type: .and, subpredicates: [predicate1,predicate2]) A: You could do: NSPredicate *p = [NSPredicate predicateWithFormat:@"attributeA contains[cd] $A OR attributeB contains[cd] $A or attributeC contains[cd] $A"]; NSDictionary *sub = [NSDictionary dictionaryWithObject:searchString forKey:@"A"]; p = [p predicateWithSubstitutionVariables:sub]; Or you could do something weirder, like this: - (NSPredicate *)buildOrPredicate:(NSDictionary *)stuff { NSMutableArray *subs = [NSMutableArray array]; for (NSString *key in stuff) { NSString *value = [stuff objectForKey:stuff]; NSPredicate *sub = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", key, value]; [subs addObject:sub]; } return [NSCompoundPredicate orPredicateWithSubpredicates:subs]; } And then invoke that with: NSDictionary *stuff = [NSDictionary dictionaryWithObjectsAndKeys: searchString, @"attributeA", searchString, @"attributeB", searchString, @"attributeC", nil]; NSPredicate *p = [self buildOrPredicate:stuff]; The only other thing I can think of that might work is to try using positional specifies in the predicate format. However, I don't know if the parser recognizes them the same way that +stringWithFormat: does: NSPredicate *p = [NSPredicate predicateWithFormat:@"attributeA contains[cd] %1$@ OR attributeB contains[cd] %1$@ or attributeC contains[cd] %1$@", searchString];
{ "language": "en", "url": "https://stackoverflow.com/questions/7536750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does monotouch support WinForms and DataGridView Virtual Mode? I currently have a WinForms application that downloads large amounts of data from a WCF service. To display the data quickly, I use DataGridView Virtual Mode with Just-In-Time Data Loading. Being new to IPAD development, monotouch seems like a good option for a C# developer. But I have a concern that involves displaying large amounts of data in a grid. Does monotouch support DataGridView and Virtual Mode? If not,then how can monotouch display lots of data quickly? Or should I use objective C? A: monotouch doesn't have winforms, it wraps (has bindings to) the CocoaTouch API. I've never used monotouch (or anything mono, unfortunately), but it would appear that UITableView might be what you want? http://docs.go-mono.com/index.aspx?link=T%3aMonoTouch.UIKit.UITableView More info about the API's available from MonoTouch: http://ios.xamarin.com/Documentation/API
{ "language": "en", "url": "https://stackoverflow.com/questions/7536751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: delete 2 rows 1 Sql statement mysql I want to delete 2 distict rows, but with simular data. 3 colums, 1 is unique, and the other 2 are switched around. I was using something like this but it only delete 1. DELETE FROM Table WHERE Column1 = 'a' AND Column2 = 'b' OR column1 = 'b' AND Column2 = 'a' This only deleted one column the statement. Thanks for any help A: In SQL AND takes preference over OR. Your where clause is interpreted as WHERE (Column1 = 'a') AND (Column2 = 'b' OR column1 = 'b') AND (Column2 = 'a') This is quite likely not what you want and you should (almost) always put the OR'ed tests in parenthesis like so: WHERE (Column1 = 'a' AND Column2 = 'b') OR (column1 = 'b' AND Column2 = 'a') See: http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7536752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Storing specific XML node values with R's xmlEventParse I have a big XML file which I need to parse with xmlEventParse in R. Unfortunately on-line examples are more complex than I need, and I just want to flag a matching node tag to store the matched node text (not attribute), each text in a separate list, see the comments in the code below: library(XML) z <- xmlEventParse( "my.xml", handlers = list( startDocument = function() { cat("Starting document\n") }, startElement = function(name,attr) { if ( name == "myNodeToMatch1" ){ cat("FLAG Matched element 1\n") } if ( name == "myNodeToMatch2" ){ cat("FLAG Matched element 2\n") } }, text = function(text) { if ( # Matched element 1 .... ) # Store text in element 1 list if ( # Matched element 2 .... ) # Store text in element 2 list }, endDocument = function() { cat("ending document\n") } ), addContext = FALSE, useTagName = FALSE, ignoreBlanks = TRUE, trim = TRUE) z$ ... # show lists ?? My question is, how to implement this flag in R (in a professional way :)? Plus: What's the best choice to evaluate N arbitrary nodes to match... if name = "myNodeToMatchN" ... nodes avoiding case matching? my.xml could be just a naive XML like <A> <myNodeToMatch1>Text in NodeToMatch1</myNodeToMatch1> <B> <myNodeToMatch2>Text in NodeToMatch2</myNodeToMatch2> ... </B> </A> A: I'll use fileName from example(xmlEventParse) as a reproducible example. It has tags record that have an attribute id and text that we'd like to extract. Rather than use handler, I'll go after the branches argument. This is like a handler, but one has access to the full node rather than just the element. The idea is to write a closure that has a place to keep the data we accumulate, and a function to process each branch of the XML document we are interested in. So let's start by defining the closure -- for our purposes, a function that returns a list of functions ourBranches <- function() { We need a place to store the results we accumulate, choosing an environment so that the insertion times are constant (not a list, which we would have to append to and would be memory inefficient) store <- new.env() The event parser is expecting a list of functions to be invoked when a matching tag is discovered. We're interested in the record tag. The function we write will receive a node of the XML document. We want to extract an element id that we'll use to store the (text) values in the node. We add these to our store. record <- function(x, ...) { key <- xmlAttrs(x)[["id"]] value <- xmlValue(x) store[[key]] <- value } Once the document is processed, we'd like a convenient way to retrieve our results, so we add a function for our own purposes, independent of nodes in the document getStore <- function() as.list(store) and then finish the closure by returning a list of functions list(record=record, getStore=getStore) } A tricky concept here is that the environment in which a function is defined is part of the function, so each time we say ourBranches() we get a list of functions and a new environment store to keep our results. To use, invoke xmlEventParse on our file, with an empty set of event handlers, and access our accumulated store. > branches <- ourBranches() > xmlEventParse(fileName, list(), branches=branches) list() > head(branches$getStore(), 2) $`Hornet Sportabout` [1] "18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 " $`Toyota Corolla` [1] "33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 " A: For others who may try to lear from M.Morgan - here is the complete code fileName = system.file("exampleData", "mtcars.xml", package = "XML") ourBranches <- function() { store <- new.env() record <- function(x, ...) { key <- xmlAttrs(x)[["id"]] value <- xmlValue(x) store[[key]] <- value } getStore <- function() as.list(store) list(record=record, getStore=getStore) } branches <- ourBranches() xmlEventParse(fileName, list(), branches=branches) head(branches$getStore(), 2) A: The branches method does not preserve the order of the events. In other words, the order of 'record' in branches$getStore() stores is different from that in the original xml file. On the other hand, the handler methods can preserve the order. Here is the code: fileName <- system.file("exampleData", "mtcars.xml", package="XML") records <- new('list') variable <- new('character') tag.open <- new('character') nvar <- 0 xmlEventParse(fileName, list(startElement = function (name, attrs) { tagName <<- name tag.open <<- c(name, tag.open) if (length(attrs)) { attributes(tagName) <<- as.list(attrs) } }, text = function (x) { if (nchar(x) > 0) { if (tagName == "record") { record <- list() record[[attributes(tagName)$id]] <- x records <<- c(records, record) } else { if( tagName == 'variable') { v <- x variable <<- c( variable, v) nvar <<- nvar + 1 } } } }, endElement = function (name) { if( name == 'record') { print(paste(tag.open, collapse='>')) } tag.open <<- tag.open[-1] })) head(records,2) $``Mazda RX4`` [1] "21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4" $`Mazda RX4 Wag` [1] "21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4" variable [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb" Another benefit of using handlers is that one can capture hierarchical structure. In other words, it is possible to save the ancestors as well. One of the key points of this process is the use of global variables, which can be assigned with "<<-", instead of "<-".
{ "language": "en", "url": "https://stackoverflow.com/questions/7536754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Regular expression for matching HH:MM time format I want a regexp for matching time in HH:MM format. Here's what I have, and it works: ^[0-2][0-3]:[0-5][0-9]$ This matches everything from 00:00 to 23:59. However, I want to change it so 0:00 and 1:00, etc are also matched as well as 00:00 and 01:30. I.e to make the leftmost digit optional, to match HH:MM as well as H:MM. Any ideas how to make that change? I need this to work in javascript as well as php. A: The best would be for HH:MM without taking any risk. ^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$ A: None of the above worked for me. In the end I used: ^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$ (js engine) Logic: The first number (hours) is either: a number between 0 and 19 --> [0-1]?[0-9] (allowing single digit number) or a number between 20 - 23 --> 2[0-3] the second number (minutes) is always a number between 00 and 59 --> [0-5][0-9] (not allowing a single digit) A: Amazingly I found actually all of these don't quite cover it, as they don't work for shorter format midnight of 0:0 and a few don't work for 00:00 either, I used and tested the following: ^([0-9]|0[0-9]|1?[0-9]|2[0-3]):[0-5]?[0-9]$ A: Your original regular expression has flaws: it wouldn't match 04:00 for example. This may work better: ^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$ A: You can use this regular expression: ^(2[0-3]|[01]?[0-9]):([1-5]{1}[0-9])$ If you want to exclude 00:00, you can use this expression ^(2[0-3]|[01]?[0-9]):(0[1-9]{1}|[1-5]{1}[0-9])$ Second expression is better option because valid time is 00:01 to 00:59 or 0:01 to 23:59. You can use any of these upon your requirement. Regex101 link A: As you asked the left most bit optional, I have done left most and right most bit optional too, check it out ^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]?$ It matches with 0:0 00:00 00:0 0:00 23:59 01:00 00:59 The live link is available here A: None of the above answers worked for me, the following one worked. "[0-9]{2}:[0-9]{2}" A: Regular Expressions for Time * *HH:MM 12-hour format, optional leading 0 /^(0?[1-9]|1[0-2]):[0-5][0-9]$/ *HH:MM 12-hour format, optional leading 0, mandatory meridiems (AM/PM) /((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/ *HH:MM 24-hour with leading 0 /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/ *HH:MM 24-hour format, optional leading 0 /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/ *HH:MM:SS 24-hour format with leading 0 /(?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d)/ Reference and Demo A: You can use this one 24H, seconds are optional ^([0-1]?[0-9]|[2][0-3]):([0-5][0-9])(:[0-5][0-9])?$ A: To validate 24h time, use: ^([0-1]?[0-9]|2?[0-3]|[0-9])[:\-\/]([0-5][0-9]|[0-9])$ This accepts: 22:10 2:10 2/1 ... But does not accept: 25:12 12:61 ... A: Description hours:minutes with: * *Mandatory am|pm or AM|PM *Mandatory leading zero 05:01 instead of 5:1 *Hours from 01 up to 12 *Hours does not accept 00 as in 00:16 am *Minutes from 00 up to 59 01:16 am ✅ 01:16 AM ✅ 01:16 ❌ (misses am|pm) 01:16 Am❌ (am must all be either lower or upper case) 1:16 am ❌ (Hours misses leading zero) 00:16 ❌ (Invalid hours value 00) Regular Expression To match single occurrence: ^(0[1-9]|1[0-2]):([0-5][0-9]) ((a|p)m|(A|P)M)$ To match multiple occurrences: Remove ^ $ (0[1-9]|1[0-2]):([0-5][0-9]) ((a|p)m|(A|P)M) A: You can use following regex: ^[0-1][0-9]:[0-5][0-9]$|^[2][0-3]:[0-5][0-9]$|^[2][3]:[0][0]$ A: The below regex will help to validate hh:mm format ^([0-1][0-9]|2[0-3]):[0-5][0-9]$ A: Declare private static final String TIME24HOURS_PATTERN = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]"; public boolean validate(final String time) { pattern = Pattern.compile(TIME24HOURS_PATTERN); matcher = pattern.matcher(time); return matcher.matches(); } This method return "true" when String match with the Regular Expression. A: A slight modification to Manish M Demblani's contribution above handles 4am (I got rid of the seconds section as I don't need it in my application) ^(([0-1]{0,1}[0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]))$ handles: 4am 4 am 4:00 4:00am 4:00 pm 4.30 am etc.. A: Your code will not work properly as it will not work for 01:00 type formats. You can modify it as follows. pattern =r"^(0?[1-9]|1[0-2]):[0-5][0-9]$" Making it less complicated we can use a variable to define our hours limits.Further we can add meridiems for more accurate results. hours_limit = 12 pattern = r"^[1-hours_limit]:[0-5][0-9]\s?[AaPp][Mm]$" print(re.search(pattern, "2:59 pm")) A: Check this one /^([0-1]?[0-9]|2[0-3]):([0-5]?[0-9]|5[0-9])$/ A: Try the following ^([0-2][0-3]:[0-5][0-9])|(0?[0-9]:[0-5][0-9])$ Note: I was assuming the javascript regex engine. If it's different than that please let me know. A: You can use following regex : ^[0-2]?[0-3]:[0-5][0-9]$ Only modification I have made is leftmost digit is optional. Rest of the regex is same. A: Mine is: ^(1?[0-9]|2[0-3]):[0-5][0-9]$ This is much shorter Got it tested with several example Match: * *00:00 *7:43 *07:43 *19:00 *18:23 And doesn't match any invalid instance such as 25:76 etc ... A: check this masterfull timestamp detector regex I built to look for a user-specified timestamp, examples of what it will pickup include, but is most definitely NOT limited to; 8:30-9:40 09:40-09 : 50 09 : 40-09 : 50 09:40 - 09 : 50 08:00to05:00 08 : 00to05 : 00 08:00 to 05:00 8am-09pm 08h00 till 17h00 8pm-5am 08h00,21h00 06pm untill 9am It'll also pickup many more, as long as the times include digits A: You can try the following ^\d{1,2}([:.]?\d{1,2})?([ ]?[a|p]m)?$ It can detect the following patterns : 2300 23:00 4 am 4am 4pm 4 pm 04:30pm 04:30 pm 4:30pm 4:30 pm 04.30pm 04.30 pm 4.30pm 4.30 pm 23:59 0000 00:00
{ "language": "en", "url": "https://stackoverflow.com/questions/7536755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "243" }
Q: How to reverse an array of strings recursively? supposed to reverse an array of strings recursively. having trouble implementing this. if i was using a for loop i would just start it at the end of the array and print out the array starting with the last element and ending with the first. I'm not too sure how to do it recursively. i was thinking about using a swap but that idea sort of fizzled when i couldnt figure out how to change the elements that i was swapping. any ideas or a push in the right direction would be appreciated. this is what icame up with so far. i know its wrong, i get an error out of bounds exception which im not sure how to fix. I think im not swapping the first and last correctly. but am i getting the right idea? this is what i came up with. a is an array. its inside a class. // reverse an array public void rev() { rev(0,a.length-1); } private void rev(int first, int last) { if(last == 0) { //do nothing } else { while(first != last) { int temp = first; first = last; last = temp; System.out.print(" " + a[first]); rev((first + 1), (last - 1)); } } } made some changes and it reverses the last 3 elements but the it repeats the second element. i have no if statement that controls when it runs so shouldnt it run until left = right? this is what i changed it to // reverse an array public void rev() { rev(0,a.length-1); } private void rev(int first, int last) { if(last == 0) { //do nothing } else { String temp = a[first]; a[first] = a[last]; a[last] = temp; System.out.print(" " + a[first]); rev(first+ 1, last-1); } } A: The trick with recursion is to try and think of the problem in terms of a base case and then a way to reduce everything to that base case. So, if you're trying to reverse a list then you can think of it like this: * *The reverse of a list of size 1 is that list. *For a list of size > 1 then the first element in the output list will be the last element of the input list. *The rest of the output list will be the reverse of the input list, minus the last element. You now have your recursive definition. Hope that helps. A: the while loop is too much, since you are using recursion anyway, try it like this private void rev(int first, int last) { if(first < last) { var temp = a[first]; a[first] = a[last]; a[last] = temp; rev(first + 1, last - 1); } } A: I always like having a simple public method that calls the private recursive one. That way from other places in your code you just give it the array, and don't have to worry about the other arguments. Also, this catches empty arrays, but you would still need to check for null at some point near the start. Maybe throw an exception in the public method if the array is null? public String[] reverseArray(String[] theArray) { this.reverseArrayWorker(theArray, 0, theArray.length -1); } private String[] reverseArrayWorker(String[] theArray, int left, int right) { // Check your base cases first if (theArray.length <= 1) { // Array is one element or empty return theArray; } else if (left - right <= 0) { // If there are an odd # of items in the list you hit the center // If there are an even number your indexes past each other return theArray; } // Make the recursive call this.reverseArrayWorker(theArray, left + 1, right - 1); // Switch the two elements at this level String temp = theArray[left]; theArray[left] = theArray[right]; theArray[right] = temp; // Return the array up a level return theArray; } A: public int[] reverse(int[] returnMe, int[] original, int curPos){ if (original.length == 1){ return original; }else{ if (curPos < original.length){ returnMe[curPos] = original[original.length - 1 - curPos]; reverse(returnMe, original, curPos + 1); }else{ return returnMe; } } } A: Here is an example (but without A String since it is homework) but hopefully it will give you the idea. public static List<Character> reverse(List<Character> chars) { return chars.isEmpty() ? chars : addToList(chars.get(0), reverse(chars.subList(1, chars.length())); } public static T List<T> addToList(T t, List<T> ts) { List<T> ret = new ArrayList<T>(); ret.addAll(ts); ret.add(t); return ret; } A: This will work too. Kinda Lisp-like solution. public static List<String> append(String x, List<String> xs) { xs.add(x); return xs; } public static List<String> reverse(List<String> xs) { return xs.isEmpty() ? xs : append(xs.get(0), reverse(xs.subList(1, xs.size()))); } I/O: List ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Reversed list ==> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
{ "language": "en", "url": "https://stackoverflow.com/questions/7536756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Testing Clojure and Java simultaneously I'm developing a library that contains both Clojure and Java code, using Eclipse + Maven to manage the project. I have a good set of JUnit tests that cover the Java portion of the code base, and also have a separate set of Clojure tests written using the standard clojure.test toolset. Ideally I'd like to be able to run all tests simultaneously as part of the build process. I have the clojure-maven-plugin installed, but it still only seems to run the JUnit tests and ignores the Clojure ones. How can I achieve this? A: OK, I figured out how to do this myself with a little help from the information in the answers to this question on testing Clojure with Maven. The trick was to add the following section to the pom.xml: <build> <plugins> <plugin> <groupId>com.theoryinpractise</groupId> <artifactId>clojure-maven-plugin</artifactId> <version>1.3.8</version> <executions> <execution> <id>test-clojure</id> <phase>test</phase> <goals> <goal>test</goal> </goals> </execution> </executions> </plugin> </plugins> <testResources> <testResource> <directory>src/test/clojure</directory> </testResource> </testResources> </build> This has the effect of running the Clojure test cases as part of the standard Maven test goal. EDIT As of 2012, a good alternative is to use cljunit to run the Clojure tests as part of a regular JUnit test suite.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Call same method from different threads For example we have 5 running threads. Each of them call the same method. When the methods is called, it will run on the current thread? That means that the same method will run separately on the different threads in the (relatively) same time? Example: public string GetHhmlCode(string url) { // ... Some code here return html; } If we call this method from different threads with different parameter in the same time, the result will be return to appropriate thread which means that the code runs separately on different threads? A: The short answer is to the first question is: Yes! The method will be executed by multiple threads concurrently. The answer to the second question is: Yes (with reservations)! If you enter from a given thread context, then the method will return to the same thread context and all the treads will generally behave as if the other thread doesn't exist. However, this will quickly change if the threads have to read and/or write on the same variable. Consider this situation: class HttpClient { private volatile bool _httpClientConnected; //.. initialize in constructor public string GetHtmlCode(string url) { string html = string.Empty; if(_httpClientConnected) { html = FetchPage(url); } return html; } public void Connect() { _httpClientConnected = true; ConnectClient(); } public void Disconnect() { _httpClientConnected = false; DisconnectClient(); } } Suppose it is required that the client is connected for a page to be successfully fetched, then consider this order of execution: Thread 1: calls GetHtmlCode Thread 1: initialize local html variable Thread 3: calls Disconnect() Therad 2: calls GetHtmlCode Thread 2: initialize local html variable Thread 1: evaluate _httpClientConnected flag Thread 3: sets _httpClientConnected to false Therad 3: calls DisconnectClient() and successfully disconnects THread 3: exits the Disconnect() method. Thread 1: calls FetchPage() Therad 2: evaluates _httpClientConnected flag Thread 2: returns empty html string Therad 1: catches an exception because it attempted to fetch a page when the client was disconnected Thread 2 exited correctly, but Thread 1 possibly threw an exception and it may cause other problems in your code. Note that read/writing to the flag itself will be safe (i.e. those operations are atomic and visible to all threads due to the flag being labeled as volatile), however there is a race condition because the flag can be set AFTER a thread has already evaluated it. In this case there are a couple of ways to guard against the problem: * *Use a synchronization block (something like lock(syncObject){...}) *Create a separate http client for each thread (probably more efficient and it avoids synchronization). Now let's look at another example: public string GetHtmlCode(string url) { string html = string.Empty; string schema = GetSchema(url); if(schema.Equals("http://")) { // get the html code } return html; } Suppose the following happens: Thread 1: calls GetHtmlCode("http://www.abc.com/"); Thread 1: html is assigned an empty string Thread 2: calls GetHtmlCode("ftp://www.xyz.com/"); Thread 2: html is assigned an empty string Therad 1: assigns it's schema to the schema variable Thread 2: assigns it's schema to the schema varaible Thread 2: evaluates schema.Equals("http://") Thread 1: evaluates schema.Equals("http://") Thread 1: fetches html code Therad 2: returns html Therad 1: returns html In this case both threads entered the method with different parameters and only Thread 1 entered with a parameter that could allow it to fetch a page, but Thread 2 did not interfere with Thread 1. The reason why this happens is because the threads don't share any common variables. A separate instance of the url parameter is passed in and each thread also gets its own local instance of schema (i.e. the schema is not shared because it only exists in the context of the calling thread). A: mark this method as static and don't refer external variables inside this method. then it will work fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make a paired input box using autocomplete i need to make an autocomplete that will fill the other input boxes as soon as the user selects a account#...i'm using this http://code.google.com/p/jquery-autocomplete/ because it has many features that other autocomplete doesn't have.....i'm using the following parameters.. data: [ ['cutomer01', 001], ['cutomer02', 002], ['cutomer03', 003], ['cutomer04', 004] ] how can i make a function that will fill all the information as soon as the user selects an account# from an array...i'm just a newbie programmer so please help..
{ "language": "en", "url": "https://stackoverflow.com/questions/7536769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set Lion built-in FTP Server auto run off I set FTP Server by using Rumpus Server application. But Lion's built-in FTP Server is running on the front. So if I try to connect my FTP Server out of my LAN, I can only connect to the built-in FTP Server despite I wanted to connect Rumpus FTP Server. It can be solved by unload the built-in FTP Server(using sudo -s launchctl unload...) but every after rebooting I should set it because it is set to run automatically in every booting. How can I set the auto run off? Mac mini, Mac OS X (10.7.1) A: Edit the /System/Library/LaunchDaemons/ftp.plist and make sure that the Disabled key is set to true not false and then reboot: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Disabled</key> <true/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7536774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to search and replace in a line using sed I have a file content like this select b.id as cli_id,b.login as cli_login, b.pname as cli_name, b.cname as cli_company, b.phone as cli_phone, b.email as cli_email, (select (value / 1048576) from Limits where limit_name='disk_space' and id=b.limits_id) as Client_Package, b.cr_date, (select FROM_UNIXTIME(value,"%Y-%m-%d") from Limits where limit_name='expiration' and id=b.limits_id) as Client_expire, If(b.status=0,'Active','Inactive') as Cli_Status, a.name as dom_name, If(a.status=0,'Active','Inactive') as Dom_Package, a.cr_date as dom_create, (select FROM_UNIXTIME(value,"%Y-%m-%d") from Limits where limit_name='expiration' and id=a.limits_id) as dom_expire, (select (value / 1048576) from Limits where limit_name='disk_space' and id=a.limits_id) as Dom_Package, round((a.real_size / 1048576)) as Dom_usage from domains a, clients b where (select FROM_UNIXTIME(value,"%Y-%m-%d") from Limits where limit_name='expiration' and id=a.limits_id and (FROM_UNIXTIME(value,"%Y-%m-%d") between '2011-08-01' and '2011-12-01') ) and a.cl_id=b.id group by a.id; this all comes in a single line in that i want to replace the date part alone in this format between '2011-08-01' and '2011-12-01' The script runs every friday , suppose if i run this on 10th month means. the script need to change the value in the file like this between '2011-09-01' and '2012-01-01' every time the month alone need to change in this format between 'current month -1month' and 'current month + 3 months' sed -i 's/between '2011-08-01' and '2011-12-01'/'between '$(date --date="- 1 month" +%Y-%m)-01' and '$(date --date="+ 3 months" +%Y-%m)-01'/g file1 in this code iam trying to find and replace but it shows this error sed: -e expression #1, char 44: unterminated `s' command What mistake iam doing can any 1 explain? A: The expression isn't properly quoted. You start with 's/... but end with ... /g. No quote there. This is what I ran and it worked fine: sed -i "s/between '[0-9-]*' and '[0-9-]*'/between '$(date --date'-1month' +%Y-%m-01)' and '$(date --date'+3months' +%Y-%m-01)'/g" file1
{ "language": "en", "url": "https://stackoverflow.com/questions/7536782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Request size vs Server load I was writing the spec on how to organize the query parameters that are sent in a HTTP Request, and I came up with the following: All parameters a prefixed with the entity to which they belong, an example "a.b", which is read "b of entity a", that way each parameter would be clearly mapped to the corresponding entity, but what if there were two different entities that share a query paramater?, to avoid repetition and request size I came up with the following micro format. To have a request wide entity called shared each property of shared will represent a property that is shared among entities, e.g. POST /app/my/resource HTTP/1.1 a.p = v b.p = v c.p = v d.p = v Here it is clear that property p is shared among a,b,c and d so this could be sent as POST /app/my/resource HTTP/1.1 shared.p = a:b:c:d%v Now, the request is smaller and I'm being a bit more DRY, however this adds an extra burden to the server as it has to parse the string to process the values. Probably in my example the differences are insignificant and I could chose either, but I'd like to know what do you think about it, what would you prefer, maybe the size of the request does not matter, or maybe the parsing of the string is not such a big deal when the length is short, but what happens when we scale the size of both the request and string which one would be better, what are the tradeoffs? A: Just to throw this out there, I think the answer would depend on what platform your back-end servers are running to process the requests. For example, the last time that I checked, the Perl-based mod_perl can parse those strings much faster something like ASP.NET. A: What you are showing is a compression algorithm. Beware that payloads often are compressed on protocol layer already (HTTP, gzip Content-Type, see HTTP compression examples). Compression algorithms are advanced enough to compress duplicate string-items, so probably you won't win much by a custom compression. Generally try not to optimize prematurely. First show that you are having a response-time or payload-size issue and then optimize. Your compression algorithm itself is a good idea, but it makes payload more complicated as normal key/value pairs (xxx-form-urlencoded Content-Type). For maintenance reasons head for the simplest design possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to refer obfuscated public fields from other .dlls I obfuscated all the public and private fields in some dlls, but problem is, when I use these dlls in my project, other dll not able to refer obfuscated fields in obfuscated dll. Is there any way to access obfuscated fields. Please help me... (I obfuscated dll using DotFuscator tool.) Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/7536788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android: how to elegantly set many button IDs I have many buttons in my activity (only a subset of which are visible at a time). I currently have something ugly like this: buttonID[0] = R.id.buttonr1b1; buttonID[1] = R.id.buttonr1b2; buttonID[2] = R.id.buttonr1b3; buttonID[3] = R.id.buttonr1b4; ... buttonID[35] = R.id.buttonr1b36; for (int i = 0; i < 36; i++) { button[i] = (Button) findViewById(buttonID[i]); } Is there a more elegant way to reference all of R.id.buttonXXX ? It just looks so wrong and ugly. Thank you. A: Your instincts are correct. It's ugly and in general if you find yourself wanting to do this you should rethink your design. If your buttons are uniform to the point where you want to loop over them to do something like this, they're probably uniform enough to generate programmatically in the first place (and you can store references as you create them) or use some form of AdapterView. What data needs to be associated with each button? Can you associate it directly using setTag/getTag? Do you need to use IDs here at all? A: I'm not sure if this is more elegant or less elegant, because you will lose compile-time checking of your IDs. However, you can construct the IDs by name: final static String PREFIX = "buttonr1b"; ... Resources res = getResources(); for (int i = 0; i < 36; i++) { int resID = res.getIdentifier(PREFIX + i , "id", getPackageName()); button[i] = (Button) findViewById(resID); } Note: make sure "getPackageName()" would return the appropriate package for your R class, otherwise specify it explicitly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best Practice Regarding Types When Programming Windows? I'm currently learning Windows programming through the Win32 API using Petzold's book as a resource and I was wondering if I should use the types defined in the API instead of the standard C types (ie. char instead of CHAR, DWORD instead of unsigned long). I understand that this was mostly for backwards compatibility but is there any benefit of using them right now? A: Use the Windows types, especially for return values. You're much more likely to write portable code (i.e. works in 32-bit and 64-bit versions) that way. A: I would use the Windows types only in code that's directly interfacing with Windows API, and even then, only when it matters what type you're using - like if you need to pass a pointer to that type to an API function, or for semi-opaque types like handles. Don't start writing your for loops with INT or DWORD as the loop counter variable... Of course I may be biased... ;-) A: When in rome... so yes. It makes your code "fit" in a particular environment. Obviously this is more relevant if doing MFC/COM+ than, say, a (portable) console app that only makes a few WinAPI calls. (The WinAPI calls should still use the "windows types", IMOHO. They are already including anyway.) Happy coding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing long string of HTML in SQLite database causes unknown error I am storing some HTML in an SQLite3 database in Python. When I go to insert some HTML into my SQL table I get an error that I don't understand what's wrong & more importantly how to fix the issue. Error string: Exception General: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. The HTML string I am inserting into the table is pretty long (about 700 characters long). Any idea whats wrong & how I can fix this? A: Looking at the answer to this question, it looks like your issue is that you are attempting to insert HTML with characters in it that do not map to ASCII. If you call unicode(my_problematic_html) you'll probably wind up with a UnicodeEncodingError. In that case you'll want to decode your problematic string representation to unicode by calling: my_unicoded_html = my_problematic_html.decode("utf-8") and then writing my_unicoded_html to the database. You'll want to read Unicode In Python Completely Demystified. * Please note, your HTML may be encoded in some other codec (format? ... charset?) than utf-8. latin-1 is also a good guess if you are on Windows (or if the HTML might be from a Windows machine).
{ "language": "en", "url": "https://stackoverflow.com/questions/7536797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing Facebook PHP SDK (3.1.1) without $_SESSIONs I'm using Facebook as an option for logging into my website, and then am doing Graph API requests on behalf of them. I'm upgrading to both the new JavaScript SDK and the PHP SDK to use their latest oAuth stuff before the October 1 deadline. The PHP SDK now comes with an abstract BaseFacebook and they have an example Facebook class implementation that relies on PHP $_SESSIONs. I run a pretty large multi-server website, which makes using $_SESSIONs tricky -- can't use the default file-based sessions, and database-backed sessions often are no good for performance reasons. Not sure I want them in Memcached either as users shouldn't get logged out if it's cleared, etc. The concrete class only needs you to persist these 4 fields for each visitor: state, code, access_token, user_id. It seems like not all of these really need to be pure $_SESSION based. I'm trying to determine what really needs to go where... * *For example, the state data seems like it can be stored in a client-side cookie as it's only 1-time use for CSRF prevention. *Does the auth code really need persisting or is it only used once? *Can the user_id and access_token be stored in my users MySQL database? If so, how do I identify who a Facebook-authed user is to login them in, using the fbsr_ cookie? I'm happy to store some stuff in the database as long as it's clear that it's only be accessed when necessary (not on every page request for logged out users). Basically: Is it feasible to authenticate FB users without using $_SESSIONs? Where by "sessions", I mean some PHP-set cookie for all visitors (logged in or not) that links them with server-side data. A: I made some changes in Facebook.php file from PHP SDK. Just changed all functions to work with cookies instead of $_SESSION. // $_SESSION[$session_var_name] = $value; setcookie($session_var_name, $value, time() + 3600, '/'); etc and commented out session_start code: //if (!session_id()) { // session_start(); // } This is simple solution and it works perfectly. A: You are correct about state and code, they are for one-time use during initial authentication and do not need to be persisted to other pages. Userid can be stored in the database, and often is done so as a permanent entry. Access_token can be stored in the database, but of course it is not a permanent value and will have to be refreshed often. But it can be a way to avoid using sessions or cookies as long as you have some other way to identify the user so you can pull the token from the db. I have never been crazy about the idea of using PHP sessions for Facebook apps anyway, for reasons of cookie (un)reliability. You might want to take a look at http://www.braintilt.com/fbcookies.php for some ideas about avoiding the dependence on sessions that most Facebook examples are filled with. Of course if you're not adverse to cookies you can set your own and just use that to propogate the user identifier, rather that the GET/POST methods outlined there. A: Based on what i know, the code need not be stored, as it is used only once, during auth. You might want to store the access_token as it'll help you to call the graph api for user information, if you require, but you have to keep in mind that it is valid only for 2 hours or so. After that you will have to re-auth using getLoginUrl(). The user_id can obviously be stored, it's the Facebook user_id and it wont change. However to get the user_id, you need to parse the signed_request that facebook sends. Or you can directly call getUser() . When getUser() returns null, you know that the user is not authenticated by facebook, and then you can redirect the user to the url returned from getLoginUrl() to get your user authenticated by facebook. After authentication, you will be getting the user_id by calling getUser(). So you know that a user is Facebook authed if getUser() returns a user_id. Facebook has really improved the PHP SDK documentation, it wont take that much time for you to go through it. So finally, you can store all of these in sessions, however, you'd be better off storing user_id in your db. I would suggest, that you use sessions to store the access_token, and also always call getUser() to know the status of the visitor. Hope you got what u were looking for.. edit: you have posted the same question twice!!! A: The Facebook PHP SDK (beginning with v3.0) is split into two main parts, The Facebook class used to interact with the Facebook API and the abstract class BaseFacebook. The Facebook class extends this abstract class. The BaseFacebook abstract class implements the core oAuth API for Facebook, providing all of the public facing functions used when instantiating a new Facebook object. The session handling related functions are abstract functions that are implemented in the Facebook class. There are four functions that must be implemented: /** * Stores the given ($key, $value) pair, so that future calls to * getPersistentData($key) return $value. This call may be in another request. * * @param string $key * @param array $value * * @return void */ abstract protected function setPersistentData($key, $value); /** * Get the data for $key, persisted by BaseFacebook::setPersistentData() * * @param string $key The key of the data to retrieve * @param boolean $default The default value to return if $key is not found * * @return mixed */ abstract protected function getPersistentData($key, $default = false); /** * Clear the data with $key from the persistent storage * * @param string $key * @return void */ abstract protected function clearPersistentData($key); /** * Clear all data from the persistent storage * * @return void */ abstract protected function clearAllPersistentData(); These classes are used to get, set, and clear any persistent data used by the session. In the default Facebook class these use the PHP $_SESSION variable to store this data. By implementing these functions in your own class that extends BaseFacebook it is possible to change to any type of session handling you desire. There are four keys used by BaseFacebook that are stored in the persisted data: 'state', 'code', 'access_token', and 'user_id'. The 'state' is used to determine the current state in the authentication of the oAuth request. It is not used after a 'code' is retrieved. The 'code' is used to retrieve an 'access_token' from Facebook. It is not used after an 'access_token' is retrieved. The 'access_token' is used in subsequent request to the Facebook oAuth API. I believe it is only good for about 2 hours. The 'user_id' is the user's Facebook ID. This value is unique to that users and persistent. It can be saved indefinitely. This information is still valid in the current version of the SDK (as of this writing v3.2.2). See the Facebook developer page for more information on the Facebook PHP oAuth login flow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Deploying SQL Server Stored Procedure to multiple servers I manage several SQL Servers 2000, 2005 and 2008; I maintain several scripts in the form of stored procedures and functions for may daily activities; as the need arise I do changes to my local copies of those scripts then I need to apply those changes to the same stored procedures and functions on every database server; it's time consuming and painful to connect to every database server and replace what's in there. I've been trying to use sqlcmd utility with option -i but it's not working well; it keeps erroring out. Is there a way or a tool that I can use to deploy my local stored procedures and functions to multiple sql servers? stored procedures and functions have this structure use dba go check if stored procedure or function exists if so, drop it create stored procedure or function
{ "language": "en", "url": "https://stackoverflow.com/questions/7536800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Grabbing digits at end of URL using PHP On a page of mine, I have a GET as a URL of a website. mypage.com/page.php?=URLHERE On this URL, I need the ID at the very end of the URL mypage.com/page.php?url=http://www.otherwebsite.com/something.php?id=%%%%%%% These numbers are sometimes different amount of digits, so how would I do that? My code: $url = $_GET['url']; A: Assuming the url parameter is a properly encoded URL, then useparse_url() to get the URL components and parse_str() to retrieve the id parameter from its query string. $url = $_GET['url']; // First parse_url() breaks the original URL up $parts = parse_url($url); // parse_str() parses the query string from the embedded URL $query = parse_str($parts['query']); // Finally, you have your full id parameter $id = $query['id']; A: try the parse_url A: assuming the the url has id at the begining of query_string <?php $url = $_GET['url']; $url = basename($url); $url =explode("?",$url); $url = explode("=",$url[1]); echo $url[1]; ?> A: $url = parse_url($_GET['url'], PHP_URL_QUERY); $query = explode('=', $url); $id = $query[1]; A: I'd use the PHP function explode() http://php.net/manual/en/function.explode.php For this example $numbers = explode("=",$url); $id_value = $numbers[2]; print $id_value;
{ "language": "en", "url": "https://stackoverflow.com/questions/7536801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Visual Studio 2008 Question, table adapters connections string issue I have a data source that I use for creating reports in my programme. I've recently changed the connection string to the table adapters created by the wizard(ConString1), because I wanted to make that connection string available to every other class that needs to use it. So basically. I deleted the application setting created by the wizard(ConString1) and entered in my own application setting(ConString). Once debugging began all the code that still refered to the now non existent connection string(ConString1), I changed to the available one(ConString). That is in the code the debugger picked up. The program works fine. Now my problem is this, when I select a table adapter and take a look at its properties, the Connection string is still set to the old connection string name, the connection string value itself is given as "Unable to find connection ". This is prohibiting me from adding new tables to my reports.xsd file. I also keep getting an error when trying to create a new datasource. Error : Could not load type Microsoft.VisualStudio.DataDesign.SyncDesigner.SyncFacade.SyncManager. A: * *Right-click on the data-set xsd, select "Open With..." *Select "XML (Text) Editor" and click OK. *Modify as needed, and be careful. *Be careful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement a "click-anywhere-to-continue" event on my android activity? Is this possible? I would display an activity that shows a welcome page, and that welcome page doesn't have any Views where I can attach an onClickListener. EDIT: ok, the reason for this welcome kind of welcome page, is that this application is used to take something like a survey... after a customer is done with the survey, the app returns to this welcome page so another person can take the survey again. A: Yes, if the original layout is somehow not appropriate, use a FrameLayout at the top level of your layout to achieve this. FrameLayout allows stackable views/layouts, so you can have your existing view as the bottom layer, and then a transparent view on top that listens for the touch event: <FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent"> <!-- Put your complete original layout/view here --> <View android:id="@+id/view_to_listen_for_touch" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </FrameLayout> A: try like this, welcome screen xml layout. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mainLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" > </RelativeLayout> add this in your activity, private RelativeLayout mainLayout; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome_screen); mainLayout=(RelativeLayout)findViewById(R.id.mainLayout); mainLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // here you can write code to proceed next step. } }); } A: I think you are using an XML layout for this page. And using at least one ViewGroup (e.g Linear Layout/Relative Layout etc). Put an id to this ViewGroup element and In the Activity initialize this ViewGroup element using find view by id. Now set the click listener to the ViewGroup element
{ "language": "en", "url": "https://stackoverflow.com/questions/7536807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using java.io.File class When you make a File object instance in a java program, is it possible for a concurrently running program to also have access to the file for writing? So like if I had a File object with a path to example.txt, can another program be writing in that example.txt file while I have my File object existing? A: Doing File f = new File("C:\\test.txt"); does nothing to the file. So any other thread or process can open the file if they like. It just creates an object that represents the file, but doesn't open it or otherwise touch it. A: IF you have written, File f=new File("example.txt"); that means, you only created a file object, but not created a file on your harddisk according to a given path.Also that file object is in virtual memory(Java).If any other application which has already loaded in virtual memory can access or call the file object's reference ,then that application can access the file object. If you create a file with, f.createNewFile(); Then there is a real file in your hard disk.Then any other application can access it as other files in your hard disk. Would you have see here A: Yes, because a File object in Java really just represents a file system path. It's not actually a file handle that has lock semantics on the underlying resource. You can even create File instances to non-existent resources. A: Yes. Having a File instance has little to do with the actual file system until you call one of its methods. In fact, you can create File instances of paths that don't even exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it a bad idea to keep a subtotal field in database I have a MySQL table that represents a list of orders and a related child table that represents the shipments associated with each order (some orders have more than one shipment, but most have just one). Each shipment has a number of costs, for example: * *ItemCost *ShippingCost *HandlingCost *TaxCost There are many places in the application where I need to get consolidated information for the order such as: * *TotalItemCost *TotalShippingCost *TotalHandlingCost *TotalTaxCost *TotalCost *TotalPaid *TotalProfit All those fields are dependent on the aggregated values in the related shipment table. This information is used in other queries, reports, screens, etc., some of which have to return a result on tens of thousands of records quickly for a user. As I see it, there are a few basic ways to go with this: * *Use a subquery to calculate these items from the shipment table whenever they are needed. This complicates things quite a bit for all the queried that needs all or part of this information. It is also slow. *Create a view that exposes the subqueries as simple fields. This keeps the reports that needs them simple. *Add these fields in the order table. These would give me the performance I am looking for, at the expense of having to duplicate data and calculate it when I make any changes to the shipment records. One other thing, I am using a business layer that exposes functions to get this data (for example GetOrders(filter)) and I don't need the subtotals each time (or only some of them some of the time), so generating a subquery each time (even from a view) is probably a bad idea. Are there any best practices that anybody can point me to help me decide what the best design for this is? Incidentally, I ended up doing #3 primarily for performance and query simplicity reasons. Update: Got lots of great feedback pretty quickly, thank you all. To give a bit more background, one of the places the information is shown is on the admin console where I have a potentially very long list of orders and needs to show TotalCost, TotalPaid, and TotalProfit for each. A: Theres absolutely nothing wrong with doing rollups of your statistical data and storing it to enhance application performance. Just keep in mind that you will probably need to create a set of triggers or jobs to keep the rollups in sync with your source data. A: I would probably go about this by caching the subtotals in the database for fastest query performance if most of the time you're doing reads instead of writes. Create an update trigger to recalculate the subtotal when the row changes. I would only use a view to calculate them on SELECT if the number of rows was typically pretty small and access somewhat infrequent. Performance will be much better if you cache them. A: Option 3 is the fastest If and when you are running into performance issues and if you cannot solve these any other way, option #3 is the way to go. Use triggers to do the updating You should use triggers after insert, update and delete to keep the subtotals in your order table in sync with the underlying data. Take special care when retrospectively changing prices and stuff as this will require a full recalc of all subtotals. So you will need a lot of triggers, that usually don't do much most of the time. if a taxrate changes, it will change in the future, for orders that you don't yet have If the triggers take a lot of time, make sure you do these updates in off-peak hours. Run an automatic check periodically to make sure the cached values are correct You may also want to keep a golden subquery in place that calculates all the values and checkes them against the stored values in the order table. Run this query every night and have it report any abnormalities, so that you can see when the denormalized values are out-of-sync. Do not do any invoicing on orders that have not been processed by the validation query Add an extra date field to table order called timeoflastsuccesfullvalidation and have it set to null if the validation was unsuccessful. Only invoice items with a dateoflastsuccesfullvalidation less than 24 hours ago. Of course you don't need to check orders that are fully processed, only orders that are pending. Option 1 may be fast enough With regards to #1 It is also slow. That depends a lot on how you query the DB. You mention subselects, in the below mostly complete skeleton query I don't see the need for many subselects, so you have me puzzled there a bit. SELECT field1,field2,field3 , oifield1,oifield2,oifield3 , NettItemCost * (1+taxrate) as TotalItemCost , TotalShippingCost , TotalHandlingCost , NettItemCost * taxRate as TotalTaxCost , (NettItemCost * (1+taxrate)) + TotalShippingCost + TotalHandlingCost as TotalCost , TotalPaid , somethingorother as TotalProfit FROM ( SELECT o.field1,o.field2, o.field3 , oi.field1 as oifield1, i.field2 as oifield2 ,oi.field3 as oifield3 , SUM(c.productprice * oi.qty) as NettItemCost , SUM(IFNULL(sc.shippingperkg,0) * oi.qty * p.WeightInKg) as TotalShippingCost , SUM(IFNULL(hc.handlingperwhatever,0) * oi.qty) as TotalHandlingCost , t.taxrate as TaxRate , IFNULL(pay.amountpaid,0) as TotalPaid FROM orders o INNER JOIN orderitem oi ON (oi.order_id = o.id) INNER JOIN products p ON (p.id = oi.product_id) INNER JOIN prices c ON (c.product_id = p.id AND o.orderdate BETWEEN c.validfrom AND c.validuntil) INNER JOIN taxes t ON (p.tax_id = t.tax_id AND o.orderdate BETWEEN t.validfrom AND t.validuntil) LEFT JOIN shippingcosts sc ON (o.country = sc.country AND o.orderdate BETWEEN sc.validfrom AND sc.validuntil) LEFT JOIN handlingcost hc ON (hc.id = oi.handlingcost_id AND o.orderdate BETWEEN hc.validfrom AND hc.validuntil) LEFT JOIN (SELECT SUM(pay.payment) as amountpaid FROM payment pay WHERE pay.order_id = o.id) paid ON (1=1) WHERE o.id BETWEEN '1245' AND '1299' GROUP BY o.id DESC, oi.id DESC ) AS sub Thinking about it, you would need to split this query up for stuff that's relevant per order and per order_item but I'm lazy to do that now. Speed tips Make sure you have indexes on all fields involved in the join-criteria. Use a MEMORY table for the smaller tables, like tax and shippingcost and use a hash index for the id's in the memory-tables. A: I would avoid #3 as possible as I can. I prefer that for different reasons: * *It's too hard to discuss performance without measurement. Imaging the user is shopping around, adding order items into an order; every time an item is added, you need to update the order record, which may not be necessary (some sites only show order total when you click shopping cart and ready to checkout). *Having a duplicated column is asking for bugs - you cannot expect every future developer/maintainer to be aware of this extra column. Triggers can help but I think triggers should only be used as a last resort to address a bad database design. *A different database schema can be used for reporting purpose. The reporting database can be highly de-normalized for performance purpose without complicating the main application. *I tend to put the actual logic for computing subtotal at application layer because subtotal is actually an overloaded thing related to different contexts - sometimes you want the "raw subtotal", sometimes you want the subtotal after applying discount. You just cannot keep adding columns to the order table for different scenario. A: It's not a bad idea, unfortunately MySQL doesn't have some features that would make this really easy - computed columns and indexed (materialized views). You can probably simulate it with a trigger.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What does this perl regex match? I've started learning regex but this has so many elements in it. What does it match? $x =~s/\.?0+$//; A: It matches zero or one literal dot, followed by one or more zeros, then the end of string. \. #A literal dot ? #Zero or one of the previous character 0+ #One or more zeros $ #End of string A: There's an App for that! A: It removes the period and trailing zeroes from the end of a string, changing '24.00' into '24'. In pieces: s/ substitute operation \. literal period, not a placeholder ? Period is optional (by the way, probably a bug) 0+ one or more zeros $ all of this at the end of the string. // replace it with nothing, i.e., just delete it. The bug? Well, '2400' would be changed to '24'. Probably not the desired behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how do I push a branch in git to a remote I am trying to do a Rails 3 upgrade. So what I did is a created a branch -b rails-3 I've been working in that branch I want to push it into a remote repository (just in case something goes down on my local machine) How do I do that? If I do git push it says everything is up to date.... A: git push origin HEAD:refs/heads/branch-name should do the trick. It will create a branch called branch-name on the origin repository and copy your HEAD to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to calculate on client side Work on C# asp.net. My gridview has five columns. Input on my Quantity column need to calculate the Item Total and Total column value. A: Bind the event onkeyup in quantity Textbox that triggers a javascript function from where you can calculate and enter the value in Item Total column. You can use jQuery to ease your task. Could you please show some code that you have done so far?
{ "language": "en", "url": "https://stackoverflow.com/questions/7536832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot get Android Market to exclude small-screen phones for this app This app was originally released erroneously supporting all screen sizes due to a manifest error. That has now seemingly been cleaned up, but there is still a continuous parade of angry users with Samsung Intercepts or similar LDPI, small-screen devices who were somehow able to purchase and install the app. Here is the manifest: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="..." android:versionCode="7" android:versionName="1.06"> <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="7"/> <application android:label="@string/app_name" android:icon="@drawable/icon" android:debuggable="true" android:theme="@android:style/Theme.NoTitleBar"> <supports-screens android:smallScreens="false" android:normalScreens="true" android:largeScreens="true"/> <activity android:name="..." </activity> </application> The "..." indicates anonymized content. Does anybody have an idea of what is causing the Android Market to still make this available to small screens? A: support-screens tag should be put outside the application tags, similar to this: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="..." android:versionCode="7" android:versionName="1.06"> <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="7"/> <application android:label="@string/app_name" android:icon="@drawable/icon" android:debuggable="true" android:theme="@android:style/Theme.NoTitleBar"> <activity android:name="..." </activity> </application> <supports-screens android:smallScreens="false" android:normalScreens="true" android:largeScreens="true"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7536836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set image's height as much as the text content In my page I show posts from feeds. A post-preview has an image and the content. The width of the image is fixed at 150px but I want the image to have height equal to content's height. A post-preview content may have less than 450 chars, that means that the height of it will be smaller that other posts. Is this possible using jQuery? This is my code: <div id="post"> <div id="image"> <?php $imgpath="timthumb.php?src=THE-IMAGE.PNG&h=91&w=150"; } ?> <img border="0" src="<?php echo $imgpath; ?>"></img> </div> <div id="thepost2"> <?php echo mb_substr(strip_tags($entry->description), 0, 450, "UTF-8"); ?> </div> </div> A: HTML <div id="uniqueid" class="autoheight"> <img /> </div> $('.autoheight img').css({height: $('#thepost2').height(), width:'150 px'}); If you will not specify the width it will set the width equal to height as well. So you will be specifying width appropriately as your needs. It may change the aspect ratio of the image and it might not look good.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to decide the rank of N horses with M tracks? Providing N horses and M(M <= N) tracks but no timer, all you could get from one round is the order of M horses. The questions how many rounds at least, if you want to get the rank of all horses? e.g. N=3, M=3, Round=1; N=3, M=2, Round=3; N=4, M=3, Round=3; what is Round, when N=1000, M=3? A: You can get a lower bound with information theory. Each race gives you log(m!) bits of information, and you need log(n!) bits. So a natural lowerbound on the number of races is then log(n!) / log(m!). A: Formal definition of the problem - http://www.math.uiuc.edu/~west/regs/ksetsort.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7536842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Master Page is adding additional text in TextBox ID I have a master page which has a content section with the id cpMainContent. I am using this master page on every webform I am creating for college project. One of such form is frmSearchPersonnel. The purpose of frmSearchPersonnel is to ask user last name of the person they want to search in a textbox and then click on search button. The ID of TextBox is txtSearchName Search button will do postbackUrl transfer to another form which I have named frmViewPersonnel. In frmViewPersonnel I am trying to use following code. NameValueCollection myRequest = Request.Form; if(!string.IsEmptyOrNull(myRequest["txtSearchName"])) string strSearch = myRequest["txtSearchName"]; The problem I ran into is that this didn't find any control with the name of txtSearchName. While debugging I found this in myRequest object, [5] "ctl00$cpMainContent$txtSearchName" string Even though when I added textbox I gave it ID of txtSearchName but when page is rendered it is adding extra string from master page. * *How can I stop this? I have to use master page so don't say not to use master page :) *Why is it doing that? Update While Googling and Binging I found that I can use Control.ClientID in this case so looking into it. Update 2 As suggested below to add ClientIDMode="static" in the html of control or add it in page directive. What it does is, it keeps the ID static to txtSearchName but problem is this, <input name="ctl00$cpMainContent$txtSearchName" type="text" id="txtSearchName" /> Here name is still using ctl00 and the code I showed above, string strSearch = myRequest["txtSearchName"] it still won't work because nvc collection is either searchable by index or name not the id directly. ============== A: * *You need to add a ClientIDMode="Static" to the html of the textbox: <asp:TextBox ID="txtSearchName" runat="server" ClientIDMode="Static" /> * *It happens to prevent duplicate ID's. Usually it happens when you use master pages as it contains nested pages If you want all controls with ClientIDMode="Static", you can put it in the page header of the master file. <%@ Page Language="C#" ClientIDMode="Static" %> A: If you are posting to another page that uses the same master page (called SiteMaster in my case), the name of the textbox should be same the same. string val = Request[((SiteMaster)Master).txtSearchName.UniqueID]; If you're NOT posting to a page with the same master, well, then are you using the viewstate for the textbox at all since you're posting to another page? If not, just make the control a non asp.net control: <input type="text" name="txtSearchName"/> If you are using viewstate and posting to another page with a different master page, well, you should use PreviousPage. A: Little late here. Appreciate @aquinas and @rudeovski ze bear. Interesting and good answers. I'd same issue and I solved it differently. In fact, I used a public Interface. public interface ISearch { string SearchText { get; } } Then implement ISearch interface in two aspx page say One.aspx and Two.aspx classes. --One.aspx-- (Where I'v added TextBox1, and Button1 and set Button1.PostBackUrl="~/Two.aspx") public partial class One : System.Web.UI.Page , ISearch { public string SearchText { get { return TextBox1.Text; } } } --Two.aspx-- public partial class Two : System.Web.UI.Page, ISearch { protected void Page_Load(object sender, EventArgs e) { ISearch search = (ISearch) PreviousPage; Label1.Text = search.SearchText; } public string SearchText { get { throw new NotImplementedException(); } } } A: If your try to access the input element value in code behind on post back instead of for example: var emailAddress = Request.Form["ctl00$ctl00$ctl00$ContentContainer$MainContent$MainContent$ContentBottom$ProfileFormView$emailaddress1"]; Use var emailAddressKeyName = Request.Form.AllKeys.FirstOrDefault(a => a.Contains("emailaddress1")); var emailAddress = Request.Form[emailAddressKeyName];
{ "language": "en", "url": "https://stackoverflow.com/questions/7536843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make buttons on UIAlertView displaying in multiple lines? I want to display a message using UIAlertView and there will be two buttons. As one of the buttons has a long name, It's not appropriate to display both of them in one line. I know that when there are more than two buttons, all of them will be displayed each in a row. How can I display these two buttons in two line? Thanks. A: There is no officially documented way to do this. UIAlertView is a subclass of UIView. So you could traverse its subclasses to find the buttons, and transform their position and size. This is probably a bad idea though. If Apple changes it's implementation of the UIAlertView, it might break your code. Your app might also be rejected for customizing the UIAlertView. Eg see this answer. Instead, you should consider changing the title of your button to be shorter, or create your custom UIView subclass that you present modally.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Embedding PHP commands in WordPress editor HTML tab I am using Wordpress and I want to have some PHP commands executed on my page. After I paste my HTML with embedded PHP (in HTML tab of WordPress editor), the PHP codes are automatically converted to comments!! Below is the example: What I enter in HTML tab: <div class="floated"><label for="contactName"><?php _e( 'Name', 'arizona' ); ?>*:</label> What it looks like after I go to Visual tab and then come back to HTML tab: <div class="floated"><label for="contactName"><!--?php _e( 'Name', 'arizona' ); ?-->*:</label> It looks like the editor just accept pure HTML code and converts the rest of unknown tags to comment! If that's the case how can have/call a php page within my text!. I need this as I want to have a contact form within an accordion slider! A: This is not a good practice, that's why it's not supported within Wordpress. The following are considered good practices: * *Custom Code on your Theme *Create a Wordpress Plugin *Create a Wordpress Widget If you want a contact form consider using the Contact Form 7 Plugin. http://wordpress.org/extend/plugins/contact-form-7/ Which will let you add a TAG that you could use in that accordion. A: You need to use a wordpress plugin to execute arbitrary php code inside a page maintained in the editor. I've used this one before, it's not bad but once you get into anything that needs to maintain state or process forms, it can be a bit messy but certainly possible. Not a shortcoming of the plugin really, but of trying to run custom code you maintain in the page editor. It might be better to write your custom code as a custom wordpress plugin. http://wordpress.org/extend/plugins/exec-php/
{ "language": "en", "url": "https://stackoverflow.com/questions/7536855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to merge two collections into one I have two collections created within Silverlight each collection is created at separate times by different methods. Method 1 creates a List<> titled person ( contains fields first name, last name age) Method 2 created a List<> titled Phone ( contains phone number, cell number) Is there a way within SL to combine these two Lists into one Collection that could then be bound to the view for display? Example: combined into a collection that contained all properties (first name, last name age, phone number, cell number) A: You're looking for the Zip function. It allows you to combine 2 collections into a single one by combining the elements of eache. List<Type1> col1 = ...; List<Type2> col2 = ...; var combined = col1.Zip(col2, (x, y) => new { FirstName = x.FirstName, LastName = x.LastName, PhoneNumber = y.PhoneNumber, CellNumber = y.CellNumber }); I'm not sure if Zip is available on not in Silverlight. If not then here's a definition of it public static IEnumerable<TRet> Zip<T1, T2, TRet>( this IEnumerable<T1> enumerable1, IEnumerable<T2> enumreable2, Func<T1, T2, TRet> func) { using (var e1 = enumerable1.GetEnumerator()) { using (var e2 = enumerable2.GetEnumerator()) { while (e1.MoveNext() && e2.MoveNext()) { yield return func(e1.Current, e2.Current); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: HTML Horizontal Menu Layout I have a Hortizontal Menu at this URL - http://www.balibar.co/main.php I'm happy with the look but I'm finding 2 things * *it doesn't take up the entire space... there is a little white space at the end. *If I change the screen size (eg: hold Ctrl & use the Mouse Wheel to change the screen size) the last menu item 'search' drops to the next level. How can i fix these 2 things. Here is the HTML code: <div id="containerNavigation"> <ul> <li><a id="headerLoginLink">Home</a></li> <li><a id="headerLanguageLink">Profile</a></li> <li><a id="headerSearchLink">Mail</a></li> <li><a id="headerSearchLink">Requests</a></li> <li><a id="headerSearchLink">Matches</a></li> <li><a id="headerSearchLink">Search</a></li> </ul> </div> And here is the CSS div#containerNavigation { width: 700px; height: 25px; float: left; } div#containerNavigation ul { list-style: none; color: #FFF; } div#containerNavigation li { background: white url(../images/online-dating-main/navigation5.png) repeat-x 0 0; display: inline; line-height: 25px; font-size: 1.1em; float: left; } div#containerNavigation li a { cursor: pointer; font-weight: normal; float: left; width: 116px; text-decoration: none; color: white; border-right: 1px solid #FFF; text-align: center; } div#containerNavigation li a:hover { background-color: #849C00; } thankyou! A: div#containerBody width should be 702px. It is less by 2px and is the reason it is falling down ( 116 * 6 + 6 = 702 ). 6 addition is for the border right 1px for each you passed. That should be same for containerNavigation too. There are few things to change. div#joinHeader li a { cursor: pointer; margin: 0 15px; } You have fixed width for the ul tag ( class=shadow ). Take out that margin 15 px for the li a tags. That should make them properly aligned fitting to the division. Also, joinCatchPhrase has extra width of 100px. Reduce it by the same. A: Two little changes: for the div#containerNavigation li a width: 100%; for the div#containerNavigation li width: 116px; A: Is there any reason to not use a table? That way you're guaranteed to never have the problem of an item going to the next line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using AJAX Response to Terminate a Concurrent Request Suppose I make an AJAX HTTP Request from jQuery to a back-end PHP script that does some querying on MySQL server. While the request is made, I want to regenerate a new request and terminate the current one on the server end. Script front-end.php contains this: function process(json) { // iterate and display result } google.maps.event.addListener(map, 'idle', function () { .... $.getJSON('back-end.php?id=$id&bounds=$bounds', process); }); Script back-end.php contains this: $id = // get current MySQL process id // check and send request to terminate previous process if id is set // send request to get data based on bounds criteria echo json_encode(data); How can I get $id onto script front-end.php so that I can terminate the previous process on the server as soon as I issue the next one? A: You need to save this process id somewhere common to the two different requests. Something like in a text file, or db table, or memcache on the backend. So for example the first php request starts your process then writes the process id to a file such as current_id.txt. Then the second request checks this file for an id, then kills the process then blanks out current_id.txt after it is killed. If you need this to be replicable across many users, you have to have a way to identify it is the same person with a session variable or the session id itself, and create files like <session_id>_process_id.txt so each unique user can do this independent of each other.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to upload my application in App Hub I can't upload my application in App Hub,When i submit a application then it shows an error message "Error occurred connection to server" Please you help me ! Thank you very much ! A: I had a similar problem. The AppHub is Silverlight based, try cleaning up your cache of your browser and try again. This solved my problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is edit_post_path from a Ruby standpoint Learning Ruby and Rails. In following the getting started guide if I invoke rails generate scaffold Post name:string title:string content:text it generates among other things code like the following in index.html.erb: <% @posts.each do |post| %> <tr> <td><%= post.name %></td> <td><%= post.title %></td> <td><%= post.content %></td> <td><%= link_to 'Show', post %></td> <td><%= link_to 'Edit', edit_post_path(post) %></td> <td><%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %></td> </tr> <% end %> </table> My only concern in the above is edit_post_path, and my question is, what is it - and specifically from a Ruby standpoint. It certainly has every appearance of being a Ruby method, and its embedded in other code which is most definitely Ruby: posts.each do |post|...end that's all Ruby But if edit_post_path is a Ruby method, where is the code for it? 'post' is a label I have provided to Rails, so presumably this Ruby method should be somewhere in my site directory along with other Ruby code generated when invoking "rails generate scaffold..." above (i.e. it wouldn't be in a Rails-specific directory for example). But there is no such method 'edit_post_path' defined anywhere. So is it not really Ruby at all, just something contrived to look that way for some reason, and really just a string of text that is processed by something strictly proprietary to Rails. Is this an example of what is so cool about Rails? A: That is a Rails helper method - aka sugar syntax as James pointed out - for routing within your app. To see all the routes available to you, at the command line do rake routes. You will see a list of the helpers on the left, then you will see the HTTP operation in the second column, third column = URL path format, and last column is a breakdown of the controller and action that it relates to. To see some of the Ruby code that is at the heart of this magic, check it out in the Rails 3 repo, like this: https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/mapper.rb#L444 Also if you want to create custom URLs for specific resources, check out: https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/url_for.rb Here is some more info on routing in general: http://guides.rubyonrails.org/routing.html Hope that helps. A: It's "sugar"-syntax built into Rails. There are a ton of easy methods like this to speed up development.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How would I package and deploy Python application like Mercurial hooks? In this case, the application consists of one or more Python files, plus a settings.ini file. Now the Python files when being installed need to be installed in ~/.hg (as default) or prompted where the user want them installed. The installation also requires text to be appended to files like hgrc. Is there already a specific Python package that does all of this, or if anyone has any experience in this area please share. As far as I have looked, Python packaging refers to setuptools and easy_install. The basis for packaging is a setup.py file. A problem with this is that such a setup file is used for a couple of dissimilar tasks: * *Generating documentation. *Creating a release (source/binary). *Actually installing the software. Combining these tasks in one file is a bit of a hazard and leads to problems now and then. or distutils, but I am not sure if these packages support the notion of user prompting and deployment like appending text to existing files, and creating new ones. A: I would include a custom script (bin/ command) which will poke the users' .hgrc and others. Doing it without the user consent would be rude. User story * *Install package: easy_install pkgname and this deploys myproject-init-hg (UNIX executable, can be also written in Python) *The installation finished and tells the user to run commmand myproject-init-hg setup.py include mechanism to distribute and deploy bin/ style scripts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android java Add a textView I have a java file that its setContentView is to another java file... Here is the first java file package dalton.metzler.occupied; import android.app.Activity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; public class PlayActivity extends Activity{ Play ourView; LinearLayout linear; TextView text; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ourView = new Play(this); setContentView(ourView); } } And here is the file thats linking to it as the set contentview there is not speical code you need to look at just showing so you can see what it is. And see exactly what i mean about the text thing i am trying to do package dalton.metzler.occupied; import java.util.Random; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.view.View; public class Play extends View { Bitmap gBall1, gBall2, gBall3, gBall4, gBall5, gBall6, gBall7, gBall8, gBall9, gBall10, gBall11, gBall12, gBall13; float changingY, changingY2, changingY3, changingY4, changingY5, changingY6, changingY7, changingY8, changingY9, changingY10, changingY11, changingY12, changingY13; public Play(Context context) { super(context); gBall1 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); gBall2 = BitmapFactory.decodeResource(getResources(), R.drawable.womentrans); gBall3 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); gBall4 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); changingY = 0; changingY2 = -110; changingY3 = -220; changingY4 = -330; changingY5 = -440; changingY6 = -550; changingY7 = -660; changingY8 = -770; changingY9 = -880; changingY10 = -990; changingY11 = -1100; changingY12 = -1210; changingY13 = -1320; } protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(Color.WHITE); canvas.drawBitmap(gBall1, (canvas.getWidth()/2), changingY, null); canvas.drawBitmap(gBall2, (canvas.getWidth()/2), changingY2, null); canvas.drawBitmap(gBall3, (canvas.getWidth()/2), changingY3, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY4, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY5, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY6, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY7, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY8, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY9, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY10, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY11, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY12, null); canvas.drawBitmap(gBall4, (canvas.getWidth()/2), changingY13, null); if (changingY < canvas.getHeight()){ changingY += 5; }else{ changingY = -600; } if (changingY2 < canvas.getHeight()){ changingY2 += 5; }else{ changingY2 = -600; } if (changingY3 < canvas.getHeight()){ changingY3 += 5; }else{ changingY3 = -600; } if (changingY4 < canvas.getHeight()){ changingY4 += 5; }else{ changingY4 = -600; } if (changingY5 < canvas.getHeight()){ changingY5 += 5; }else{ changingY5 = -600; } if (changingY6 < canvas.getHeight()){ changingY6 += 5; }else{ changingY6 = -600; } if (changingY7 < canvas.getHeight()){ changingY7 += 5; }else{ changingY7 = -600; } if (changingY8 < canvas.getHeight()){ changingY8 += 5; }else{ changingY8 = -600; } if (changingY9 < canvas.getHeight()){ changingY9 += 5; }else{ changingY9 = -600; } if (changingY10 < canvas.getHeight()){ changingY10 += 5; }else{ changingY10 = -600; } if (changingY11 < canvas.getHeight()){ changingY11 += 5; }else{ changingY11 = -600; } if (changingY12 < canvas.getHeight()){ changingY12 += 5; }else{ changingY12 = -600; } if (changingY13 < canvas.getHeight()){ changingY13 += 5; }else{ changingY13 = -600; } invalidate(); } } How can i add text to the app? Like a textview but not in the xml because i can't do this (i think) I want to add like the text: Score: 0 to the screen A: Right now you cannot added another view to your custom View as it extends the View class. You will need to extend a viewgroup class to add other views. Create a linear layout and add the play view and the textview to that and set the linear layout in the setContentView function. If you just need to draw text on playview, there is the canvas.drawText function. I think your drawText method is wrong. Try this. Paint orangePaint = new Paint(); orangePaint.setColor(Color.BLACK); canvas.drawText("test", 50, 50, orangePaint); This should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: REST Web Service usage in Android I have got a tutorial on "Build RESTful web services with the Spring 3 MVC HttpMessageConverter feature" here : http://www.ibm.com/developerworks/webservices/library/wa-restful/index.html But I am not sure if android supports this? If yes, how can i call these web services in my android application and use it?? Or do I have to go for JSON and Jesrey, JAVA - RX etc?? Any help?? Thanks, Sneha A: I know of Android applications invoking web services - havent actually worked on such an app though. The actual payload can be JSON or XML - I am assuming you are building the client on the Android device and the server is hosted somewhere else. If this is the case, the API should not be much different from what you use on the desktop to access a web service. Sravan.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to modify a bound texture in OpenGL ES 1.1 My platform is iPhone - OpenGL ES 1.1 I'm looking for the tutorial about modifying or drawing to a texture. For example: I have a background texture: (Just blank blue-white gradiant image) and a object texture: I need to draw the object to background many times so to optimize the performance I want to draw it to the background texture like this: does anyone know the fastest way to do this ? Thanks a lot ! A: Do you want to draw it into the background texture, and then keep that, or overlay it, or what? I'm not entirely sure the question. To draw onto the background and then reuse that, you'll want to create another texture, or a pbuffer/fbo, and bind that. Draw a full-screen quad with your background image, then draw additional quads with the overlays as needed. The bound texture should then have the results, composited as necessary, and can be used as a texture or copied into a file. This is typically known as render-to-texture, and is commonly used to combine images or other dynamic image effects. To optimize the performance here, you'll want to reuse the texture containing the final results. This will reduce the render cost from whatever it may have been (1 background + 4 faces) to a single background draw. Edit: This article seems to have a rather good breakdown of OpenGL ES RTT. Some good information in this one as well, though not ES-specific. To overlay the decals, you simply need to draw them over the background. This is the same drawing method as in RTT, but without binding a texture as the render target. This will not persist, it exists only in the backbuffer, but will give the same effect. To optimize this method, you'll want to batch drawing the decals as much as possible. Assuming they all have the same properties and source texture, this is pretty easy. Bind all the textures and set properties as needed, fill a chunk of memory with the corners, and just draw a lot of quads. You can also draw them individually, in immediate mode, but this is somewhat more expensive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: uiprogressview jumps to 99% then 100% using ASIFormDataRequest I'm trying to implement a UIProgressView for an image upload so I set it up with uploadProgress = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; [uploadProgress setFrame:CGRectMake(85, 19, 150, 9)]; imageRequest = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:@"http://theurl.com"]]; [imageRequest setDelegate:self]; [imageRequest setDidFinishSelector:@selector(uploadedImage:)]; [imageRequest setDidFailSelector:@selector(asiRequestFailed:)]; [imageRequest setTimeOutSeconds:60]; [imageRequest addData:imgData forKey:@"file"]; [imageRequest addPostValue:[parameters yajl_JSONString] forKey:@"json"]; [imageRequest setUploadProgressDelegate:uploadProgress]; [imageRequest setShowAccurateProgress:YES]; [imageRequest startAsynchronous]; It loads for awhile, then jumps to almost 100% then it gets to 100%, then after a couple seconds, it completes. Is there something I'm missing in my code, or do I need to do something on the server side? Thanks A: Tracking a Post operation is always going to have this issue. The data uploads, and then your app has to wait for the response from your server that it has completed successfully. The ASIFormDataRequest is aware of the incremental sending of data, so it can track this progress accurately up until the last bit of data is sent. It can't however, know how long your server will take to respond to confirm that the entire upload has been received successfully (when your didFinishSelector is called). Your upload is fast, and progress is tracked up to 99%, then sits at 99% until uploadImage is called, which signals it's completion, 100%.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode 4 Templates—How to add license to beginning of file? I've spent hours trying to figure this out. In my custom Xcode 4 template, I have a checkbox option to include the zlib/libpng license at the top of each source file. Trouble is, no matter what I do I can't make it tack it on to the beginning of the file AND keep the rest of the file. It either shows // THIS IS A TEST and nothing else, or the whole file but not the test comment. I've tried what is shown in the screenshot above and dozens of other things. Help! A: I figured it out, finally. As you can see in the image above, for every source file I have two rules, :comments and :content. In the Definitions, I set the :content of each to the rest of the file (all in a big string), and in the option i set just the comments of every file depending on whether the checkbox is checked or not. Since the definitions for the files are now strings, not paths, I had to keep the dictionaries for the header files just to keep the <key>TargetIndices</key> <array/> so they don't get added to the Copy Bundle Resources build phase.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does window.postMessage guarantee the order of events? window.onmessage = ... window.postMessage('1', '*'); window.postMessage('2', '*'); Does postMessage (http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#queue-a-task) guarantee the order of events? A: window.postMessage() only triggers a message event on being invoked, and as with classic event publish-subscribe mechanism, there is not real guarantee of the order in their order. A: I don't know, although the wording of the spec seems to suggest it doesn't make such guarantees (which is surprising). It's clear that once the MessageEvent is added to the task queue on the receiving end, then it's order is maintained, although the MessageEvent creation and dispatch are asynchronous to the original postMessage call, so theoretically it appears that you could have the following situation: main thread: window.postMessage('1', '*'); --> thread spawned to create MessageEvent window.postMessage('2', '*'); --> new thread spawned for another MessageEvent If the thread management system allowed the second postMessage to execute before the first thread managed to dispatch the MessageEvent, and for whatever unlucky reason allowed that newer thread to execute (a diluted priority inversion), again before the first managed to dispatch, then you would indeed receive those messages in the reverse order. Although there might be some other place in the spec that provides more context for these asynchronous executions and rules out this case - I couldn't find it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: JSON variable returning correct but value is undefined? Here is my success function for my ajax request via jquery, success: function(response) { if (response.error == undefined) { alert(response); } $('#' + id).after('<div id="emailMsg" class="error">' + response.error + '</div>'); } Because the value is coming back as undefined it alerts me the returned JSON which is... {"error":true} Why is this happening, surely when I call response.error I should get either true or false. UPDATE Variable is returning as a string and not boolean, my json_encode(); if (!$q -> rowCount()) { echo json_encode(array('error' => false)); } else { echo json_encode(array('error' => true)); } A: You might want to try adding the dataType: 'json' parameter to your $.ajax call. That will ensure that jQuery will take care of making the response an object for you. A: You need to first parse the JSON from a string into a JavaScript object. This can be done with JSON.parse(response). In old browsers that don't have native JSON, eval(response) works too, but is less secure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why am I getting a NameError for authlogic method after upgrade to Rails 3 I am doing an upgrade to Rails 3 and had originally been using authlogic. I now get a NameError: NameError (undefined local variable or method `require_no_user' 'require_no_user" is a method for authlogic that is put into the UserSessions Controller. But I'm getting an error and can't figure out why it is considered undefined. I updated the authlogic gem to 3.0.3, but that hasn't fixed it..... Yes, I will look into moving to Devise, but I really need to just get the basics of the upgrade done and hope I can do so...thanks. A: I had the same problem. Unfortunaltely its not described in the tutorial. Here is the answer: https://github.com/binarylogic/authlogic_example/blob/9b22672cd64fb31b405c000e207b2cae281baa58/app/controllers/application_controller.rb
{ "language": "en", "url": "https://stackoverflow.com/questions/7536905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get Exact Time format using select query I'm using below query to get the time as AM/PM format eg:- if time is 2011-10-10 13:10:10 in database it will return as 1:10 PM I just want to fetch like 01:10 PM I used below query to fetch the above result SELECT SUBSTRING(CONVERT (varchar,FromDateTime,100),13,7)+' - '+SUBSTRING(CONVERT (varchar,ToDateTime,100),13,7) as EventTime FROM tblEvent How to get the time time like 01:10 AM A: You could convert the datetime value using the default format, then extract the time portion and slightly modify it to guarantee the leading zero's presence when it's needed: SELECT RIGHT('0' + LTRIM(RIGHT(CONVERT(varchar, GETDATE()), 7)), 7) A: you can directly use convert with 108 as parameter see here
{ "language": "en", "url": "https://stackoverflow.com/questions/7536907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I use EXCLUDED_SOURCE_FILE_NAMES in XCode 4 (iOS) I've found several references to a build setting in XCode called EXCLUDED_SOURCE_FILE_NAMES - the pattern below hints at how it works. But I can't figure out how to use this option in XCode (4.02). "EXCLUDED_SOURCE_FILE_NAMES[sdk=iphoneos*][arch=*]" = ... The goal is to have one or more source files compile when the target is the Simulator, and a different set of source files compile when the target is an iOS device. I figure I need to tell xcode the list of files for each target. So, how do I implement that using this setting? Where in XCode does it go? Is there any documentation for how to do this? I also need to do the same thing with a static lib. Specifically - I have a static lib I want to include in my project, but the lib only supports arm not i386, so, when building for the simulator, I need to exclude this file from being linked! Can this be done? A: Basically EXCLUDED_SOURCE_FILE_NAMES will just remove those files from that build configuration If you want to remove a static library from a build configuration, then this is the way to go. To implement this, just go to the "Build Settings" of your Target, then click on the "Add Build Setting" button and add the EXCLUDED_SOURCE_FILE_NAMES configuration for your target. Then you can specify which file names to exclude for each build configuration... In your case and since you mentioning a list of different files, then you should probably create 2 set of app bundles, then exclude the bundles in the EXCLUDED_SOURCE_FILE_NAMES So if you create a bundle named simulator.bundle and a bundle named release.bundle you would exclude the simulator.bundle file in the Release Configuration and the release.bundle in the simulator configuration...
{ "language": "en", "url": "https://stackoverflow.com/questions/7536908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: HTML5 Mobile App that accesses Java library? I am working on HTML5 mobile app, that needs a Java library to be complete. So I want to know exactly how to invoke java method from within javascript? The HTML5 will be wrapped in a WebView or something in Android app. I need to know exactly how to invoke the java library from within HTML5. Please be as specific as possible. A: Have you checked out PhoneGap? It lets you build Android apps in HTML5 using a WebView and also lets you create Plugins written in Java and Objective-C. PhoneGap http://www.phonegap.com/ Examples: https://github.com/phonegap/phonegap-plugins
{ "language": "en", "url": "https://stackoverflow.com/questions/7536910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook Graph API Explorer won't POST scores According to Facebook documentation: "Create or update a score for a user You can post a score or a user by issuing an HTTP POST request to /USER_ID/scores with the app access_token as long as you have the publish_actions permission." So I obtain the app access token from the access token tool. I have also verified that the publish_actions permission is enabled. When I use the API Explorer for /USER_ID/scores with app access token I get the following error: { "error": { "message": "A user access token is required to request this resource.", "type": "OAuthException" } } OK. So I provide the user access token instead and I get: { "error": { "message": "(#15) This method must be called with an app access_token.", "type": "OAuthException" } } What am I doing wrong here? EDIT: It works as long as authentication is set to WEB instead of Mobile/Native. A: You need to POST the score using the application token. Since you are using the application token, you can no longer use /me so you will need to post to /userid/scores. If your application token isn't working, try one in this format temporarily: appID|appSecret You need to first make sure the user has granted publish_actions (verify by calling /userid/permissions). You also need to make sure you application is marked as a game. I just did this all myself via the Facebook Graph Explorer and it worked: A: If you have built your own Action-Type in the Open-Graph then you should select "no" at "Requires App Token to Publish" in the Action configuration page. It fixed my issue with "(#15) This method must be called with an app access_token."
{ "language": "en", "url": "https://stackoverflow.com/questions/7536912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: subdomain htaccess redirect I have searched Google for this thing but nothing found I would like to redirect any sub-domain to new page which is located in new directory example: if people write http://subdomain.example.com it will automatically redirect to http://subdomain.example.com/newdirectory/new-index.php A: You might want to do a url rewriting redirection RewriteEngine on RewriteRule ^(.*)$ / newdirectory/$1 [R] In my example I presumed new-index.php is actually call index.php so that it is easier and makes more sense to me. Have a look at: http://httpd.apache.org/docs/2.0/misc/rewriteguide.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7536915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL - Views - Super slow query This is a weird one. I am trying to use Views in MySQL (I'm reasonably new to MySQL with more experience with Sybase and SQL Server). Any way this new project we are using MySQL as it seems to have good performance. However to make querying for a web front end simpler we decided to create a few views, all work well, but they take forever to run. The views are very simple, just select statements (these tables do have a few million rows in them). Say for example this query: SELECT CAST(classifier_results.msgDate as DATE) AS mdate ,classifier_results.objClass AS objClass ,COUNT(classifier_results.objClass) AS obj ,classifier_results.subjClass AS subjClass ,COUNT(classifier_results.subjClass) AS subj FROM classifier_results WHERE (classifier_results.msgDate >= (curdate() - 20)) GROUP BY CAST(classifier_results.msgDate as DATE) ,classifier_results.objClass ,classifier_results.subjClass ORDER BY classifier_results.msgDate DESC When run as a normal select takes around 1.5 seconds to return a result. However when this query is put into a view (as is) - i.e. CREATE VIEW V1a_sentiment_AI_current AS SELECT CAST(classifier_results.msgDate as DATE) AS mdate ,classifier_results.objClass AS objClass ,COUNT(classifier_results.objClass) AS obj ,classifier_results.subjClass AS subjClass ,COUNT(classifier_results.subjClass) AS subj FROM classifier_results WHERE (classifier_results.msgDate >= (curdate() - 20)) GROUP BY CAST(classifier_results.msgDate as DATE) ,classifier_results.objClass ,classifier_results.subjClass ORDER BY classifier_results.msgDate DESC The query takes about 10 times longer (22-30 seconds). So I'm thinking maybe there is some optimization or query caching that doesnt work with Views or maybe there is some setting we've missed in the MySQL config. But is there any way to speed up this view so its just a nice placeholder for this query? Running EXPLAIN on the two queries: The normal select gives: 1, SIMPLE, classifier_results, ALL, idx_date, , , , 594845, Using where; Using temporary; Using filesort The view select gives: 1, PRIMARY, , ALL, , , , , 100, 2, DERIVED, classifier_results, ALL, idx_date, , , , 594845, Using where; Using temporary; Using filesort A: Try re-creating your view using this: CREATE ALGORITHM = MERGE VIEW `V1a_sentiment_AI_current` AS SELECT CAST(classifier_results.msgDate as DATE) AS mdate ,classifier_results.objClass AS objClass ,COUNT(classifier_results.objClass) AS obj ,classifier_results.subjClass AS subjClass ,COUNT(classifier_results.subjClass) AS subj FROM classifier_results WHERE (classifier_results.msgDate >= (curdate() - 20)) GROUP BY CAST(classifier_results.msgDate as DATE) ,classifier_results.objClass ,classifier_results.subjClass ORDER BY classifier_results.msgDate DESC More information on MySQL's view processing algorithms can be found here. A: This is a really common problem. It can be very hard to write DRY, re-usable SQL. There is a workaround I've found though. Firstly, as others have pointed out, you can and should use VIEWs to do this wherever possible using the set ALGORITHM = MERGE, so that any queries using them are optimised on the merged SQL statement's where clause rather than having the VIEW evaluated for the entire view which can be catastrophically large. In this case, since you cannot use MERGE because of the group/count aspect, you might want to try using a stored procedure that creates a temporary session table as a workaround. This technique allows you to write reusable queries that can be accessed from middleware / framework code and called from inside other stored procedures, so you can keep code contained, maintainable and reusable. I.e. if you know in advance that the query will be filtered on certain conditions, put those in a stored procedure. (It may be more efficient to post-filter the data set, or a combination - it depends how you use the data and what common sets are needed). CREATE PROCEDURE sp_create_tmp_V1a_sentiment_AI_current(parm1, parm2 etc) BEGIN drop temporary table if exists tmp_V1a_sentiment_AI_current; create temporary table tmp_V1a_sentiment_AI_current as SELECT CAST(classifier_results.msgDate as DATE) AS mdate ,classifier_results.objClass AS objClass ,COUNT(classifier_results.objClass) AS obj ,classifier_results.subjClass AS subjClass ,COUNT(classifier_results.subjClass) AS subj FROM classifier_results WHERE (classifier_results.msgDate >= (curdate() - 20)) -- and/or other filters on parm1, parm2 passed in GROUP BY CAST(classifier_results.msgDate as DATE) ,classifier_results.objClass ,classifier_results.subjClass ORDER BY classifier_results.msgDate DESC; END; Now, any time you need to work with this data, you call the procedure and then either select the result (possibly with additional where clause parameters) or join with it in any other query. The table is a session temporary table so it will persist beyond the call to the procedure. The calling code can either drop it once it's finished with the data or it'll go automatically when the session goes or a subsequent call to the sproc is made. Hope that's helpful. A: MERGE can't be used here because of the count() aggregates in the select list; it might help in these cases to specify TEMPTABLE to save the engine from having to decide between them. Once I'd decided which algorithm to use I'd look at the EXPLAIN plan and try to add an index hint or locate a missing index.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: FTSearch in Domino not working for Domino 851 server however it works fine for Domino 8 I have two Domino servers one having the version Domino 8 and the other having Domino 851. FTSearch API works fine with Domino 8 server(French server) and doesn't work fine with the Domino 851. The query is like "[_CreationDate] >= 1/1/2009". Date formats are handled well to generate the date in mm/dd/yyyy or dd/mm/yyyy. FTSearch API always returns 0(ZERO) when a query is made with the above said query. However there are messages in the domino server which are later 1/1/2009. System.out.println("DOMINO" + unFilteredView.getName());//($Inbox) retCount = unFilteredView.FTSearch(query,0); Code is in JAVA. Date search works fine in Domino851 if the messages in the server are full text indexed. However if messages are not indexed in the Domino 851, then search in it doesn't work. The error displayed in the Domino Server console is "full text operations on database mail\tuser.nsf which is not fully indexed. This is extremele inefficient" Please help me in resolving this. Thanks, Rajath. A: The error message states, that you are calling a full text operation on a server, where there is no full text index for the database enabled. As the FTI is a per database, per server setting, you have to enable it on all replicas of a database explicitly. Create/Enable the full text index on the Domino 8.5.1 server and the code will work. Best practice would be to use the Database.IsFTIndexed property of the Database class to check for an existing FTIndex, before you call the FT method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I set session timeout so that it never expires? How can I set session timeout so that it never expires? It's for a Java EE web application. A: Specify a negative time. <session-config> <session-timeout>-1</session-timeout> </session-config> The benefit is however questionable. The webapp will leak memory away on long term. Think twice before you do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Solr not loading a custom filter I have written a custom KeepWord filter factory and have put the resultant jar under solr/lib directory. But when starting solr I am getting this error SEVERE: org.apache.solr.common.SolrException: Error loading class 'org.custom.solr.analysis.MyKeepWordFilterFactory' at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:389) at org.apache.solr.core.SolrResourceLoader.newInstance(SolrResourceLoader.java:404) at org.apache.solr.util.plugin.AbstractPluginLoader.create(AbstractPluginLoader.java:83) at org.apache.solr.util.plugin.AbstractPluginLoader.load(AbstractPluginLoader.java:140) at org.apache.solr.schema.IndexSchema.readAnalyzer(IndexSchema.java:941) at org.apache.solr.schema.IndexSchema.access$100(IndexSchema.java:62) at org.apache.solr.schema.IndexSchema$1.create(IndexSchema.java:450) at org.apache.solr.schema.IndexSchema$1.create(IndexSchema.java:435) at org.apache.solr.util.plugin.AbstractPluginLoader.load(AbstractPluginLoader.java:140) at org.apache.solr.schema.IndexSchema.readSchema(IndexSchema.java:480) at org.apache.solr.schema.IndexSchema.<init>(IndexSchema.java:125) at org.apache.solr.core.CoreContainer.create(CoreContainer.java:461) at org.apache.solr.core.CoreContainer.load(CoreContainer.java:316) ... Caused by: java.lang.ClassNotFoundException: org.custom.solr.analysis.MyKeepWordFilterFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) ... This is the content of my solr instance directory. >$ ls solr/* solr/README.txt solr/conf: admin-extra.html mapping-ISOLatin1Accent.txt scripts.conf stopwords.txt velocity/ elevate.xml protwords.txt solrconfig.xml stopwords_en.txt xslt/ mapping-FoldToASCII.txt schema.xml spellings.txt synonyms.txt solr/data: index/ spellchecker/ solr/lib: my-solr-analyserfilter.jar The content of the jar file >$ unzip -l solr/lib/my-solr-analyserfilter.jar Archive: solr/lib/ctown-solr-analyserfilter.jar Length Date Time Name -------- ---- ---- ---- 0 09-23-11 23:07 META-INF/ 60 09-23-11 23:07 META-INF/MANIFEST.MF 3330 09-23-11 23:07 org/custom/analysis/MyKeepWordFilterFactory.class -------- ------- 3390 3 files I am using solr version 3.4.0. As per documentation - https://wiki.apache.org/solr/SolrPlugins#How_to_Load_Plugins - keeping the jar file under lib directory should have made solr detect the jar. But apparently it's not happening. What am I doing wrong? Kindly help me in resolving this issue. A: Couple of things - 1. org.custom.solr.analysis.MyKeepWordFilterFactory does not match the contents of your jar file org/custom/analysis/MyKeepWordFilterFactory.class. The solr package is missing. 2. If it still does not find it. Check if the entry in solrconfig.xml is uncommented and the jar file is loaded when the server starts up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cacheing Drawables on a large ListView of images If I have a ListView with heaps of images, I obviously can't have all the images stored in memory at once (too large). These images are downloaded from the internet as you move through the list, so removing an image from memory if it leaves the screen and re-downloading when you scroll back is silly lol. The average image size is approx 40kb about 500 x 500 Should I: 1) When an image is off-screen, compress & decode the image and store it in a database as a byte[], then when the user scrolls back to the item, it displays a 'loading' symbol over the image in the UI thread while decoding the image in the background (so as to not lag the scroll), and clear this database on exit or when it gets larger than say 100 images. I'm assuming that decoding an image is relatively quick (less than a second) or 2) Save this image on the filesystem, and it's location on a database, and fetch the image when the user scrolls to an item, and remove the image from the db and filesystem on exit or when the filesystem gets full (seems like it would take up more room on the phone than option 1). This also seems harder and more annoying to keep the database and the filesystem in 'sync'. or 3) your suggestion =D Thanks for your help :) A: I strongly recommend using WebImageView, part of the Droidfu library. It handles downloading the images asynchronously (with a placeholder animation while it is doing so) and then also caches the images intelligently for you so you don't have to worry about storing the images. http://brainflush.wordpress.com/2009/11/23/droid-fu-part-2-webimageview-and-webgalleryadapter/
{ "language": "en", "url": "https://stackoverflow.com/questions/7536934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring - setter injection method modifier Totally basic question, but what type of modifier is allowed for doing Spring setter injection. I am using Spring Proxy AOP and notice that only public methods are proxied and so thought about switching my setters methods in my classes to protected/package...would setter injection still work? I couldn't find anything in the docs about the modifier type. A: For beans configured via XML I think the setter methods have to be public. By default Spring AOP uses dynamic proxies which only applies to methods defined as part of interfaces. So by not including the setter methods in the interface you can exclude them from AOP. A: * *I am using Spring Proxy AOP and notice that only public methods are proxied from Spring Documentation: "Due to the proxy-based nature of Spring's AOP framework, protected methods are by definition not intercepted, neither for JDK proxies (where this isn't applicable) nor for CGLIB proxies (where this is technically possible but not recommendable for AOP purposes). As a consequence, any given pointcut will be matched against public methods only!" "If your interception needs include protected/private methods or even constructors, consider the use of Spring-driven native AspectJ weaving instead of Spring's proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving first before making a decision."
{ "language": "en", "url": "https://stackoverflow.com/questions/7536937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: div height needs to grow based on div next to it Here's the url to the page: http://whiterootmedia.com/test I need the right brown div to grow when the grey div content expands. I'm vertically repeating a background image in the brown div. <body style="margin: 0px; min-width: 700px; height: 100%;"> <div class="site" style="background: yellow; min-width: 577px; height: 100%;"> <div class="banner" style="background: blue; height: 100px; width: 417px; float: left;"> Banner Banner Banner Banner Banner </div> <div class="body_container" style="background: pink; height: 100%;"> <div class="ads" style="background: brown; width: 160px; position: absolute; right: 0px; height: 100%; clear: left;"> Ads Ads Ads Ads Ads Ads Ads Ads Ads </div> <div class="tree" style="background: grey; white-space: nowrap; width: auto; min-width: 417px; clear: left;"> Content Content Content Content Content Content Content Content Content Content <br /> </div> </div> <div class="grass" style="background: green; height: 100px;"> </div> </div> </body> A: The classic way of doing this is using a technique called Faux Columns. The idea is to put the repeating background image on the container, and background-position: 100% 0 to put it on the right side and make it look like it's the background of the right column. (The right column would have a transparent background.) You don't need to worry about the height of the column, since the background fills the height of the container instead. A: Try using this script var tree_height = $('.tree').height(); var tree_top = $('.tree').offset().top; var ads_height = tree_height + tree_top ; $('.ads').css('height',ads_height); A: there is easy way, set overflow: hidden for wrapper and for columns set padding-bottom: 9999px; margin-bottom: -9999px;
{ "language": "en", "url": "https://stackoverflow.com/questions/7536943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASPxNavBar state not being persisted I am using the ASPxNavBar on the master page of my sharepoint site (Sharepoint Foundation 2010). I have succefully integrated the control so that it functions properly however i am have a problem that the state of the navbar (which groups are open) is not being persisted) Here is some of the code <Sharepoint:SPNavigationManager id="QuickLaunchNavigationManager" runat="server" QuickLaunchControlId="ASPxNavBar1" ContainedControl="QuickLaunch" EnableViewState="false"> <dx:ASPxNavBar ID="ASPxNavBar1" AutoCollapse="true" Paddings-PaddingLeft="0" Paddings-PaddingRight="0" Paddings-PaddingTop="0" runat="server" GroupSpacing="0" AllowSelectItem="true" BackColor="Transparent" ForeColor="White" Width="220px" ItemLinkMode="TextOnly" EnableAnimation="true" ShowExpandButtons="true" AllowExpanding="true" ItemStyle-SelectedStyle-Font-Italic="true" ItemStyle-SelectedStyle-Font-Bold="true" ExpandImage-Url="/_layouts/images/FamilyCarePRL/Buttons/Expand.png" CollapseImage-Url="/_layouts/images/FamilyCarePRL/Buttons/Contract.png" SaveStateToCookies="True" > <GroupHeaderStyle Height="40" BackColor="Transparent"> <BackgroundImage ImageUrl="/_layouts/images/FamilyCarePRL/Buttons/NavBarButtonGradient.png" Repeat="RepeatX" /> <Border BorderColor="Black"></Border> </GroupHeaderStyle> <Groups> <dx:NavBarGroup Name="AboutUs" Text="About Us"> <Items> <dx:NavBarItem Name="Vision" Text="Our Vision"> <Template> <asp:ImageButton ID="ImageButton1" ImageUrl="/_layouts/images/FamilyCarePRL/Buttons/Vision.png" PostBackUrl="<% $SPUrl:~SiteCollection/SitePages/Vision.aspx%>" runat="server" /> </Template> </dx:NavBarItem> . . The problem is that when i click on the image button it takes you to the site page but the state of the NavBar is not persisted. I have set SaveStateToCookies to true but that doesn't seem to work. Any suggestions are much appreciated A: The ASPxNavBar synchronizes the selected NavBarItems according to the NavigateUrl and page Url. To resolve this issue, specify the NavBarItem's NavigateUrl as follows: <dx:NavBarItem ... NavigateUrl="<% $SPUrl:~SiteCollection/SitePages/Vision.aspx%>"> </dx:NavBarItem>
{ "language": "en", "url": "https://stackoverflow.com/questions/7536951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenGL ES 2.0 Shader best practices I've been searching for examples of shaders in OpenGL and I've seen some varying styles. Some shaders specifically use the built in types (ie. gl_Vertex) to transfer data to and from the application code and the shader. Some shaders use the varying types to transfer data from vertex to fragment shader instead of gl_Position and gl_FragColor. Some shaders use the prefixes 'in' and 'out' to specify data transfer: in vec3 vertex; void main() { gl_Position = projection_matrix * modelview_matrix * vec4(vertex, 1.0); } ... while others use attributes: attribute vec4 vertex_attrib; attribute vec4 tex_coord_attrib; attribute vec4 color_attrib; uniform mat4 mvp_matrix; uniform mat4 texture_matrix; varying vec4 frag_color; varying vec2 tex_coord; void main(void) { gl_Position = mvp_matrix * vertex_attrib; vec4 transformed_tex_coord = texture_matrix * tex_coord_attrib; tex_coord = transformed_tex_coord.st / transformed_tex_coord.q; frag_color = color_attrib; } My question is, what is the preferred way in GLES 2.0 to write shaders? Is there a best practices guide? Can someone provide an example of a vertex & fragment shader that is a shining example of 'what to do'?? Thanks. A: * *There is no gl_Vertex in "ES 2.0". All attributes provided by you are custom. *gl_Position is not an option in ES 2 but a requirement. Learn about OpenGL pipeline to understand why. Hint: it could be optional only when rasterizer is disabled (Transform Feedback, for example) but this is not supported in ES. *In ES 2.0 vertex attributes have to have 'attribute' value and varyings have to be declared as 'varying'. Using 'in' and 'out' instead is a habit developed under OpenGL 3+ and can not be applied to ES. Finally, the best option for you would be to read OpenGL ES 2.0 Specification as suggested by Nicol Bolas. Rules first, best practices - later. Good luck! A: Your biggest problem is that you're looking at desktop GLSL shaders and trying to figure out what that means for GLSL-ES. Just as OpenGL ES is not the same thing as OpenGL, GLSL-ES is not the same thing as GLSL. GLSL has progressed rather far in the many years since GLSL-ES split off. Therefore, you cannot use desktop GLSL shaders as anything more than a rough guide for implementing GLSL-ES shaders. Any more than you could use C++ texts as a guide for C. The languages are quite similar, but desktop GLSL had to abandon a lot of keywords that GLSL-ES has not ditched yet. Similarly, old-school GLSL (1.20) implemented a lot of things that GLSL-ES and later versions of GLSL removed, like built-in inputs and outputs. So you will see a lot of desktop GLSL shaders that will flat-out not work on GLSL-ES. Indeed, if you find some that do, it will only be by sheer accident. I don't know much about guides to GLSL-ES, but the easiest to find and use is the ultimate source: The OpenGL ES Shading Language Specification (PDF). Extensions can pile on functionality, but that PDF defines the core language. Your next bet would be any material explicitly marked as OpenGL ES 2.0 specific. Basically, while you can understand what a desktop GLSL shader is doing, it is best to look at the algorithm and not the syntax if you're writing an OpenGL ES 2.0 application. A: There is sample code for OpenGL ES 2.0 in the Android Developer OpenGL ES 2.0 tutorials and also in the sdk sample code. But you will still need the very same reference file people keep on mentioning: The OpenGL ES Shading Language Specification" to understand that sample code, since Google does not often explain what they are doing. And when they do, they don't always stick to standard OpenGL terminology. That said, you may find it easier to refer to the OpenGL ES 2.0 Reference pages at http://www.khronos.org/opengles/sdk/docs/man/ while reading code. A: From what I understand, you should be able to compile GLSL to SPIR-V, then decompile it to GLSL ES to get a working shader again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Using the identifier of an object to change settings in flex well i want this actually <s:Button x="240" id="anything" y="80" label="User 4" click="click_Handler(event.currentTarget.id)" /> protected function click_Handler(s:String) { s.width ="xx" ; } Well in this code of course s.width cant be done. any ideas about how to do this. i must change the width when i click on the button. A: you need to use the id of the object, or pass the object reference instead of just its id to the event handler. In the example you have given the id is anything. Make sure this is unique for each object instance in the MXML. One option is to directly refer to the stage instance. The code will be like this protected function click_Handler(s:String){ anything.width ="xx" ; } The other option is to pass either the event object (which is a good practice) or at least the target object to event handler, and use that. The code will be like this: <s:Button x="240" id="anything" y="80" label="User 4" click="click_Handler(event)" /> protected function click_Handler(e:Event){ ((DisplayObject)(e.currentTarget)).width = "xx" }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reset PHP Array Index I have a PHP array that looks like this: [3] => Hello [7] => Moo [45] => America What PHP function makes this? [0] => Hello [1] => Moo [2] => America A: If you want to reset the key count of the array for some reason; $array1 = [ [3] => 'Hello', [7] => 'Moo', [45] => 'America' ]; $array1 = array_merge($array1); print_r($array1); Output: Array( [0] => 'Hello', [1] => 'Moo', [2] => 'America' ) A: Use array_keys() function get keys of an array and array_values() function to get values of an array. You want to get values of an array: $array = array( 3 => "Hello", 7 => "Moo", 45 => "America" ); $arrayValues = array_values($array);// returns all values with indexes echo '<pre>'; print_r($arrayValues); echo '</pre>'; Output: Array ( [0] => Hello [1] => Moo [2] => America ) You want to get keys of an array: $arrayKeys = array_keys($array);// returns all keys with indexes echo '<pre>'; print_r($arrayKeys); echo '</pre>'; Output: Array ( [0] => 3 [1] => 7 [2] => 45 ) A: The array_values() function [docs] does that: $a = array( 3 => "Hello", 7 => "Moo", 45 => "America" ); $b = array_values($a); print_r($b); Array ( [0] => Hello [1] => Moo [2] => America ) A: you can use for more efficient way : $a = [ 3 => "Hello", 7 => "Moo", 45 => "America" ]; $a = [...$a];
{ "language": "en", "url": "https://stackoverflow.com/questions/7536961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "141" }
Q: uiscrollview textured background is compressed after frame animation I have a UIScrollView which is resized when the keyboard is presented (to stay above the keyboard as it slides in from the bottom.) To make the animation work right I have to specify UIAnimationOptionBeginFromCurrentState. If I don't specify this I get weird effects during the animation and I can see the view behind the UIScrollView peek through. Here's the animation routine: - (void) onKeyboardWillShow: (NSNotification*) n { // get the keyboard rect CGRect rKeyboard; NSValue* v; v = [n.userInfo objectForKey: UIKeyboardFrameEndUserInfoKey]; [v getValue: &rKeyboard]; rKeyboard = [self.view convertRect: rKeyboard fromView: nil]; // get the keyboard animation duration, animation curve v = [n.userInfo objectForKey: UIKeyboardAnimationDurationUserInfoKey]; double keyboardAnimationDuration; [v getValue: &keyboardAnimationDuration]; v = [n.userInfo objectForKey: UIKeyboardAnimationCurveUserInfoKey]; UIViewAnimationCurve keyboardAnimationCurve; [v getValue: &keyboardAnimationCurve]; // animate [UIView animateWithDuration: keyboardAnimationDuration delay: 0 options: UIViewAnimationOptionBeginFromCurrentState | keyboardAnimationCurve animations: ^{ CGRect f = _clientAreaView.frame; f.size.height = rKeyboard.origin.y - f.origin.y; _clientAreaView.frame = f; } completion: ^(BOOL finished) { }]; } The problem is the UIScrollView backgroundColor, which is set to scrollViewTexturedBackgroundColor. After the animation the textured background is compressed (with minor artifacts showing). If I animate it all back to the original size it returns to normal. How to make it so the background either doesn't resize with the animation, or at least have the background 'pop' back to an uncompressed look post animation? I tried setting the bg color in the completion routine (to white, then back to scrollViewTexturedBackgroundColor, but this didn't work, and I dont really understand why.) A: I think your problem might be related to setting the value of UIKeyboardAnimationCurveUserInfoKey (which is a UIViewAnimationCurve and not a UIViewAnimationOption) along with UIViewAnimationOptionBeginFromCurrentState (which is supposed to capture the current state and modify it). Animating the frame of UIScrollView (and UITableView) is buggy on iOS, therefore you should animate the contentInset and scrollIndicatorInsets properties as well as the contentOffsetif you need to reposition your views (e.g. moving a text field up). Just add the height of the keyboard to the bottom part of the insets and calculate if you need to scroll up or down.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multi-page registration system: How to maintain state along the way? I built a system to allow new members to join an organisation last year when I was just starting out as a programmer. It's a multi-step process across several pages that concludes after a successful credit card transaction. Part of the complication was the requirement for family memberships, which recorded the details of everyone in the family and created records for them as well. Originally, I maintained the form input data across the steps using arrays in session variables and the data was committed to the DB after a the credit card payment went through. I'm now completely rebuilding it since I've learned a lot since then and it's become too messy to maintain, but I still have no idea what the best way to manage this data is. The original rationale was that because there were a lot of steps, and the requirement for a payment at the end, it seemed to make no sense to commit data to the DB until the process was complete, especially since it involved records in multiple tables and the idea of having to periodically flush out the incomplete records seemed like unnecessary and overly complicated effort. Having done it the first time around, the arrays in session variables got extremely messy and involved a lot of verification in the code since it was potentially error-prone. I also lost a lot of time trying to correct for session timeouts (which seemed to happen far more often than I would have expected when I was developing). So I ask those with far more knowledge and experience than myself: What is the best way to maintain temporary data through a multipage registration process? A: There aren't that many different approaches to handle this generally speaking. Either all the data will persist in the session, or just a unique identifier persists in the session that allows you to query out all the data that lives in the database throughout the process. Sessions are volatile though, so the database is a better approach. Save each step of partial data into the database, but have a column like "completed" or "committed" in each relevant table that is 0 by default, and only when the process is completed flag them all to 1. It really isn't too much trouble to write a php script that gets called by cron once a night to go delete all the records that are committed=0 and last modified > 1 day (you do have a column that auto-updates a timestamp when modified right? ) or something like that. Or better yet instead of deleting, move them to another table called "warm_leads" - people who were interested in your service but bailed out for some reason and have sales/customer service follow up. also, increase the session timeout to 1 or 2 hours: ini_set(’session.gc_maxlifetime’, 120*60); // 120 minutes Or have an AJAX request that fires every 10 minutes on each page that essentially is performing a session keep-alive to extend sessions as long as the browser is open and javascript isn't broken. The other good news is with the database persisting data, you only need to validate it once on the way in, and not on every step. A: Here is my other idea. If you are not wanting to use SESSIONS at all you could use Javascript (Yeah hear me out on this). So basically you would load the whole form at once then hide parts of it, when someone clicks next to move on to the next steps in the processes it would show (you could even animate a slide) the hidden part and hide what they just completed. So you wouldn't be loading different pages but 'sliding' content in and out of view of the user. You could verify that the user has entered data as well before moving on, but you would not be saving the data and you wouldn't need to. Here would be an example in jQuery (Note it doesn't show fields but you get the idea.) http://cssglobe.com/lab/easyslider/03.html Click the down button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Game center takes forever to show disconnected When game center has a match running and one player disconnects it takes at least 30 seconds for the disconnect method to get called. Any ideas on how to make the disconnect method called as soon as the opponent quits the applications. (void)match:(GKMatch *)theMatch player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state { if (match != theMatch) return; switch (state) { case GKPlayerStateConnected: // handle a new player connection. NSLog(@"Player connected!"); if (!matchStarted && theMatch.expectedPlayerCount == 0) { NSLog(@"Ready to start match!"); [self lookupPlayers]; } break; case GKPlayerStateDisconnected: // a player just disconnected. NSLog(@"Player disconnected!"); matchStarted = NO; [delegate matchEnded]; break; } } A: I am not sure but i have one suggestion for you ... if you are using threading than quit the thread forcefully ... and check this links for know more about threading... http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html And check the how to Terminating a Thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JAXB marshalling and unmarshalling CDATA I have a requirement in which i have XML like this <programs> <program> <name>test1</name> <instr><![CDATA[ some string ]]></instr> </program> <program> <name>test2</name> <instr><![CDATA[ some string ]]></instr> </program> </programs> My program needs to unmarshal this to JAXB, do some processing and finally marshall back to xml. When I finally marshall the JAXB objects to xml, i get the as plain text without CDATA prefix. But to keep the xml intact I need to get the xml back with CDATA prefix. It seems JAXB doesnt suppor this directly. Is there a way to achieve this? A: CDATA or not, this should not be a problem since the output from JAXB will be escaped if needed. A: I've also had the same problem and while looking in SO I found this post. Since I'm generating my beans with xjc I did not want to add a @XmlCData in the generated code. After looking a while for a good solution I finally found this post: http://javacoalface.blogspot.pt/2012/09/outputting-cdata-sections-with-jaxb.html Which contains the following example code: DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); Document document = docBuilderFactory.newDocumentBuilder().newDocument(); // Marshall the feed object into the empty document. jaxbMarshaller.marshal(jaxbObject, document); // Transform the DOM to the output stream // TransformerFactory is not thread-safe StringWriter writer = new StringWriter(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer nullTransformer = transformerFactory.newTransformer(); nullTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); nullTransformer.setOutputProperty( OutputKeys.CDATA_SECTION_ELEMENTS, "myElement myOtherElement"); nullTransformer.transform(new DOMSource(document), new StreamResult(writer)); It works pretty fine for me. Hope it helps others that land in this page looking for the same thing I was. A: Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group. You can use MOXy's @XmlCDATA extension to force a text node to be wrapped with CDATA: package blog.cdata; import javax.xml.bind.annotation.XmlRootElement; import org.eclipse.persistence.oxm.annotations.XmlCDATA; @XmlRootElement(name="c") public class Customer { private String bio; @XmlCDATA public void setBio(String bio) { this.bio = bio; } public String getBio() { return bio; } } For More Information * *http://blog.bdoughan.com/2010/07/cdata-cdata-run-run-data-run.html *http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7536973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: drupal mutisite we develop two sites in drupal both sites have different urls and different drupal instance but some pages in the both site have common. If we edit one page (common) in the both site.we need to login to both sites and edit them.instead of doing like this if edit one site its automatically reflect in particular page in second site.is there any module to provide such functionality or interconnecting two sites.Kindly any one share me how to handle this. Note : This sites developed in drupal 6.x Thanks............. A: The Domain Access Module does exactly that A: You can also achieve single sign on by sharing common tables related to user information and same $cookie_domain in the settings.php Something like following in settings.php: $db_prefix = array( 'default' => '', 'users' => 'example_shared_db.', 'sessions' => 'example_shared_db.', 'role' => 'example_shared_db.', 'users_roles' => 'example_shared_db.', 'profile_fields' => 'example_shared_db.', 'profile_values' => 'example_shared_db.', ); $cookie_domain = 'example.com'; A: You have two options 1. Domain Access module - http://drupal.org/project/domain - This module provide very useful set of feature which will allow you to get your multi-site setup done in lesser time. It has very friendly dashboard to manage your sites. 2. Folder based structure - you may refer any URL https://www.drupal.org/documentation/install/multi-site https://www.acquia.com/blog/power-drupal-multi-site-part-1-code-management http://www.ibm.com/developerworks/library/wa-multisitedrupal/ Please let me know in case you looking forward to implement any specific requirements. A: The best way to achieved this is by using Multi site setup for Drupal. Multi site use the same code base for both the site. You can opt to choose different or same database for your site. For you situation you can use the same database for both the domain. You can setup a same database for both the site if functionality doens't differs much.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 2D array object in Google Cloud Datastore I was just wondering if we are able to add a 2D array object into Google Cloud Datastore. Will the following code for adding using persistence manager be able to work? TwoDArray is a 2 Dimension object. Below is a method in my Data Manager. Thanks! public static void add(String username) { TwoDArray twoArray = new TwoDArray(username); PersistenceManager pm = PMF.get().getPersistenceManager(); try { pm.makePersistent(twoArray); } finally { pm.close(); } } A: You can make almost any object persistent, as long as it follows the rules for JDO persistence. That is about as specific as we can get unless you show us what your TwoDArray class looks like.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Java make bitmapfactory images clickable Alright so how can I do this.. I have 2 classes PlayActivity.java and Play.java PlayActivity's setContentView is play.java In play.java I have this: gBall1 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); gBall2 = BitmapFactory.decodeResource(getResources(), R.drawable.womentrans); gBall3 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); gBall4 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); gBall5 = BitmapFactory.decodeResource(getResources(), R.drawable.womentrans); gBall6 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); gBall7 = BitmapFactory.decodeResource(getResources(), R.drawable.womentrans); gBall8 = BitmapFactory.decodeResource(getResources(), R.drawable.womentrans); gBall9 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); gBall10 = BitmapFactory.decodeResource(getResources(), R.drawable.womentrans); gBall11 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); gBall12 = BitmapFactory.decodeResource(getResources(), R.drawable.mantrans); gBall13 = BitmapFactory.decodeResource(getResources(), R.drawable.womentrans); And these appear on the screen.. How exactly can I make them clickable and show a toast? A: You should set these bitmaps to an imageview and add a setOnClickListener to the imageview. That way the images can be clicked on. A: The basic premise here is that, in android, only a view is clickable. In your case the individual Bitmaps are contained is a View and therefore if a click listener can be applied to anything it has to be done on the View itself. i:e a bitmap cannot to made clickable unless it is put inside a view (ImageView in this case). Therefore i suggest you make your Play class extend a Layout like FrameLayout or LinearLayout. Then add all the bitmaps to ImageViews and add the imageviews to the class. this.addView(childImageView)
{ "language": "en", "url": "https://stackoverflow.com/questions/7536982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Comparing 2 arrays of symbols I'm new to ruby, and I've been googling for hours, but I can't figure this one out. It looks like it should be really easy so I'm getting pretty frustrated. I'm working in ruby and need to compare 2 arrays of symbols for a true or false return. array1 = [:a, :c] array2 = [:a, :b, :c] The comparison I need to do, is to see if array2 includes all the elements of array1. In this case array2 includes array1, but array1 does not include array2. I tried: array2.to_s.include?(array1.to_s) Which only returns true if they are in the same order because it needs to convert to a string for comparison. So as is it returns false (not what I'm looking for), but if array2 = [:a, :c, :b] it would be true. Is there a more appropriate way of making this comparison? A: You can use -. e.g.: array1 - array2 #=> returns empty array, if array2 include all array1 elements. Hope this can solve your problem. A: venj's answer is fine for small arrays but might not perform well (this is debatable) for large arrays. Since you're basically doing a set operation ("is Set(array1) a subset of Set(array2)?"), it makes sense to see how Ruby's own Set library does this. Set has a subset? method, and taking a peek at its source we see that it's short and sweet: def subset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if set.size < size all? { |o| set.include?(o) } end We could just instantiate two Set objects from the arrays and call it a day, but it's just as easy to distill it into a oneliner that operates directly on them: array1 = [:a, :c] array2 = [:a, :b, :c] array1.length < array2.length && array1.all? {|el| array2.include? el } # => true array1 << :z array1.length < array2.length && array1.all? {|el| array2.include? el } # => false A: You can add this method to the Array class. #!/usr/bin/env ruby class Array def includes_other(arr) raise "arr must be an Array" unless arr.kind_of? Array return (arr - self).length == 0 end end arr1 = [:a, :c, :e] arr2 = [:e, :a, :c, :d] puts arr2.includes_other(arr1) # prints true arr3 = [:x, :c, :e] puts arr3.includes_other(arr1) # prints false
{ "language": "en", "url": "https://stackoverflow.com/questions/7536986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android app out of memory issues - tried everything and still at a loss I spent 4 full days trying everything I can to figure out the memory leak in an app I'm developing, but things stopped making sense a long time ago. The app I'm developing is of social nature, so think profile Activities (P) and list Activities with data - for example badges (B). You can hop from profile to a badge list to other profiles, to other lists, etc. So imagine a flow like this P1 -> B1 -> P2 -> B2 -> P3 -> B3, etc. For consistency, I'm loading profiles and badges of the same user, so each P page is the same and so is each B page. The general gist of the problem is: after navigating for a bit, depending on the size of each page, I get an out-of-memory exception in random places - Bitmaps, Strings, etc - it doesn't seem to be consistent. After doing everything imaginable to figure out why I am running out of memory, I have come up with nothing. What I don't understand is why Android isn't killing P1, B1, etc if it runs out of memory upon loading and instead crashes. I would expect these earlier activities to die and be resurrected if I ever Back to them via onCreate() and onRestoreInstanceState(). Let alone this - even if I do P1 -> B1 -> Back -> B1 -> Back -> B1, I still get a crash. This indicates some sort of a memory leak, yet even after dumping hprof and using MAT and JProfiler, I can't pinpoint it. I've disabled loading of images from the web (and increased the test data loaded to make up for it and make the test fair) and made sure the image cache uses SoftReferences. Android actually tries to free up the few SoftReferences it has, but right before it crashes out of memory. Badge pages get data from the web, load it into an array of EntityData from a BaseAdapter and feed it to a ListView (I'm actually using CommonsWare's excellent MergeAdapter, but in this Badge activity, there is really only 1 adapter anyway, but I wanted to mention this fact either way). I've gone through the code and was not able to find anything that would leak. I cleared and nulled everything I could find and even System.gc() left and right but still the app crashes. I still don't understand why inactive activities that are on the stack don't get reaped, and I'd really love to figure that out. At this point, I'm looking for any hints, advice, solutions... anything that could help. Thank you. A: Bitmaps are often the culprit for memory errors on Android, so that would be a good area to double check. A: Some tips: * *Make sure you are not leak activity context. *Make sure you are don't keep references on bitmaps. Clean all of your ImageView's in Activity#onStop, something like this: Drawable d = imageView.getDrawable(); if (d != null) d.setCallback(null); imageView.setImageDrawable(null); imageView.setBackgroundDrawable(null); *Recycle bitmaps if you don't need them anymore. *If you use memory cache, like memory-lru, make sure it is not using to much memory. *Not only images take alot of memory, make sure you don't keep too much other data in memory. This easily can happens if you have infinite lists in your app. Try to cache data in DataBase. *On android 4.2, there is a bug(stackoverflow#13754876) with hardware acceleration, so if you use hardwareAccelerated=true in your manifest it will leak memory. GLES20DisplayList - keep holding references, even if you did step (2) and no one else is referencing to this bitmap. Here you need: a) disable hardware acceleration for api 16/17; or b) detach view that holding bitmap *For Android 3+ you can try to use android:largeHeap="true" in your AndroidManifest. But it will not solve your memory problems, just postpone them. *If you need, like, infinite navigation, then Fragments - should be your choice. So you will have 1 activity, which will just switch between fragments. This way you will also solve some memory issues, like number 4. *Use Memory Analyzer to find out the cause of your memory leak. Here is very good video from Google I/O 2011: Memory management for Android Apps If you dealing with bitmaps this should be a must read: Displaying Bitmaps Efficiently A: Are you holding some references to each Activity? AFAIK this is a reason which keeps Android from deleting activities from the stack. We're you able to reproduce this error on other devices as well? I've experienced some strange behaviour of some android devices depending on the ROM and/or hardware manufacturer. A: I think the problem maybe a combination of many factors stated here in the answers are what is giving you problems. Like @Tim said, a (static) reference to an activity or an element in that activity can cause the GC to skip the Activity. Here is the article discussing this facet. I would think the likely issue comes from something keeping the Activity in an "Visible Process" state or higher, which will pretty much guaranty that the Activity and its associated resources never get reclaimed. I went through the opposite problem a while back with a Service, so that's what got me going on this thought: there is something keeping your Activity high on the process priority list so that it won't be subject to the system GC, such as a reference (@Tim) or a loop (@Alvaro). The loop doesn't need to be an endless or long running item, just something that runs a lot like a recursive method or cascaded loop (or something along those lines). EDIT: As I understand this, onPause and onStop are called as needed automatically by Android. The methods are there mainly for you to overide so that you can take care of what you need to before the hosting process is stopped (saving variables, manually saving state, etc.); but note that it is clearly stated that onStop (along with onDestroy) may not be called in every case. Additionally, if the hosting process is also hosting an Activity, Service, etc. that has a "Forground" or "Visible" status, the OS might not even look at stopping the process/thread. For example: an Activity and a Service are both luanched in the same process and the Service returns START_STICKY from onStartCommand() the process automatically takes at least a visible status. That might be the key here, try declaring a new proc for the Activity and see if that changes anything. Try adding this line to the declaration of your Activity in the Manifest as: android:process=":proc2" and then run the tests again if your Activity shares a process with anything else. The thought here is that if you've cleaned up your Activity and are pretty sure that the problem is not your Activity then something else is the problem and its time to hunter for that. Also, I can't remember where I saw it (if I even saw it in the Android docs) but I remember something about a PendingIntentreferencing an Activity may cause an Activity to behave this way. Here is a link for the onStartCommand() page with some insights on the process non-killing front. A: One of the things that really helped the memory issue in my case ended up being setting inPurgeable to true for my Bitmaps. See Why would I ever NOT use BitmapFactory's inPurgeable option? and the answer's discussion for more info. Dianne Hackborn's answer and our subsequent discussion (also thanks, CommonsWare) helped clarify certain things I was confused about, so thank you for that. A: I still don't understand why inactive activities that are on the stack don't get reaped, and I'd really love to figure that out. This is not how things work. The only memory management that impacts activity lifecycle is the global memory across all processes, as Android decides that it is running low on memory and so need to kill background processes to get some back. If your application is sitting in the foreground starting more and more activities, it is never going into the background, so it will always hit its local process memory limit before the system ever comes close to killing its process. (And when it does kill its process, it will kill the process hosting all the activities, including whatever is currently in the foreground.) So it sounds to me like your basic problem is: you are letting too many activities run at the same time, and/or each of those activities is holding on to too many resources. You just need to redesign your navigation to not rely on stacking up an arbitrary number of potentially heavy-weight activities. Unless you do a serious amount of stuff in onStop() (such as calling setContentView() to clear out the activity's view hierarchy and clear variables of whatever else it may be holding on to), you are just going to run out of memory. You may want to consider using the new Fragment APIs to replace this arbitrary stack of activities with a single activity that more tightly manages its memory. For example if you use the back stack facilities of fragments, when a fragment goes on the back stack and is no longer visible, its onDestroyView() method is called to completely remove its view hierarchy, greatly reducing its footprint. Now, as far as you crashing in the flow where you press back, go to an activity, press back, go to another activity, etc and never have a deep stack, then yes you just have a leak. This blog post describes how to debug leaks: http://android-developers.blogspot.com/2011/03/memory-analysis-for-android.html A: so the only thing i can really think of is if you have a static variable that references directly or indirectly to the context. Even something so much as a reference to part of the application. I'm sure you have already tried it but i will suggest it just in case, try just nulling out ALL of your static variables in the onDestroy() just to make sure the garbage collector gets it A: The biggest source of memory leak I have found was caused by some global, high level or long-standing reference to the context. If you are keeping "context" stored in a variable anywhere, you may encounter unpredictable memory leaks. A: Try passing getApplicationContext() to anything that needs a Context. You might have a global variable that is holding a reference to your Activities and preventing them from being garbage collected. A: I encountered the same problem with you. I was working on a instant messaging app, for the same contact, it is possible to start a ProfileActivity in a ChatActivity, and vice versa. I just add a string extra into the intent to start another activity, it takes the information of class type of starter activity, and the user id. For example, ProfileActivity starts a ChatActivity, then in ChatActivity.onCreate, I mark the invoker class type 'ProfileActivity' and user id, if it's going to start an Activity, I would check whether it is a 'ProfileActivity' for the user or not. If so, just call 'finish()' and go back to the former ProfileActivity instead of creating a new one. Memory leak is another thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "92" }
Q: How can I filter a Javascript array and maintain it's indices? Here is what I have currently: var myArray = []; myArray[15] = 2; myArray[6323] = 1; myArray[349022] = 3; myArray = myArray.filter(function(i,v,a){return ! (typeof v == 'undefined')}); myArray = myArray.sort(function(a,b){return (a - b)}); When I console.log() allocationOrder after the "filter" function, I get the values that I expect, but the indices are not maintained. How can I maintain the indices but also remove the undefined values (due to having spread out indices)? Keep in mind that I need to sort the array by value afterwards (which is why I avoided objects as a solution). A: If you're working with filter, you could supply it with an extra callback for the index and assign it in the returned object: source = source.filter((instance, index) => { instance.originalIndex = index; }); My usage was in working with adding options to a car, there was a filterable list of options, and each one could only be applied to the car once (meaning it needed to be stripped from the available options array as well as the filtered array). Hopefully that helps! A: You can't have your cake and eat it too. You can't have a sparse array (only some values filled in) and have no undefined values in between. That's just not how javascript arrays work. Further, you can remove the elements that have undefined values and expect the other values to stay at the same index. By defintion, removing those other values, collapses the array (changing indexes). Perhaps if you can describe what you're really trying to accomplish we can figure out a better way to approach the problem. I'm thinking that what you want is an array of objects where each object in the array has an index and a value. The indexes on the objects in the array will never change, but the container array can be sorted by those indexes. var mySortedArray = [ {index:15, value: 2}, {index:6323, value: 1}, {index:349022, value: 3} ]; mySortedArray = myArray.sort(function(a, b) {a.value - b.value}); Now you have a sorted array that's three elements long and it's sorted by value and the original index is preserved and available. The only drawback is that you can't easily access it by the index. If you wanted to be able to have both ordered, sorted access and access by the index key, you could make a parallel data structure that make key access quick. In Javascript, there is no single data structure that supports both key access and sorted order access. If you want to build a parallel data structure that would support fast access by key (and would include the value and the sortOrder value, you could build such an object like this: // build a parallel data structure for keyed access var myKeyedObject = {}, temp, item; for (var i = 0; i < mySortedArray.length; i++) { item = mySortedArray[i]; temp = {}; temp.value = item.value; temp.index = item.index; temp.sortOrder = i; myKeyedObject[item.index] = temp; } A: While JavaScript arrays behave rather nicely if you delete their entries, there is sadly no built-in function that does this. However, it isn't too hard to write one: Array.prototype.filterAssoc = function(callback) { var a = this.slice(); a.map(function(v, k, a) { if(!callback(v, k, a)) delete a[k]; }); return a; }; With this added to the array prototype, myArray.filterAssoc(...).map(...) will map over only the key-value pairs that were filtered for, just as expected. That answers the question in the title. As for your side note about wanting to sort the array afterward... sort does not behave nicely on sparse arrays. The easiest way to do that really is to sort an array of objects. A: You could map the original index before filtering. When filtering and eventually iterating over the items just destructure to get hold of the item and its original index. var fruit = ['apple', 'banana', 'mango']; fruit .map((item, index) => ({ item, index })) .filter(({ item }) => item == 'mango') .forEach(({ item, index}) => console.log(`${index} - ${item}`)); This will log 2 - mango.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Multiplying Two Columns in SQL Server How can I perform operations such as Multiplying and Subtracting two columns in SQL Server? Payment PK - PaymentID FK - PaymentTypeID FK - OccupiedApartmentID **- InitalPayment - MonthlyRate - Balance** - PaymentDate A: In a query you can just do something like: SELECT ColumnA * ColumnB FROM table or SELECT ColumnA - ColumnB FROM table You can also create computed columns in your table where you can permanently use your formula. A: Syntax: SELECT <Expression>[Arithmetic_Operator]<expression>... FROM [Table_Name] WHERE [expression]; * *Expression : Expression made up of a single constant, variable, scalar function, or column name and can also be the pieces of a SQL query that compare values against other values or perform arithmetic calculations. *Arithmetic_Operator : Plus(+), minus(-), multiply(*), and divide(/). *Table_Name : Name of the table. A: select InitialPayment * MonthlyPayRate as SomeRandomCalculation from Payment A: This code is used to multiply the values of one column select exp(sum(log(column))) from table A: select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment A: You can use the query: for multiplication Select columnA * cloumnB as MultiplyResult from TableName for subtraction Select columnA - cloumnB as SubtractionResult from TableName
{ "language": "en", "url": "https://stackoverflow.com/questions/7536996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }