text
stringlengths
8
267k
meta
dict
Q: XSLT transforming is throwing error I've xml as below, <?xml version="1.0" encoding="utf-16" ?> <AllResidentAndUnitInfo xmlns:i="http://www.w3.org/2001/XMLSchema-instance" i:type="ResidentsByUnitInfo" xmlns="http://schemas.datacontract.org/2004/07/FSRSchema"> <BillingAddresses> <BillingAddress> <billing_address1>Some address</billing_address1> <billing_address2 /> <billing_city>Gilbert</billing_city> <billing_country i:nil="true"/> <billing_dtmmodified>2010-12-08T01:37:41+05:30</billing_dtmmodified> <billing_state>AZ</billing_state> <billing_zipcode>23233</billing_zipcode> </BillingAddress> <BillingAddress> <ResidentsByUnitInfoPropertyUnitBillingAddress> <billing_address1>Some address</billing_address1> <billing_address2 /> <billing_city>Gilbert</billing_city> <billing_country i:nil="true"/> <billing_dtmmodified>2010-12-08T01:37:41+05:30</billing_dtmmodified> <billing_state>AZ</billing_state> <billing_zipcode>23233</billing_zipcode> </ResidentsByUnitInfoPropertyUnitBillingAddress> </BillingAddress> .... </AllResidentAndUnitInfo> I'm transforming into another xml format in C# using the XslCompiledTransform, <?xml version='1.0' ?> <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:msxsl='urn:schemas-microsoft-com:xslt' xmlns:i='http://www.w3.org/2001/XMLSchema-instance' exclude-result-prefixes='msxsl i' version='1.0'> <xsl:output method='xml' indent='yes'/> <xsl:template match='/AllResidentAndUnitInfo/BillingAddresses/BillingAddress'> <Root> <Address1>..</Address2> ... </Root> </xsl:template> </xsl:stylesheet> I'm getting the error "Token Text in state Start would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment." I understood the problem is with the i:nil attributes in the xml. Eventhough I included the namespace of them in XSLT still i'm getting the error. A: I'm getting the error "Token Text in state Start would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment." I understood the problem is with the i:nil attributes in the xml. Eventhough I included the namespace of them in XSLT still i'm getting the error. No. The problem is that the result isn't a well-formed XML document and thus the XmlWriter, involved in producing the final serialization of the result tree to text, raises this exception. Really, in your result you have two Root elements and none of them has a parent element. You need to produce a well-formed document, or change the ConformanceLevel setting for the XmlWriter to ConformanceLevel.Fragment or ConformanceLevel.Auto. To create a wellformed output, just add: <xsl:template match="/"> <top> <xsl:apply-templates/> </top> </xsl:template>
{ "language": "en", "url": "https://stackoverflow.com/questions/7634465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to write tuple range function in scala? I want following function range((1,1), (2,2)) which return Seq[(Int,Int)]((1,1),(1,2),(2,1),(2,2)) It is analog for one dimensional range with 1 to 2 The function should work for any scala tuple (i.e. Tuple2, Tuple3, Tuple4, ...) and be typesafe. I've tried with def tupleRange[T <: Product](t1:T, t2:T):Seq[T] = { assert(t1.productArity == t2.productArity) def tail(t:Product):Product = sys.error("todo"); def join(i:Int, p:Product):T = sys.error("todo"); for( v <- t1.productElement(0).asInstanceOf[Int] to t2.productElement(0).asInstanceOf[Int]; v2 <- tupleRange(tail(t1), tail(t2))) yield join(v,v2) } implicit def range[T <:Product](p1:T) = new { def to(p2:T) = tupleRange(p1,p2)} But I think I've chosen wrong direction. A: I'd suggest the same thing that @ziggystar suggested above. Use List[Int] instead of tuples of Ints. scala> import scalaz._ import scalaz._ scala> import Scalaz._ import Scalaz._ scala> def range(xs: List[Int], ys: List[Int]): List[List[Int]] = { | (xs, ys).zipped.map((x, y) => List.range(x, y + 1)).sequence | } range: (xs: List[Int], ys: List[Int])List[List[Int]] scala> range(List(1, 2, 4), List(2, 5, 6)) res29: List[List[Int]] = List(List(1, 2, 4), List(1, 2, 5), List(1, 2, 6), List(1, 3, 4), List(1, 3, 5), List(1, 3, 6), List(1, 4, 4), List(1, 4, 5), List(1, 4, 6), List(1, 5, 4), List(1, 5, 5), List(1, 5, 6), List(2, 2, 4), List(2, 2, 5), List(2, 2, 6), List(2, 3, 4), List(2, 3, 5), List(2, 3, 6), List(2, 4, 4), List(2, 4, 5), List(2, 4, 6), List(2, 5, 4), List(2, 5, 5), List(2, 5, 6)) This implementation assumes that xs and ys are ordered and have same length. A: First, consider this: scala> 1 to 10 res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) It'd be nice to have something like that for Tuples, right? class RangedTuple(t: Tuple2[Int, Int]) { def to(t2: Tuple2[Int, Int]) = { (t, t2) match { case ((a1: Int, a2: Int), (b1: Int, b2: Int)) => { (for { i <- a1 to b1 } yield (a1 to b1).map(j => (i, j))).flatMap(k => k) } } } } implicit def t2rt(t: Tuple2[Int, Int]) = new RangedTuple(t) This gives you the following: scala> (1, 1) to (2, 2) res1: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,1), (1,2), (2,1), (2,2)) scala> (1, 1) to (3, 3) res2: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3)) Does that work for you? A: You'll need a different version for each tuple-arity (but you can use a preprocessor to generate each version). Here is my implementation (which is lazy): def range2( range: Range ): Seq[(Int,Int)] = range.toStream.map( i => (i,i) ) You can use it as: scala> range2( 1 to 10 ) res3: Seq[(Int, Int)] = Stream((1,1), ?) A: Simple way with lots of cut and paste, overload the method for each tuple arity: def range(r: (Int, Int), s: (Int, Int)) = for { p1 <- r._1 to s._1 p2 <- r._2 to s._2 } yield (p1, p2) def range(r: (Int, Int, Int), s: (Int, Int, Int)) = for { p1 <- r._1 to s._1 p2 <- r._2 to s._2 p3 <- r._3 to s._3 } yield (p1, p2, p3) def range(r: (Int, Int, Int, Int), s: (Int, Int, Int, Int)) = for // etc up to 22 Alternatively: def range(p1: Product, p2: Product) = { def toList(t: Product): List[Int] = t.productIterator.toList.map(_.asInstanceOf[Int]) def toProduct(lst: List[Int]) = lst.size match { case 1 => Tuple1(lst(0)) case 2 => Tuple2(lst(0), lst(1)) case 3 => Tuple3(lst(0), lst(1), lst(2)) //etc up to 22 } def go(xs: List[Int], ys: List[Int]): List[List[Int]] = { if(xs.size == 1 || ys.size == 1) (xs.head to ys.head).toList.map(List(_)) else (xs.head to ys.head).toList.flatMap(i => go(xs.tail, ys.tail).map(i :: _)) } go(toList(p1), toList(p2)) map toProduct } seems to work: scala> range((1,2,4), (2,5,6)) res66: List[Product with Serializable] = List((1,2,4), (1,2,5), (1,2,6), (1,3,4), (1,3,5), (1,3,6), (1,4,4), (1,4,5), (1,4,6), (1,5,4), (1,5,5), (1,5,6), (2,2,4), (2,2,5), (2,2,6), (2,3,4), (2,3,5), (2,3,6), (2,4,4), (2,4,5), (2,4,6), (2,5,4), (2,5,5), (2,5,6)) Your basic problem is that since Scala is statically typed, the method needs to have a return type, so you can never have a single method that returns both a Seq[(Int, Int)] and a Seq[(Int, Int, Int)] and all the other arities of tuple. The best you can do is to use the closest type that covers all of the outputs, in this case Product with Serializable. You can of course do a cast on the result e.g. res0.map(_.asInstanceOf[(Int, Int, Int)]). Overloading the method as in the first example allows you a different return type for each arity, so you don't need to do any casting. A: How about an Iterator, and using two Seq instead of two tuples for initialization? Here is a class Cartesian, which extends Iterator. def rangeIterator (froms: Seq[Int], tos: Seq[Int]) = { def range (froms: Seq[Int], tos: Seq[Int]) : Seq[Seq[Int]] = if (froms.isEmpty) Nil else Seq (froms.head to tos.head) ++ range (froms.tail, tos.tail) new Cartesian (range (froms, tos)) } usage: scala> val test = rangeIterator (Seq(1, 1), Seq(2, 2)) test: Cartesian = non-empty iterator scala> test.toList res38: List[Seq[_]] = List(List(1, 1), List(2, 1), List(1, 2), List(2, 2)) scala> val test = rangeIterator (Seq(1, 0, 9), Seq(2, 2, 11)) test: Cartesian = non-empty iterator scala> test.toList res43: List[Seq[_]] = List(List(1, 0, 9), List(2, 0, 9), List(1, 1, 9), List(2, 1, 9), List(1, 2, 9), List(2, 2, 9), List(1, 0, 10), List(2, 0, 10), List(1, 1, 10), List(2, 1, 10), List(1, 2, 10), List(2, 2, 10), List(1, 0, 11), List(2, 0, 11), List(1, 1, 11), List(2, 1, 11), List(1, 2, 11), List(2, 2, 11))
{ "language": "en", "url": "https://stackoverflow.com/questions/7634474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: add class to if href starts with http://www.twitter.com/ Possible Duplicate: jQuery: Select <a> which href contains some string I am working on a little twitter implementation for a website. The javascript I use exports the code as following: <ul> <li>twitter message here <a href="http://twitter.com/username/ID">time of twitter</a></li> </ul> Now I like to add a class to the twitter link, so I can give it a different css then normal links inside the tweets. Anyone got any thoughts how to fix this in a proper way? :) A: $(function() { $("a[href^='http://twitter.com/']").addClass("someClass"); }); Check reference here: http://api.jquery.com/attribute-starts-with-selector/ A: $('a[href^="http://twitter.com"]').addClass('twitter'); http://jsfiddle.net/apjD6/
{ "language": "en", "url": "https://stackoverflow.com/questions/7634484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: mySQL fulltext learning I am creating an online FAQ type system using php and mySQL. The following SQL is what is used to find relevant questions based on what the user entered as $term. When a user searches for something and clicks on a relevant question to display the answer they get the chance to rate the question given based on what they searched for. The first part of the SQL gets relevant question ID's from the actual questions table. The second part looks at the ratings table and tries to match what people have previously searched for to find relevant question ID's. The union of these results is then used to get the actual question titles stored in the database. (SELECT id_question, MATCH(question, tags) AGAINST ('%$term%') as rank FROM question WHERE MATCH(question, tags) AGAINST ('%$term%') AND category = '$category') UNION (SELECT id_question, MATCH(customer_search_query) AGAINST ('%$term%') as rank FROM rating WHERE MATCH(customer_search_query) AGAINST ('%$term%') AND (customer_rating = 1)) ORDER BY rank DESC LIMIT 5;"); The problem I'm having is the system isn't really learning correctly. For example, if I type "three users", the system will find a match in the questions table. If I type "3 users", the system will find a match in the questions table (based on the keyword "users"). If I click "yes this answered my question" it will store "3 users" in the ratings table associating it with the question "three users". The issue is that "3" only becomes associated with "three users". Is there a way to associate the number 3 in this case with every instance of the word "three". A: You don't use wildcards in match against in natural language mode (the default). Use this query instead: (SELECT id_question, MATCH(question, tags) AGAINST ('$term') as rank FROM question WHERE MATCH(question, tags) AGAINST ('$term') AND category = '$category') UNION ALL <<-- faster than UNION. (SELECT id_question, MATCH(customer_search_query) AGAINST ('$term') as rank FROM rating WHERE MATCH(customer_search_query) AGAINST ('$term') AND (customer_rating = 1)) ORDER BY rank DESC LIMIT 5;"); You can use search modifiers in boolean mode. Also match against will not search for stopwords and words shorter than 4 chars. You when you use $term = "3 users", MySQL will only look for users and ignore the 3. If you want to search for 3 you'll have to revert to LIKE '% 3 %' See: http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html http://dev.mysql.com/doc/refman/5.0/en/fulltext-stopwords.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7634486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delphi XE2 FireMonkey and ssl does anyone know how to use ssl with Indy and get it to run under windowns and osX? I've seen the link below so TIdHttp appears to work but I need the ssl options. Firemonkey and TDownloadUrl Thanks A: If you are using the Indy components that came with XE2, then you can drop in the Windows SSL binaries from OpenSSL. For Windows, put these in the same folder as your EXE: * *libeay32.dll *ssleay32.dll You'll find a link to the latest Windows binaries here: http://www.openssl.org/related/binaries.html You don't need Visual C++ 2088 redistributables if you are just using the DLLs, so ignore the installation warning if you get one. Then, you add a TIdSSLIOHandleSocketOpenSSL component to your form. Set the IOHnandler property of your TIdHTTP component to the new TIdSSLIOHandlerSocketOpenSSL component. Set the following SSLOptions of the TIdSSLIOHandlerSocketOpenSSL component: Mode := sslmClient; That's all you need. Now when you call a 'https://' instead of a 'http://' URL, it will automatically load the libraries and use the SSL component. For OS X, it comes with OpenSSL, though not the latest versions, so you don't need to add any DLLs/dylibs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Drawables are always read from mdpi folder, regardless of screen size I am trying to create an application that works both on Samsung galaxy tab GT P1000 and samsung galaxy tab 10.1; The samsung galaxy tab 10.1 (1280 * 800) has a much bigger screen than that of the GT P1000, so I am assuming the GT P1000 should read from hdpi, and 10.1 should read from xhdpi. The surprise is that both of them are reading from the mdpi folder. Regards A: Large screen size does not necessarily means high pixel density. For pixel density you have to consider both physical screen size and screen resolution. For example consider Galaxy Note 1 and Galaxy Tab 10.1, both have screen resolution of 1280*800 but galaxy tab 10.1 has physical screen size of 10.1 inch whereas galaxy note has physical screen size of 5.3 inch, which is almost half of galaxy tab size. Thus galaxy note has more pixel per inch than galaxy tab 10.1 and it has xhdpi density, where as galaxy tab 10.1 has mdpi density, check density values in this link- http://developer.android.com/guide/practices/screens_support.html For 10.1 tab you should use drawable-xlarge-mdpi folder and GT P1000 should also use mdpi but as I have seen on many online posts that GT P1000 has problem, it has mdpi density but it uses drawables from hdpi, I have not checked myself so for GT P1000 you can try to use drawable-large-hdpi folder, if drawable-large-mdpi does not wok. And also add xlarge support in your manifest. <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" /> You have to use 2.3 and above sdk for using xlarge as it was added later. A: mdpi refers to the screen density, in dots per inch, not the overall size. I presume that both devices have similar densities, so they load resources from the mdpi folder. You can have separate layout resources based on the actual screen size (large/medium/small) rather than the density. Refer to the documentation. A: Just Make new folder name drawable-xlarge-mdpi and paste all images in it.. Device will automatically get from that folder..! My problem with Galaxy Tab2 was solved!
{ "language": "en", "url": "https://stackoverflow.com/questions/7634492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Permission denied while reading the db file I need to read a db file from a different application. The db file is created by the specific provider app & my application has to read this db file and take a back up. Not able to access the file : Permission Denied. Is it possible to read the file created by a different app? I think it may not be possible as per the android design, but just wanted to confirm whether it is possible by setting any permission. Thanks, Grace. A: No its not possible to read a db file from a different app in Android unless both apps are from the same publisher. It is part of the android security model that the application DB files are set as readable only by the application publisher in question. This is done by each publisher being given their own user id on the device. The only work rounds are * *Root you android device ( If you break it you get to keep both pieces ) and run your app with elevated privs. *Look to see if the app in question has some kind of published API for querying their data. Hope this helps Peter
{ "language": "en", "url": "https://stackoverflow.com/questions/7634500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable unlocking screen programmatically * *I need to lock the Android phone when the user leaves a defined WiFi area *I need to prevent the user from unlocking the phone when he/she is out side the defined WiFi area *I need to unlock the phone when user is back to the WiFi area I guess list items 1 and 3 can be done programmatically. Is it possible to do the 2nd item? A: Locking can be done using this method: How to lock the screen of an android device Unlocking look here: How to display Activity when the screen is locked? For your problem 2, i see 2 solutions a. If the user unlocks the screen, a message is fired: check at that moment if you are in the area and if not, instantly lock again b. create your own locksreen with no possibility to unlock yourself A: I need to prevent the user from unlocking the phone when he/she is out side the defined WiFi area Fortunately, this is not supported, for obvious security reasons. You are welcome to create your own home screen that offers different behavior when inside/outside a defined area and use that in lieu of trying to prevent a phone from being unlocked. However, the user is welcome to remove that home screen by booting their device into safe mode and uninstalling your app. A: I had done similar thing in past but dont have the code right now so cant help in that respect. What I did is implement the app as Car Dock that will make the Home button override unless car-dock mode is dis-abled. I hope this will help, for code google it you definitely find resources A: I guess this will help you out. This is just for Disabling the Lock Programmatically.Disable Screen Lock A: private Window w; public void onResume() { w = this.getWindow(); w.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD); w.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED); w.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON); super.onResume(); tToast("onResume"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Segmentation Fault while reading specificly 13 lines char **getLines(FILE *pFile) { int nLines = 0; size_t memRes = 0; char **lines = malloc(memRes); char *current = (char*) malloc(20); while(fgets(current, 20, pFile) != NULL) { memRes += sizeof(char*); lines = realloc(lines, memRes); lines[nLines] = malloc(20); strcpy(lines[nLines], current); nLines++; } free(current); return lines; } void printLines(char **lines) { int lineI = 0; while(lines[lineI] != NULL) { printf("%s", lines[lineI]); lineI++; } } First I get the lines then I print them. The odd thing about it is that my code fails when it has read exactly 13 lines of code and then prints them. I get a segmentation fault after printing the last line. It works with 12 lines and with 14 lines perfectly. A: size_t memRes = 0; char **lines = malloc(memRes); Lines might be a bit too small. A: In your printLines function, "while(lines[lineI] != NULL)" What is happening is that lines[lineI] isn't NULL, it just hasn't been allocated at the end. So because lineI is greater than nLines, it segfaults. You have to pass nLines into the function and use that to check boundries. "while (lineI < nLines)" A: You are assuming that the memory past the end of lines will contain a NULL, which it may or may not - it is uninitialized, so it could hold anything. You are getting 'lucky' for some small data sets, and it happens to contain zeros, so it works. For bigger data sets, you are running into an area of memory that has something else in it, and it is failing. If you want lines to be NULL past the set of pointers that hold the data from the fgets() calls, you need to allocate it big enough to hold an extra pointer, and set that space to NULL. char **getLines(FILE *pFile) { int nLines = 0; /* Start lines big enough to hold at least the NULL */ size_t memRes = sizeof(char *); char **lines = malloc(memRes); lines[0] = NULL; /* the memory returned by malloc must be initialized */ char *current = (char*) malloc(20); while(fgets(current, 20, pFile) != NULL) { memRes += sizeof(char*); lines = realloc(lines, memRes); lines[nLines + 1] = NULL; /* Prepare the NULL to terminate display loop */ lines[nLines] = malloc(20); strcpy(lines[nLines], current); nLines++; } free(current); return lines; } void printLines(char **lines) { int lineI = 0; while(lines[lineI] != NULL) { printf("%s", lines[lineI]); lineI++; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting JSONObject from JSONArray I am in a bit of a fix regarding the JSONObject that I am getting as a response from the server. jsonObj = new JSONObject(resultString); JSONObject sync_reponse = jsonObj.getJSONObject("syncresponse"); String synckey_string = sync_reponse.getString("synckey"); JSONArray createdtrs_array = sync_reponse.getJSONArray("createdtrs"); JSONArray modtrs_array = sync_reponse.getJSONArray("modtrs"); JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs"); String deleted_string = deletedtrs_array.toString(); {"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}] as you can see in the response that I am getting I am parsing the JSONObject and creating syncresponse, synckey as a JSON object createdtrs, modtrs, deletedtrs as a JSONArray. I want to access the JSONObject from deletedtrs, so that I can split them apart and use the values. i.e I want to extract companyid, username, date etc. How can I go about this ? Thanks for your input. A: Here is your json: { "syncresponse": { "synckey": "2011-09-30 14:52:00", "createdtrs": [ ], "modtrs": [ ], "deletedtrs": [ { "companyid": "UTB17", "username": "DA", "date": "2011-09-26", "reportid": "31341" } ] } } and it's parsing: JSONObject object = new JSONObject(result); String syncresponse = object.getString("syncresponse"); JSONObject object2 = new JSONObject(syncresponse); String synckey = object2.getString("synckey"); JSONArray jArray1 = object2.getJSONArray("createdtrs"); JSONArray jArray2 = object2.getJSONArray("modtrs"); JSONArray jArray3 = object2.getJSONArray("deletedtrs"); for(int i = 0; i < jArray3 .length(); i++) { JSONObject object3 = jArray3.getJSONObject(i); String comp_id = object3.getString("companyid"); String username = object3.getString("username"); String date = object3.getString("date"); String report_id = object3.getString("reportid"); } A: JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs"); for(int i = 0; deletedtrs_array.length(); i++){ JSONObject myObj = deletedtrs_array.getJSONObject(i); } A: JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop: JSONArray array; for(int n = 0; n < array.length(); n++) { JSONObject object = array.getJSONObject(n); // do some stuff.... } A: {"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}] The get companyid, username, date; jsonObj.syncresponse.deletedtrs[0].companyid jsonObj.syncresponse.deletedtrs[0].username jsonObj.syncresponse.deletedtrs[0].date A: start from JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs"); you can iterate through JSONArray and use values directly or create Objects of your own type which will handle data fields inside of each deletedtrs_array member Iterating for(int i = 0; i < deletedtrs_array.length(); i++){ JSONObject obj = deletedtrs_array.getJSONObject(i); Log.d("Item no."+i, obj.toString()); // create object of type DeletedTrsWrapper like this DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj); // String company_id = obj.getString("companyid"); // String username = obj.getString("username"); // String date = obj.getString("date"); // int report_id = obj.getInt("reportid"); } Own object type class DeletedTrsWrapper { public String company_id; public String username; public String date; public int report_id; public DeletedTrsWrapper(JSONObject obj){ company_id = obj.getString("companyid"); username = obj.getString("username"); date = obj.getString("date"); report_id = obj.getInt("reportid"); } } A: When using google gson library. var getRowData = [{ "dayOfWeek": "Sun", "date": "11-Mar-2012", "los": "1", "specialEvent": "", "lrv": "0" }, { "dayOfWeek": "Mon", "date": "", "los": "2", "specialEvent": "", "lrv": "0.16" }]; JsonElement root = new JsonParser().parse(request.getParameter("getRowData")); JsonArray jsonArray = root.getAsJsonArray(); JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject(); String dayOfWeek = jsonObject1.get("dayOfWeek").toString(); // when using jackson library JsonFactory f = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(); JsonParser jp = f.createJsonParser(getRowData); // advance stream to START_ARRAY first: jp.nextToken(); // and then each time, advance to opening START_OBJECT while (jp.nextToken() == JsonToken.START_OBJECT) { Map<String,Object> userData = mapper.readValue(jp, Map.class); userData.get("dayOfWeek"); // process // after binding, stream points to closing END_OBJECT } A: Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .operator like normal JAVA Object. It makes response handling very simple.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: Facebook Graph API Batch Requests - Retrieve Friends Likes returns unknown error I'm accessing the Graph API using batch requests, while trying to retrieve all of my friends likes the plataform returns-me a unknow error. By the way i'm using JSONPath to retrieve the likes. likes?ids={result=friends:$.data.*.id} Is this an security related question or a bug? A: Ensure your access token has friends_likes by using the linter: https://developers.facebook.com/tools/debug
{ "language": "en", "url": "https://stackoverflow.com/questions/7634519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RJS Handler missing I got a missing template error when I tried to achieve a task using RJS. All I want is to execute an RJS file on ajax call. But I am getting the following error. ActionView::MissingTemplate (Missing template line_items/create, application/create with {:handlers=>[:erb, :builder, :coffee], :formats=>[:js, :html], :locale=>[:en, :en]}. Searched in: * "<MY APP PATH>/app/views" ): app/controllers/line_items_controller.rb:46:in `create' But the create.js.rjs is present in the folder /views/line_items. You can see the handlers miss .rjs extension. I think thats causing the error. If I change .rjs to .erb, it works and the content is executed as javascript and thus I need to modify the RJS functions to Javascript to return the contents of AJAX call. Could you please explain how I can attain this using RJS? Please help. Following is the versions of tools I use. Ruby version 1.9.2 (i686-linux) RubyGems version 1.8.10 Rack version 1.3 Rails version 3.1.0 JavaScript Runtime Node.js (V8) Active Record version 3.1.0 Action Pack version 3.1.0 Active Resource version 3.1.0 Action Mailer version 3.1.0 Active Support version 3.1.0 Thanks in advance. A: in order to use RJS with Rails 3.1 you have to use the prototype-rails gem A: Make sure prototype-rails gem is in bundler's production group. If you put it in the assets group it will not register the RJS template handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to call C .exe file from C#? I have an .exe file which was written in C. It is a command line application. I want give command line and also get correspond output in this application through a C# application. How do I invoke the command and get the output from C#? A: You could use the Process.Start method: class Program { static void Main() { var psi = new ProcessStartInfo { FileName = @"c:\work\test.exe", Arguments = @"param1 param2", UseShellExecute = false, RedirectStandardOutput = true, }; var process = Process.Start(psi); if (process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds)) { var result = process.StandardOutput.ReadToEnd(); Console.WriteLine(result); } } } A: You need to use the Process.Start method. You supply it with the name of your process and any command line arguments and it will run the executable. You can capture any output which you can then process in your C# application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split line with perl I have a multiline credits with missing a few commas: rendező: Joe Carnahan forgatókönyvíró: Brian Bloom, Michael Brandt, Skip Woods zeneszerző: Alan Silvestri operatőr: Mauro Fiore producer: Stephen J. Cannell, Jules Daly, Ridley Scott szereplő(k): Liam Neeson (John 'Hannibal' Smith ezredes) Bradley Cooper (Templeton 'Szépfiú' Peck hadnagy) szinkronhang: Gáti Oszkár (John 'Hannibal' (Smith magyar hangja)) Rajkai Zoltán (Templeton 'Faceman' Peck magyar hangja) This leads to inability to split line by commas: $credits (split /, */, $line): I want to split after comma and if not exist comma between credits, split after first credits (ex.): rendező: Joe Carnahan forgatókönyvíró: Brian Bloom Michael Brandt Skip Woods zeneszerző: Alan Silvestri operatőr: Mauro Fiore producer: Stephen J. Cannell Jules Daly Ridley Scott szereplő(k): Liam Neeson (John 'Hannibal' Smith ezredes) Bradley Cooper (Templeton 'Szépfiú' Peck hadnagy) szinkronhang: Gáti Oszkár (John 'Hannibal' (Smith magyar hangja)) Rajkai Zoltán (Templeton 'Faceman' Peck magyar hangja) Thanks A: So you can split by a comma-space in most cases, but otherwise by a space character preceded by a right parenthesis. This would be: /, |(?<=\)) / Or, perhaps (?) more clearly: /,[[:space:]]|(?<=\))[[:space:]]/ The pipe character will make for a disjunctive match between what's on either side of it. But there's also parsing out the roles, and the entire string is full of non-ascii characters. Script: use strict; use warnings; use utf8; use Data::Dump 'dump'; my $big_string = q/rendező: ... hangja)/; my @credits = map { my ($title, $names) = /([[:alpha:]()]+): (.+)/; my @names = split /,[[:space:]]|(?<=\))[[:space:]]/, $names; my $credit = { $title => \@names }; } split / (?=[[:alpha:]()]+:)/, $big_string; binmode STDOUT, ':utf8'; print dump \@credits; Output: [ { rendező => ["Joe Carnahan"] }, { forgatókönyvíró => ["Brian Bloom", "Michael Brandt", "Skip Woods"], }, { zeneszerző => ["Alan Silvestri"] }, { operatőr => ["Mauro Fiore"] }, { producer => ["Stephen J. Cannell", "Jules Daly", "Ridley Scott"], }, { "szerepl\x{151}(k)" => [ "Liam Neeson (John 'Hannibal' Smith ezredes)", "Bradley Cooper (Templeton 'Sz\xE9pfi\xFA' Peck hadnagy)", ], }, { szinkronhang => [ "G\xE1ti Oszk\xE1r (John 'Hannibal' (Smith magyar hangja))", "Rajkai Zolt\xE1n (Templeton 'Faceman' Peck magyar hangja)", ], }, ] Notes: * *An array of hashrefs is used to preserve the order of the list. *The utf8 pragma will make the [:alpha:] construct utf8-aware. *Given Perl >= v5.10, The utf8::all pragma can replace utf8 and also remove the need to call &binmode prior to output. *Lookarounds ((?=), (?<=), etc.) can be tricky; see perlre and this guide for good information on them. A: I think you can try to set up a regular expression. you can substitute any 'word:' with '\nword:' in the same way you can substitte ',' with ',\n' to give a look to regular expression check this page: http://www.troubleshooters.com/codecorn/littperl/perlreg.htm the 2 roules should be something similar to: $newstr ~= ($str =~ tr/[a-zA-Z]+:/(\n)[a-Z]+:/); it's just a guess... not really aware of Perl syntax
{ "language": "en", "url": "https://stackoverflow.com/questions/7634528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Backbone.js detecting scroll event I have a following view var FullWindow = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'detect_scroll'); }, // bind the events events : { "scroll" : "detect_scroll" }, detect_scroll: function() { console.log('detected'); } }); and I initialize it via var full_window = new FullWindow({el:$('body')}); But I don't think it's working. When I change the events to events : { "click" : "detect_scroll" }, It's fine. What's wrong? A: I don't think that the body element will fire a scroll event unless you explicitly give it a scrollbar by setting set its overflow property to scroll in CSS. From the jQuery docs: The scroll event is sent to an element when the user scrolls to a different place in the element. It applies to window objects, but also to scrollable frames and elements with the overflow CSS property set to scroll (or auto when the element's explicit height or width is less than the height or width of its contents). Assuming that you aren't explicitly giving the body element a scrollbar with overflow:scroll and/or a fixed height, the scroll event you want to listen for is probably being fired by the window object, not the body. I think the best approach here is to drop the Backbone event binding (which is really just a shorthand, and only works on events within the view.el element) and bind directly to the window in initialize(): initialize: function() { _.bindAll(this, 'detect_scroll'); // bind to window $(window).scroll(this.detect_scroll); } A: The scroll bars for body and window are different and you have to make sure you aren't scrolling on the window object. Here is a jsfiddle that illustrates the issue you are probably encountering. jsfiddle I'm not for sure if you can change the 'el' to the document.window object, but I don't think that would be a good solution anyway. I would say your best bet is to either use CSS like I've done to help you with the body element or to create a div inside the body and reference that verse the body tag. Good luck. A: I think the problem is that Backbone uses event delegation to capture events, that is it attaches listeners to the this.$el, and that the scroll event does not bubble up by definition. So, if the scroll event occurs for a child (or descendant) of this.$el, then this event can not be observed at this.$el. The reason it works for click, is just because click bubbles up. A: I had same issue and this is how I implemented it var MyView = Backbone.View.extend({ el: $('body'), initialize: function() { $(window).scroll(function() { if ($(window).scrollTop()!=0 && $(window).scrollTop() == $(document).height() - $(window).height()) { if (mpListModel.get('next')) { var res = confirm('Next page?'); if (res==true) { myView.fetch() } } } }); }, events: {}, fetch: function() { //fetch stuff } }); var myView = MyView(); A: afterRender: function() { // <div id="page-content" class="page-content"> la class qui contiens le scroll var $scrollable = this.$el.find('.page-content'); $scrollable.scroll(function() { alert("event scroll "); }); },
{ "language": "en", "url": "https://stackoverflow.com/questions/7634529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How to Hide an Image, if not clicked, in N seconds? I have a button that when is clicked, an image is created using javascript and get prepended to a div (adds it inside a div). var image = new Image(); var imageHtml = image.toHtml(); $('div.board').prepend(imageHtml); function Image() { this.toHtml = function () { return '<img src=\"myImage.png\" width=\"40px\" height=\"40px\" />'; } } This image can be clicked in 2 seconds then user will have 1 more score and if not clicked in that time, then the image should disappear. How to do that in javascript? Thanks, A: function start_game(image){ var timeout = null; image.onclick = function(){ clearTimeout(timeout); //addScore(); }; timeout = setTimeout(function(){ image.onclick = null; image.style.display = "none"; // remove the image from dom if needed; }, 2000); } Demo: http://jsfiddle.net/UpNCb/ A: see this, just difference is you going to hide instead of link display or give id 'img_id' to your image function hideimage() { document.getElementById('img_id').style.display = 'none'; } setTimeout(hideimage, 10000); A: Use the function setTimeout() and the CSS property display or visibility.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Session, cookies and Security I got a problem. I have a web app,where I do the following: 1)Login 2)later extract the cookie 3)Logout 4)Insert manually the cookie and when I visit some page again, I'm logged. How can I fix it? I want the cookie expiration. thanks for your response. A: I suggest you use the built-in Forms Authentication mechanism. A: What is in that cookie? Just a "loggedin = yes" value? In that case you could change that to "loggedinsession = {current session ID}". On logout, delete the cookie (set the value to empty, without expiry) and also .Abandon() the session (so a new request gets a new session ID). The logged-in check then changes from "does the cookie exist" to "is the value the same as the current session ID".
{ "language": "en", "url": "https://stackoverflow.com/questions/7634533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Complex query across multiple tables I'm simplifying my actual case to get the point across quicker, just as a heads up if this seems nonsensical. I have a table called Candy_Central. Candy_Central has all of the ids for my candy, the price per pound as well and a couple other significant pieces of information that are the same across all Candy records. It also has a field called Candy_Type. Candy_Type's value might be chocolate, hard, gummy, or liquid. I have another set of tables that are used for the candy information, but their use is determined by candy type. For instance, if I want the rest of the information about my prime chocolate bar, I need to go to Chocolate_Standard to get the rest of the information. If I'm looking up gummy worms with sugar on the outside, I need to go to Gummy_Standard. The reason is that the fields for one set of information are completely different than the fields for the other. I have one more layer of information, colors. I have Candy that's blue, I have candy that's black, and I have candy that's both colors. The way I'm currently storing this information, I have a table with the fields Candy_Id and Color. To find all of the colors I'd normally just do a query on this table using the color_id field to find the candy I'm interested in. But SQL of course is about finding all of your results. So if I wanted to find all of the gummy info I'd want to do a join or union of some sort. I'm not extremely familiar with this type of query so I'm not sure how to get the result table that I want, which is basically going to be [sorry for the psuedo query] (items from Candy_Main as CM ... items from Gummy as g ... items from color as c ... where cm.candy_id = g.candy_id and cm.candy_id = c.candy_id ). If the gummy's didn't have colors, I'd just want null. I'm fine with getting multiple lines back for each candy_id, but I'd want this as limited as possible just so that post processing (turning the multiple candy lines into one object in my application) took as little time as possible. Tables: Candy_Main candy_id (primary key, auto increment, not null, etc) candy_name (varchar) candy_inventor_id (a primary key from some other table, but this is needed for the where clause. candy_type (varchar) Gummy_Standard gummy_id (primary, auto) candy_id (should match to candy_main) softness (varchar) outer_coating_type (varchar) animal_likeness (varchar) Gummy_Colors gummy_color_id (primary, auto) gummy_id (int) candy_id (int) color (varchar(64)) Gummy_Ingredients gummy_ingredient_id (primary, auto) gummy_id (int) candy_id (int) ingredient (varchar(64)) Now, I want to do a query for all entries where candy_inventor_id = 5 AND candy_type = 'gummy'. At the end of the query, I'd want candy_name, candy_type, softness, outer_coating_type, animal_likeness, colors, and ingredients. Color & ingredients are the only objects that aren't 1 to 1 in this query, so I'd like there to be only as many entries as there are colors and ingredients. Thanks for the help if this is possible. I have a feeling that it'd be easy enough to limit this for just colors or just ingredients, but that it'll be too difficult to do it with both. A: try this SELECT c.candy_name, c.candy_type, s.softness, s.outer_coating_type, s.animal_likeness, GROUP_CONCAT(gc.color), GROUP_CONCAT(gi.ingredient) FROM candy_main c LEFT JOIN gummy_standard s on s.candy_id=c.candy_id LEFT JOIN gummy_colors gc on gc.candy_id = c.candy_id LEFT JOIN gummy_ingredients gi cl on cl.candy_id = c.candy_id WHERE c.candy_inventor_id=5 AND c.candy_type='gummy' GROUP BY gc.color , gi.ingredient A: If I understand your DB setup correctly, for each candy, there are many potential gummy_standards (so a hard bear and a chocolate bear might be two gummy standard records linked to one candy record). In that case, the following should work: SELECT cm.candy_name, cm.candy_type, gs.softness, gs.outer_coating_type, gs.animal_likeness, gc.color, gi.ingredient FROM Candy_Main cm INNER JOIN Gummy_Standard gs ON gs.candy_id = cm.candy_id INNER JOIN Gummy_Colors gc ON gc.candy_id = gs.gummy_id INNER JOIN Gummy_Ingredients gi ON gi.gummy_id = gs.gummy_id WHERE candy_inventor_id = 1 -- Of course, this 1 be replaced with the actual inventor's ID Bear in mind that doing it like this causes duplications to cross multiply, so if a gummy has three colours and 4 ingredients, each ingredient is repeated for all three colours (so 12 lines for just the one gummy). If you don't want this, try concatenating the strings to one line and then splitting the line in code. Don't know what the function in MySQL is, but if concat_ws() works like textcat_all() does in PostgreSQL, then the following should work: SELECT cm.candy_name, cm.candy_type, gs.softness, gs.outer_coating_type, gs.animal_likeness, CONCAT_WS(', ', gc.color), CONCAT_WS(', ', gi.ingredient) FROM Candy_Main cm INNER JOIN Gummy_Standard gs ON gs.candy_id = cm.candy_id INNER JOIN Gummy_Colors gc ON gc.candy_id = gs.gummy_id INNER JOIN Gummy_Ingredients gi ON gi.gummy_id = gs.gummy_id WHERE candy_inventor_id = 1 -- Of course, this 1 be replaced with the actual inventor's ID GROUP BY cm.candy_name, cm.candy_type, gs.softness, gs.outer_coating_type, gs.animal_likeness Two tips on the architecture: 1. If my understanding of your tables is correct and ingredients and colors always apply to a gummy standard record, then the candy_id field in Colors and Ingredients is redundant. Better just to connect to Candy through Gummy Standard each time. 2. You might benefit from a higher degree of normalisation, i.e. creating a colors table and an ingredients table and then linking to those, rather than including the string description in your tables as they are. This will make it easier to make changes for all appropriate records, i.e. say you want to change the name of the Blue colour to Blue (Dark) because you're adding Blue (Light), you should only have to update one record rather than all of the Color records saying Blue (or blue, or even blu or blou since misspellings frequently occur when you have to type the same description in every time). So your tables would look like: Color color_id (primary, auto) color (varchar(64)) Ingredient ingredient_id (primary, auto) ingredient (varchar(64)) Gummy_Colors gummy_color_id (primary, auto) gummy_id (int) candy_id (int) color_id (foreign key to Color) Gummy_Ingredients gummy_ingredient_id (primary, auto) gummy_id (int) candy_id (int) ingredient_id (foreign key to Ingredient) Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: issue while getting values from Dictionary> I am having a dictionary which was defined as follows Dictionary<int, List<int>> dict1 = new Dictionary<int, List<int>>(); I will have a list element where i can store the values which will come from database List<int> lstdbTaskID = new List<int>(); assume this holds 100 105 110 200 respectively. I will have my dictionary with values stored as follows. Assume that i have 2 keys 10,20 respectively, and for this key values i will have my values as for 10 i will have 100,105 and 110 and for 20 i will have 200. I would like to compare these values with the list available lstdbTaskID I tried this foreach (int strlst in lstdbTaskID) { if (dict1.ContainsValue(lstdbTaskID[strlst])) } But i am getting errors as follows The best overloaded method match for 'System.Collections.Generic.Dictionary>.ContainsValue(System.Collections.Generic.List)' has some invalid arguments` and Cannot convert from 'int' to 'System.Collections.Generic.List'` can any help me on this? A: Your code is wrong at because you are trying to compare int value with List of int. Your dictionary is: Dictionary of int to List of int. and you have another structure as List of int so when you do: // Compiler fails here because you are trying to check whether dictionary contains // the given integer value. Dictionary in this case has a list of integers as its `Value` // in its `<Key,Value>` pair. dict1.ContainsValue(lstdbTaskID[strlst]) Use linq statement: foreach (int strlst in lstdbTaskID) { if (dict1.Any(pair => pair.Value.Contains(strlst))) { // do something } } Edit: If you want this without linq, do the linq task by self. foreach (int strlst in lstdbTaskID) { foreach (int key in dict1.Keys) { if (dict1[key].Contains(strlst)) { // do something } } } A: Look at the type of the value you're storing in your dictionary - it's a List<int>, not an int. So it makes no sense to ask whether the dictionary contains a value of 5, say. However, it does make sense to ask if the dictionary contains any value (list) which itself contains 5. For example: foreach (int strlst in lstdbTaskID) { if (dict1.Values.Any(list => list.Contains(strlst)) { ... } } However, that's really not a very efficient way of representing it. It's not clear what the best of representing it is though, without knowing what you're going to do with the results. You may just want a HashSet<int> containing all the values from all the lists, for example - but if you want to get back to the keys whose values contained a particular ID, that's a different matter. EDIT: In .NET 2.0 land, you could use: foreach (int strlst in lstdbTaskID) { foreach (List<int> list in dict1.Values) { if (list.Contains(strlst)) } } ... but you're really not using the dictionary as a dictionary in either case here... A: I am having slight problems understanding your question fully, however, my answer should push you in the right direction. Seeing as you do not have access to Linq (as you are using .Net 2.0): static bool IsContained(IEnumerable<int> lstdbTaskID, Dictionary<int, HashSet<int>> dict1) { foreach (int strlst in lstdbTaskID) foreach (HashSet<int> value in dict1.Values) if (value != null && value.Contains(strlst)) return true; return false; } You should use a HashSet<int> as it is far faster for looking up values (and is supported in .Net 2.0); however, you should not use HashSet<int> (and instead use List<int>) if: * *The list needs to store duplicates. *- or - The order of the values is important. A: Well, dict1 is a dictionary of dictionaries, not ints. So dict1.ContainsValue takes a dictionary as a parameter - you're checking whether it contains a given dictionary or not. But you're giving it an int. Try this: if (dict1.Any(x => x.Value.ContainsValue(strlst))) // ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7634535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rotating ImageView in Android < API Level 11 So in API Level 11 Google introduced the ability to rotate an ImageView (Yay, after they introduced the possibility to Animate such a rotation, yay smart thinking, yay!) But how should I go about to rotate an ImageView using e.g. API level 8? I can't use setRotation() as described above. A: RotationAnimation was present since Api level 1 RotateAnimation animation = new RotateAnimation(from, to, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setInterpolator(new LinearInterpolator()); animation.setDuration(1); animation.setFillAfter(true); imageView.startAnimation(animation ); A: I started with creating BitMap and rotating the canvas/matrix, however this was not a good solution. Finally ended up just swapping the drawable if conditions are met. I should say this is an ExpandableListView where cells are reused when drawing. if (isExpanded) { ImageView view = (ImageView) convertView.findViewById(R.id.ImageView); view.setImageResource(R.drawable.quickactions_button_normal_down); } if (!isExpanded) { ImageView view = (ImageView) convertView.findViewById(R.id.ImageView); view.setImageResource(R.drawable.quickactions_button_normal); } I'm not usually a Android developer but I'm really amazed that it is possible to animate a rotation, but not statically set the rotation of a drawable. Logically the first is a subset of the second and not the other way around.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: how to get data from xml object in org.jdom.Document? I am trying to get some datas from xml document object. My imaginery xml file is like that; <root> <body> <oids> <oid> </oid> <oid> </oid> <oid> </oid> <oid> </oid> </oids> </body> </root> And to do that I am writing a function for that ; public Vector<String> getOIDs(Document document){ Vector<String> oids = new Vector<String>(); Element root = document.getRootElement(); Element body = root.getChild("body"); Element element = body.getChild("oids"); List rows = (List) element.getChildren("oid"); /* List rows = root.getChildren("oids"); for (int i = 0; i < rows.size(); i++) { } */ return oids; } As I read from the Internet , I undeerstood that I should use List class to get the s but when I try it, I always get errors. Can you please help me to get the s. Thank you all. A: I can't see what is wrong in the code. The only thing that looks fishy is the explicit conversion to List. Why is that? I'm guessing that you have imported the wrong List implementation. Make sure you have imported java.util.List. A: In your XML, <body> and <oids> are siblings, i.e. they have the same parent. Your code assumes that <oids> is a child of <body>. That should hopefully get you going again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the outp() counterpart in gcc compiler? In my School my project is to make a simple program that controls the LED lights my professor said that outp() is in the conio.h, and I know that conio.h is not a standard one. example of outp() //assume that port to be used is 0x378 outp(0x378,1); //making the first LED light thanks in advance A: You can do this from user space in Linux by writing to /dev/port as long as you have write permissions to /dev/port (root or some user with write permissions). You can do it in the shell with: echo -en '\001' | dd of=/dev/port bs=1 count=1 skip=888 (note that 888 decimal is 378 hex). I once wrote a working parallel port driver for Linux entirely in shell script this way. (It was rather slow, though!) You can do this in C in Linux like so: f = open("/dev/port", O_WRONLY); lseek(f, 0x378, SEEK_SET); write(f, "\01", 1); Obviously, add #include and error handling. A: You're mixing up two things. A compiler makes programs for an OS. Your school project made a program for DOS. outp(0x378,1); is essentially a DOS function. It writes to the parallel port. Other operating systems use other commands. GCC is a compiler which targets multiple Operating Systems. On each OS, GCC will be able to use header files particular top that system. It's usually going to be a bit more complex. DOS runs one program at a time, so there's no contention for port 0x378. About every other OS runs far more programs concurrently, so you first have to figure out who gets it. A: How to write to a parallel port depends on the OS, not the compiler. In Linux, you'd open the appropriate device file for your parallel port, which is /dev/lp1 on PC hardware for port 0x0378. Then, interpreting the MS docs for _outp, I guess you want to write a single byte with the value 1 to the parallel port. That's just FILE *fp = fopen("/dev/lp1", "wb"); // check for errors, including permission denied putc(1, fp);
{ "language": "en", "url": "https://stackoverflow.com/questions/7634549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sharing session via web request I have spend a lot of time on this problem without any change : I have got 2 simples apsx page, in the first page the Page_Load event put data in the session ; later the on_click event of a button fire an HttpWebRequest to the second page with the idea to retrieve on the page_load of the second page the data in the session. to sum up : 1st page put data in session, make the httpWebRequest to the 2nd page 2nd page : try to get the stored data in the session. This is the different attempt of code i 've tested to perform this action, the result was always the same. When i try to add sessionId Information (via a cookieContainer or directly in the Header request) i get a timeout exception System.Net.HttpWebRequest.GetResponse() and when i do the HttpWebrequest without the session_id information i get the response immediatly but without the session info :-) A: It's not clear what you're trying to do, but have you considered using Server.Execute instead? http://www.west-wind.com/weblog/posts/2004/Jun/08/Capturing-Output-from-ASPNet-Pages
{ "language": "en", "url": "https://stackoverflow.com/questions/7634552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Registering the google api key for publishing app When we are ready to publish your application,we must get a Maps API Key that is based on the certificate that be will used to sign the application for release n then change the Maps API Key strings referenced by all of MapView elements, so that they reference the new Key. But my problem is how to get the api key for publishing based on the certificate. A: For Google Map to visible in all Devices after you launched your app in Android Market you need to create Keystore using Release Key. Check my post for creating Signed Application and Register Map using Release Key
{ "language": "en", "url": "https://stackoverflow.com/questions/7634553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: GetType used in PowerShell, difference between variables What is the difference between variables $a and $b? $a = (Get-Date).DayOfWeek $b = Get-Date | Select-Object DayOfWeek I tried to check $a.GetType $b.GetType MemberType : Method OverloadDefinitions : {type GetType()} TypeNameOfValue : System.Management.Automation.PSMethod Value : type GetType() Name : GetType IsInstance : True MemberType : Method OverloadDefinitions : {type GetType()} TypeNameOfValue : System.Management.Automation.PSMethod Value : type GetType() Name : GetType IsInstance : True But there seems to be no difference although the output of these variables looks different. A: Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType(): PS > $a.GetType().fullname System.DayOfWeek PS > $b.GetType().fullname System.Management.Automation.PSCustomObject A: First of all, you lack parentheses to call GetType. What you see is the MethodInfo describing the GetType method on [DayOfWeek]. To actually call GetType, you should do: $a.GetType(); $b.GetType(); You should see that $a is a [DayOfWeek], and $b is a custom object generated by the Select-Object cmdlet to capture only the DayOfWeek property of a data object. Hence, it's an object with a DayOfWeek property only: C:\> $b.DayOfWeek -eq $a True A: Select-Object returns a custom PSObject with just the properties specified. Even with a single property, you don't get the ACTUAL variable; it is wrapped inside the PSObject. Instead, do: Get-Date | Select-Object -ExpandProperty DayOfWeek That will get you the same result as: (Get-Date).DayOfWeek The difference is that if Get-Date returns multiple objects, the pipeline way works better than the parenthetical way as (Get-ChildItem), for example, is an array of items. This has changed in PowerShell v3 and (Get-ChildItem).FullPath works as expected and returns an array of just the full paths.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "110" }
Q: What's an "auto-casting bool"? On the following answer to a previous question someone mentioned an "auto-casting bool" I guess null has an auto-casting bool that is false. What is it, and what does the code that makes it look like? A: The phrase "auto-casting bool" is a poor phrase someone used off hand. I believe what they mean is the internal ToBoolean operation Of special note is the if statement which calls ToBoolean on the expression. I don't know my way around the v8 source code but here is a search for ToBoolean on the v8 repo. For reference v8 is the javascript implementation used by chrome and written in C++
{ "language": "en", "url": "https://stackoverflow.com/questions/7634584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Date Error in vb.net This one has both me and my boss tearing our hair out in frustration: I'm running a stored procedure to get some information out of my database. One of the values it returns is a date field. When I manually exec the stored procedure in SQL, I get a value and yet when I write the data out onto the page, I get a value + 1. So, for example, if SQL says the date should be 12/11/2011, my page is displaying it as 13/11/2011. It doesn't appear to be a date format issue - my date's coming out of SQL in UK/Europe format and the .NET page is displaying it in UK/Europe format - and as far as I'm aware, I'm not actually adding 1 on when I display the date. Does anyone have any suggestions for what stupid mistake (and at this point, we're both pretty sure it IS something silly since all my googling hasn't turned up anyone else with this problem) we've made? The select query is as follows: Select @TotalPrice as Price, Convert(varchar(10),@Departure, 103) as Departure, @PImage1 as PImage1, @PImage2 as PImage2, @PImage3 as PImage3, PName, PBath, PBed, PMaxSleep, PSwim, PLong, PLat, RIName, CIName, RName, CName, PTShortDesc, PTLongDesc from Property P, PropertyText PT, Region R, RegionID RI, Country C, CountryID CI where P.PID=@PID and P.RIID=RI.RIID and P.CIID=CI.CIID and P.PID=PT.PID and PT.CID=PT.CID and C.CID=R.CID and LCode='EN' and R.RIID=RI.RIID and C.CIID=CI.CIID I'm then writing Departure to a label: DepartureLabel.text = myReader1("Departure") At no stage do I have any DateAdd statements in my page. A: You might need to check daylight savings time and regional settings. Both on the client and on the server. Also check the actual value in the table in the SQL server (not by using the client) to find out whether it is the server or the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading Facebook wall returns an empty array I am trying to read a user's wall, not news feeds, with PHP, and I always get an empty array from this: $api_call = array( 'access_token'=>$facebook->getAccessToken() ); try{ $wall= $facebook->api("$uid/feed/","get",$api_call); } catch (Exception $e){} Any idea what is wrong here? A: You need to have the read_stream extended permission if you want to see posts other than those with visibility set to 'Public'
{ "language": "en", "url": "https://stackoverflow.com/questions/7634587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cocoa/OSX - NSTextField not responding to click for text editing to begin when titlebar is hidden I have a NSTextField in my window (added with IB) with a hidden title bar but when I click on it when the app is running, it does not respond or place a cursor in its field. Is there anything I am doing wrong? it is setup in the most standard way possible, an editable textfield on a window. Thanks. A: Create a custom class that inherits from NSWindow, and set it as the NSWindow Object in InterfaceBuilder. Then override the following methods: // // canBecomeKeyWindow // // Overrides the default to allow a borderless window to be the key window. // - (BOOL)canBecomeKeyWindow { return YES; } // // canBecomeMainWindow // // Overrides the default to allow a borderless window to be the main window. // - (BOOL)canBecomeMainWindow { return YES; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: EventLog not working in blackberry I am working on Blackberry simulator with no real device. I have opened the EventLog by tools -> Show Event Log. But it is coming blank with no log details. for sd card I gave path of my simulator.dmp path. I have also tried pressing alt key and then write LGLG. But nothing is happening, I just get options of youtube search, local google search and search blackberry. My question is where do I check log results? If the event log needs a real device, is there any other way of checking it on a simulator? A: EventLogger works on simulator and on actual devices. If menu in simulator does not show you log contents, launch event log viewer in your application. Just add an additional menu item to your application and launch event log viewer upon clicking on this menu item. Additional information: on keyboard device simulator to show event log hit Ctrl on your computer keyboard, keep it pressed and hit LGLG On actual keyboard device hit Alt button, keep it pressed and hit LGLG Here is the instruction to show log for touchscreen devices.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How Can I Code A Category / Sub Category Database Query (One Level Deep) In Codeigniter? Ah, the aged old question of parent / child categories in PHP. My apologies if this question has been asked already (I know it has in many forms), but doing a search couldn't specifically answer how to do this using one query and Codeigniter. Basically I am developing a classifieds website using Codeigniter. A listing can be assigned to a category. A category can be stand-alone (no children) or a category can have one child. Using Codeigniter's "Active Record" functions, I have the following that almost works. $this->db->select('l.*'); $this->db->select('c.cat_parent, c.cat_slug, c.cat_name, c.cat_description, c.cat_display'); $this->db->select('c2.cat_slug AS parent_cat_slug, c2.cat_name AS parent_cat_name, c2.cat_description AS parent_cat_description, c2.cat_display AS parent_cat_display'); $this->db->limit($limit, $offset); $this->db->join('listing_status ls', 'ls.status_id = l.listing_status'); $this->db->join('categories c', 'c.cat_id = l.listing_category'); $this->db->join('categories c2', 'c2.cat_parent = c.cat_id'); return $this->db->get('listings l')->result(); I want to be able to pull out a listing, it's assigned category and if that category the listing belongs to has a parent, get the parent category details as well. I've added in 2 joins and it should be working, is there something I've missed? A: After a little messing around, I realised that my second join was wrong. Here is my updated and working code in hopes it helps someone else. $this->db->select('l.*'); $this->db->select('c.cat_parent, c.cat_slug, c.cat_name, c.cat_description, c.cat_display'); $this->db->select('pc.cat_slug AS parent_cat_slug, pc.cat_name AS parent_cat_name, pc.cat_description AS parent_cat_description, pc.cat_display AS parent_cat_display'); $this->db->limit($limit, $offset); $this->db->join('listing_status ls', 'ls.status_id = l.listing_status'); $this->db->join('categories c', 'c.cat_id = l.listing_category'); $this->db->join('categories pc', 'pc.cat_id = c.cat_parent'); return $this->db->get('listings l')->result();
{ "language": "en", "url": "https://stackoverflow.com/questions/7634591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How Edit Image view in android I have Image View I want to show the Current time and date on each Image View. I don't know how to edit the Image view in android. A: Hope this trick will help: Take a textview and add your image as it's background and set it's text to current date and time whatever you want. :) Yes you can do that using onDraw(Canvas c) which takes canvas parameter.Here is also some functions of Canvas which can help you. A: You should be able to just override the OnDraw method and you will get the canvas parameter. http://developer.android.com/reference/android/widget/ImageView.html#onDraw(android.graphics.Canvas) Here is an example of someone overriding in this question: Creating Custom ImageView In order to save this to a database you will just need to save the canvas as a bitmap
{ "language": "en", "url": "https://stackoverflow.com/questions/7634592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use toString and vector between two classes in C++? Possible Duplicate: Is this possible in C++? toString(ClassName* class) I'm trying to use toString but I have a problem in there. I ask this question second time, because the first time I asked before had insufficient information. I just worried about the length of question. Sorry about that. toString is in the Animal class, and Animal class has vector<Treatment> treatArray; as a data member, but the thing is I can use the data member itself, but I cannot get the data member of treatArray. These are my code: Animal.h #ifndef ANIMAL_H #define ANIMAL_H #include "jdate.h" //#include "Treatment.h" #include <vector> #include <sstream> class Treatment; class Animal{ protected: int id; double weight; int yy; int mm; int dd; double dose; double accDose; char sex; vector<Treatment*> treatArray; public: Animal(); Animal(int newid, double newweight, int yy, int mm, int dd, char newsex, vector<Treatment*> treatArray); ~Animal(); void setTreatArray(vector<Treatment*> treatArray); vector<Treatment*> getTreatArray(); string toString(); }; Treatment.h #ifndef TREATMENT_H #define TREATMENT_H #include "jdate.h" class Treatment{ private: int id; jdate dayTreated; double dose; double accDose; public: Treatment(int id,jdate dayTreated, double dose); Treatment(); ~Treatment(); }; #endif Animap.cpp #include "Animal.h" //using namespace std; Animal::Animal(int newid, double newweight, int yy, int mm, int dd, char newsex, vector<Treatment*> treatArray) { id = newid; weight = newweight; yy = yy; mm = mm; dd = dd; dose = 0; accDose = 0; sex = newsex; } Animal::Animal() { id = 0; weight = 0; yy = 0; mm = 0; dd = 0; dose = 0; accDose = 0; sex = ' '; } void Animal::setTreatArray(vector<Treatment*> treatArray){treatArray = treatArray;} vector<Treatment*> Animal::getTreatArray(){return treatArray;} string Animal::toString() { jdate DOB(getYY(),getMM(),getDD()); ostringstream ostr; ostr<<"Cattle / Sheep: "<<getSex()<<", Weight: "<<getWeight() <<" kg. DOB: " <<DOB.toString()<<" Accum Dose " <<getAccDose() << "mg" << endl; if(getTreatArray().size()==0) ostr<<"\n No History Found\n"; else { for(int i=0;i<getTreatArray().size();i++) { //UNTIL HERE, NO ERROR FOUND, BUT ERROR OCCURS FROM THE STATEMENT BELOW ostr<<" Treatment: " << getTreatArray().at(i)->getID() << " " <<getTreatArray().at(i)->getDayTreated().toString()<< " " <<getTreatArray().at(i)->getDose() <<"mg\n"; } } return ostr.str(); } There are setter and getter for each class, and I cut it down. Also, I thought it's because of initalisation of the vector, but I googled regarding initalising vector, and it says that vector is automatically initialised, so I don't have to initailise manually. Now I don't know what the problem is :( The error message is: 1 IntelliSense: pointer to incomplete class type is not allowed l:\2011-08\c++\assignment\drug management\drug management\animal.cpp 97 30 Drug Management A: You should include Treatment.h in Animal.cpp. EDIT: To expand on the reason, the error message translates to: "I see that you've declared a class called Treatment. But I don't see its implementation!". So to let the compiler see its implementation where you're accessing the members of the class Treatment, you need to #include Treatment.h in your Animal.cpp. I see the reason why you don't want it to be in Animal.h, because Animal.h is being included in Treatment.h, which could cause compiler to get into a problem like: "Okay! I'm parsing Animal.cpp... - It includes Animal.h... -- I'm going to expand Animal.h... -- Animal.h includes Treatment.h... --- I'm going to expand Treatment.h... --- Treatment.h includes Animal.h... ---- I'm going to expand Animal.h.... ---- (Loops)" This kind of gets avoided by the #pragma once or #ifdef guards. But when them come into action, compiler goes like this: "Okay! I'm parsing Animal.cpp... - It includes Animal.h... -- I'm going to expand Animal.h... -- Animal.h includes Treatment.h... --- I'm going to expand Treatment.h... --- Treatment.h is using class called Animal... --- WHERE IS THE DEFINITION FOR ANIMAL?.... ERROR! --- (The compiler did not come to the point where class Animal was defined!) It will also depend on whether the compiler started with Treatment.cpp or Animal.cpp. If it was Treatment.cpp, it would complain about missing definition of Treatment (just the opposite scenario of what's happened with Animal). Now that you've declared to the compiler in Animal.h that "Keep an eye out for a class called Treatment", as long as it's not being used in Animal.h and the use of Treatment class is as a pointer, the compiler will not complain with the header file side of Animal class. But in Animal.cpp you're calling a function from Treatment class. Then the compiler goes: Hey! You told me to look out for a class called Treatment. And now you're asking me to resolve that function definition, but I don't see the implementation of Treatment! And hence the reason to include Treatment.h in your Animal.cpp. Animal.cpp will get compiled independently of Treatment.cpp and vice-versa and hence should not cause the clash I mentioned above. A: Since you used a forward declaration in the header, you still need to include the Treatment.h file in your animal.cpp Otherwise, the compiler still does not know what the Treatment class is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ORA-00907 when dynamically creating a view in PL/SQL and using a CLOB This is one of those situations where you get an unhelpful error message back from Oracle. My situation is as follows: I'm dynamically creating a view in PL/SQL. I build a string and use EXECUTE IMMEDIATE to create the view. The string is so long that I use a CLOB to store it. When I run the code below in TOAD I get the unhelpful ORA-00907: missing right parenthesis error. Manually creating the view in TOAD (without the EXECUTE IMMEDIATE) gives no problems. My feeling is that the length of the string is a factor here as I've successfully created views with shorter strings (and also by using to_char() instead of dbms_lob.substr(), however to_char() only works with smaller clobs). The total string length is 13775. (Obviously I've edited the line below where I build the string.) This is an Oracle 10g database on Linux. declare lv_sql CLOB; begin lv_sql := ' CREATE OR REPLACE FORCE VIEW my_view.....'; EXECUTE IMMEDIATE dbms_lob.substr(lv_sql, 14765, 1 ); end; A: As Klas has said, you should be able to use VARCHAR2(32767) for your variable declaration but if you find that this is not quite enough, you could just use more than one VARCHAR2 variable to hold the various parts of the view statement and then issue them to the EXECUTE IMMEDIATE statement. An AskTom answer here demonstrates: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:6161200355268 Says: You have indicated that the max string length for execute immediate is 32K. We are using execute immediate to create generated packages and we are currently passing it > 35000 chars by execute immediate v_myvc1 || my_vc2 vc1 and vc2 are 32 k varchar2 vars. whose combined length is currently 35000 All on 8.1.7 My Question is what is the maximum length for the execute immediate string cause I was worried it was 32k and we are already over it, and I'm not sure when I'm going to hit the wall. Tom Kyte responds: Followup March 5, 2003 - 6pm Central time zone: interesting -- never would have thought to do it that way. That appears to work -- will it hit a wall? not sure, I would never have gone over 32k. looks like it can go pretty large: ops$tkyte@ORA817DEV> declare 2 l_str1 long := 'select /* ' || rpad( '*', 20000, '*' ) || ' */ * '; 3 l_str2 long := 'from /* ' || rpad( '*', 15000, '*' ) || ' */ dual'; 4 l_str3 long := '/* ' || rpad( '*', 32000, '*' ) || ' */ '; 5 l_result dual.dummy%type; 6 begin 7 execute immediate l_str1||l_str2||l_str3||l_str3||l_str3||' d' into l_result; 8 dbms_output.put_line( l_result ); 9 end; 10 / PL/SQL procedure successfully completed. Though this was on an Oracle 8i database instance I would be very surprised if the ability to daisy-chain the VARCHAR2 variables had been dropped in later revisions. Unfortunately I can't test it as I don't have a 10g instance available to hand at the moment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Web Deploy API (deploy .zip package) Clarification I'm using the web deploy API to deploy a web package (.zip file, created by MSDeploy.exe) to programmatically roll the package out to a server (we need to do some other things before we release the package which is why we're not doing it all in one go using MSDeploy.exe). Here's the code I have. My question is really to clarify what is happening when this is executed. In the package parameters XML file I have the application name specified ("Default Web Site") but that's about it, there's no other params are specified in there. From testing the server it appears the package gets deployed successfully but my question is are any other settings on the server I'm deploying to getting changed without my knowledge, are any default settings published etc.? Things like security settings, directory browsing etc. that I might not be aware of? The code here seems to deploy the package but I'm anxious about using this on a production environment when I'm so unsure of how this API works. The MS documentation is not helpful (more like non-existant, actually). DeploymentChangeSummary changes; string packageToDeploy = "C:/MyPackageLocation.zip"; string packageParametersFile = "C:/MyPackageLocation.SetParameters.xml"; DeploymentBaseOptions destinationOptions = new DeploymentBaseOptions() { UserName = "MyUsername", Password = "MyPassword", ComputerName = "localhost" }; using (DeploymentObject deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Package, packageToDeploy)) { deploymentObject.SyncParameters.Load(packageParametersFile); DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); syncOptions.WhatIf = false; //Deploy the package to the server. changes = deploymentObject.SyncTo(destinationOptions, syncOptions); } If anyone could clarify that this snippet should deploy a package to a web site application on a server, without changing any existing server settings (unless specified in the SetParameters.xml file) that would be really helpful. Any good resources on using the API or an explanation of how web deployment works behind the scenes would also be much appreciated! A: The setparameters file just controls the value for the parameters defined in the package. A package might be doing much more than that. Web deploy has a concept of providers and any given package can have one or more providers. If you want to make sure that the package is not changing server side settings the best approach you can take is to use the API but make the packages be deployed via Web Management Service. This will give you two benefits: * *You can control what providers you allow through. *You can add users and give restricted permissions to them to deploy to their site or their folder etc. The alternate approach is to: * *In the package manually look at the archive.xml and look for the providers in the package. As long as you dont see any of the following providers that can cause server settings change such as apphostconfig or webserver or regkey (this is not a comprehensive list) you should be good. Runcommand is a provider that allows you to execute batch scripts or commands. While it is a good provider for admins themselves you need to consider whether you want to allow packages with such providers to run. *You can do the above mentioned inspection in code by calling getchildren on the deployment object you create out of the package and inspect the providers and the provider paths.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: To print a page of web page I want to print the page content in the printer. I use the following code to write the content to printer: <?php $printer = "\\\\Pserver.php.net\\printername"; if($ph = printer_open($printer)) { // Get file contents $fh = fopen("filename.ext", "rb"); $content = fread($fh, filesize("filename.ext")); fclose($fh); // Set print mode to RAW and send PDF to printer printer_set_option($ph, PRINTER_MODE, "RAW"); printer_write($ph, $content); printer_close($ph); } else "Couldn't connect..."; ?> but I found out that it returns an error like printer_open($printer) is undefined function. Where's the fault in the code? A: http://php.net/manual/en/function.printer-open.php This is only Windows function (according to: http://www.php.net/manual/en/intro.printer.php) So there can be just few reasons * *You are not running server on Windows *You don't have this extension installed (see: http://www.php.net/manual/en/printer.installation.php) *You don't have this extension enabled (see phpinfo() to check it) You have to compile that extension manually or download pack with version according to your PHP version, since it is not downloadable via PECL See this comment, since it looks like you're trying to print on network shared printer http://www.php.net/manual/en/ref.printer.php#89054 If you want to print to a network printer on another machine: If you are running PHP on a web server that is running as the System user (quite likely), it won't have access to network resources, including network printers. Changing the web server service to run as an account with access to network printers fixes the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: asp.net forms authentication showing same LastActivityDate for all users I'm not sure why this is happening, but the last activity date for all my users is showing the same. I thought it was the way I was pulling the data from the database, but I checked my data, and it shows the same for all users. Is there something I need to be doing to get this field updated? I'm not doing anything special with this field other than reporting it. A: I found the answer here in this article. Apparently, when I pull up the list of users and I pull the profile for each, it calls a stored procedure that in turn, updates the LastActivityDate of each user to the current date and time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jena TDB in Python? Is it possible to run a Jena TDB database from a Python app to store a large amount of RDF data? What would be a native alternative in Python? A: An alternative is to use a SPARQL endpoint such as Apache Jena's Fuseki and just use an HTTP client from Python or any other language. To read more about Fuseki, look here: * *http://incubator.apache.org/jena/documentation/serving_data/ A: http://code.google.com/p/python-graphite/ A Python package that make it possible to use Jena in Python A: An alternative is to run the python code under Jython not the normal C based Python run time. Jython converts python code to the JVM language. It cannot therefore call python extensions that use C but it can call all Java classes including the Jena TDB and all pure python modules.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to integrate XMPP framework for iPhone? Possible Duplicate: How to implement XMPP protocol in objective-C? I am a new developer for Xcode, I don't know how to use XMPP Framework to develop chat application for iPhone. So, please can help me for creating chat appication using XMPP? Also provide some example, if possible. Thanks! A: Tutsplus recently posted extensive tutorial on creating chat application using xmpp framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I extract an exact word from text by using python? I want to calculate how many lines contain a word matched with keywords I chosen. So I coded like this. 28 for each_keyword in keywords: 29 if each_keyword in text: 31 related_tweet_count += 1 32 print "related_tweet_count", related_tweet_count 33 print text It performed very well. But it has a problem. For example, I have a keyword "flu" then it gives not only "flu" but also "influence". To solve this problem, I searched match word examples and fixed the code like this. 28 for each_keyword in keywords: 30 if re.search('\beach_keyword\b', text, re.I): 31 related_tweet_count += 1 32 print "related_tweet_count", related_tweet_count 33 print text But it doesn't work. Please help me out! A: You need to actually substitute each_keyword into the regular expression. At the moment it's literally trying to match "each_keyword". 28 for each_keyword in keywords: 30 if re.search('\\b' + each_keyword + '\\b', text, re.I): 31 related_tweet_count += 1 32 print "related_tweet_count", related_tweet_count 33 print text A: Alternatively do it without regular expressions and use more kw variations, for keyword in keywords: kw_list = [' '+keyword+',',' '+keyword+' ',' '+keyword+'.','. '+keyword] for kw in kw_list: if kw in text: related_tweet_count += 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7634626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access "textChanged" event from text box that added to telerik Rad Grid? Hi There Do you know how to access textboxes textChanged event added to a radgrid that are bound but are used to trap any row related input a user typed in to the textbox for that column. I need to access this data server side when a postback occurs. Your thoughts are greatly appreciated Thanking you A: Being in a RadGrid really doesn't change much. Set AutoPostBack="true" on the TextBox, and create an OnTextChanged event handler: <telerik:RadGrid ID="RadGrid1" runat="server"> <MasterTableView AutoGenerateColumns="false"> <Columns> <telerik:GridTemplateColumn> <ItemTemplate> <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" OnTextChanged="TextBox1_TextChanged" /> </ItemTemplate> </telerik:GridTemplateColumn> </Columns> </MasterTableView> </telerik:RadGrid> In code-behind: protected void TextBox1_TextChanged(object sender, EventArgs e) { TextBox txt = sender as TextBox; if (txt != null) { //some logic here } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hibernate throws SQLException Could not reset reader java.sql.SQLException: could not reset reader at org.hibernate.lob.ClobImpl.getCharacterStream(ClobImpl.java:100) at org.hibernate.type.ClobType.set(ClobType.java:70) at org.hibernate.type.ClobType.nullSafeSet(ClobType.java:141) at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2025) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2271) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2688) at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) Hi, Above is the stack trace. It is working with small amount of data but fails with large data. I cant figure out what could be the problem? Regards, Preet A: We just solved a similar problem and I would like to describe the problem here in case someone encounters it. Note that there is another question about the same problem. We have Oracle 10, Hibernate 3, Java 1.4 and patched Ojdbc14. We created CLOBs using ˇHibernate.createClob(String)ˇ. The program (batch job) failed on large strings (~700KB). The problem was that with Hibernate we first inserted the entity with CLOB and the updated it (including CLOB). The second update was a part of many-to-one update. The CLOB didn't change in between, it's just that Hibernate wanted to update it twice. And it got this "could not reset" reader error. It seems that it can not use the same stream twice. We fixed this by making sure that CLOB is saved only once. A: We had this issue when porting a MySQL-backed transaction system to a H2 database. (Somewhat similar to this issue on the now-obsolete Hibernate forums.) Our story * *We had model entities with blob fields. *In code, we were fetching batches of these entities transactionally, updating their status to "processing", and then reading the blob payloads outside the transaction (after the status update is committed) for the actual processing. *Lazy-loading was not working initially, so every fetch was pulling in the blob field content along with the entity. At transaction commit, Hibernate checks the dirtiness of each field, and pushes updates for all dirty fields back to the DB. In Hibernate's change detection mechanism, blobs were always being treated as dirty (probably because you cannot compare two blobs in a non-invasive way; e.g. if one blob is stream-backed, you would have to actually consume the stream in order to compare its content with another blob). Check out: * *org.hibernate.type.AbstractStandardBasicType#isDirty(java.lang.Object, java.lang.Object, boolean[], org.hibernate.engine.spi.SharedSessionContractImplementor) and *org.hibernate.type.descriptor.java.BlobTypeDescriptor#areEqual to see how blob comparison eventually boils down to a simple == check. While you might expect this to still return true (as we never touch the blob field), proxy-wrapping and other Hibernate-level internals would cause the final blob object to be a different object altogether, failing the == test. As a result... *In the commit phase, every previously fetched blob was being consumed (read), in order for its content to be written back to the database. This is not a problem for MySQL because their blobs are in-memory (and can be read multiple times without causing stream exhaustion). However H2 provides stream-backed blobs, which means they are read-once. *So, when we were trying to (re-)read the blob after the transaction, Hibernate was trying to reset the already-consumed stream for the next read, and failing. Our solution The solution was simply to enable lazy loading for blob fields as outlined in this SO answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Rectangle used in ZXING Library for scanning QR code is not centerd I have requirement in which I need to scan the QR code using ZXING library in Android application. I have added complete ZXING code in my project and written following code for opening camera for QR code scanning. Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); the rectangle used to scan QR code on camera isn't at center? rectangle is coming at bottom right corner. I haven't changed any code from ZXING library. Can anybody help me out for this solution to get that rectangle in Centered? A: PS, developer here, this was fixed (or rather, workaround) about a month ago in the source tree. A version 4.0 is going to be released shortly that contains the change. A beta version is here: http://code.google.com/p/zxing/downloads/list The problem is that some devices think they are in landscape mode at creation, even when the app is landscape-only. It's a platform or device problem but easily worked around.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there an embeddable FLV player with external audio support? I'm looking for an embeddable FLV player that lets me specify a custom audio track that overrides (i.e. mutes and players over) the existing audio (if any) in the FLV file. I don't want to do any re-encoding - I simply want to specify a playlist of videos and an external audio track. I looked through the JWPlayer and FlowPlayer docs and neither of them support this. A: Have you considered using two players, one for audio, one for video, and muting the audio part of the video player? I have done something similar successfully using JPlayer. (The video in my case was without sound and I used a second player instance to add the sound. But I don't see why this shouldn't work even when the video has audio of its own.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Maps V3 panTo offset I am having the same issue as this folk ( link ), trying to offset panTo coordinates. The only solution I've found so far is to use panBy after I've used panTo. map.panTo( position ); map.panBy(120, -70); Those familiar with the Google Maps API will know that the issue with this approach is that it will trigger a smooth animation after panTo, to move to panBy. I wonder if there is a better approach?
{ "language": "en", "url": "https://stackoverflow.com/questions/7634655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Order of derived classes in the console my last problem is with inheritance in C#. I thought I understood this topic but somehow I am missing the point why the output is like that. Here are my classes: BaseClass: public abstract class Vehicle { public Vehicle() { Console.WriteLine("Honda Civic"); } public abstract void Display(); } Derived Class 1: public class Vehicle4Wheels : Vehicle { public override void Display() { Console.WriteLine("Derived111 class Constructor."); } } Derived Class 2: public class SportCar : Vehicle4Wheels { public new void Display() { Console.WriteLine("Derived222 class Constructor."); base.Display(); } } This is the hierarchy: Base Class -> Derived Class 1 -> Derived Class 2 This is the output I am getting: Honda Civic Derived222 class Constructor. Derived111 class Constructor. This is the output I am trying to achieve: Honda Civic Derived111 class Constructor. Derived222 class Constructor. I have read several articles where it was stated that base class is printed first and the other derived classes are printed based on their spot in the hierarchy. So why is the last derived class printed before the first derived class? What am I missing (except C# programming skills)? Thank for the answers. EDIT: I am sorry it took me a while to get back to this thread. To be more precise, I will post the task of the homework I am trying to achieve: Work 2: An abstract class is not a complete class, it misses some parts, and you cannot create objects from it. The programmer who writes the derived classes must fill in the missing parts. Consider an abstract class Vehicle. Derive two hierarchies from this class as it is shown below: Now, write 4 classes, see the yellow rectangle. Start from the abstract base class Vehicle -> Vehicle with 4 wheels -> Sport Cars and stop at the derived class Rally, which is the most specific class. The class Vehicle contains a field which holds the vehicle name and an abstract method void Display(). Implement this function in the derived classes, so that the function returns information about the vehicle, e.g. the motor power and other necessary properties. The last derived class has private fields to hold the motor power, the car weight, the car acceleration, the highest speed and a function that computes the specific power (power / weight). The function Display returns a text string with all this information. Test your work in a Console application that uses objects of the type of the classes Sport car and Rally. Class Vehicle: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace A_work_2 { public abstract class Vehicle { public string vehicleName; public abstract void Display(); } } Class Vehicle4Wheels: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace A_work_2 { public class Vehicle4Wheels : Vehicle { public override void Display() { Console.WriteLine("Car1"); } } } Class SportCar: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace A_work_2 { public class SportCar : Vehicle4Wheels { public override void Display() { Console.WriteLine("Derived222 class Constructor."); } } } Class Rally: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace A_work_2 { public class Rally : SportCar { private double motorPower = 408; private double carWeight = 2380; private double carAcceleration = 4.7; private double highestSpeed = 250; public double SpecificPower() { double specificPower = motorPower / carWeight; return specificPower; } public override void Display() { Console.WriteLine("The acceleration is: {0}.\nThe highest speed is {1} km/h.", carAcceleration, highestSpeed); Console.WriteLine("Specific power is {0}", SpecificPower()); } } } I am not sure how to achieve the goal of the task with abstract methods. Thank you for answers, V. A: You are mixing the concept of a constructor with the concept of a virtual method. Constructors are indeed called in order from base to derived, but you have created non-constructor virtual methods. This will give the output you wanted: // In Vehicle4Wheels public Vehicle4Wheels() { Console.WriteLine("Vehicle4Wheels constructor"); } // In SportCar public SportCar() { Console.WriteLine("SportCar constructor"); } (Also, edit the string you are printing in the Display() methods, since they are misleading - Display() is not a constructor.) As for virtual methods (note that abstract methods automatically become virtual), the "most derived" class' method is the one that is called, and only that method is called - unless the method invokes base.MethodName(). A: This is the output I am getting: Honda Civic Derived222 class Constructor. Derived111 class Constructor. This is the output I am trying to achieve: Honda Civic Derived111 class Constructor. Derived222 class Constructor. Ok, just swap the calls: public new void Display() { base.Display(); Console.WriteLine("Derived222 class Constructor."); } A: You first Get Honda Civic because it is output during the creation of the base class. the constructors of the base class is the first thing that is perform during the constructor of the inherited class. Then you Get Derived222 because it is output first in your display method. A: Change your code that way : public abstract class Vehicle { public Vehicle() { Console.WriteLine("Honda Civic"); } } public class Vehicle4Wheels : Vehicle { public Vehicle4Wheels() { Console.WriteLine("Derived111 class Constructor."); } } public class SportCar : Vehicle4Wheels { public SportCar() { Console.WriteLine("Derived222 class Constructor."); } you don't need to override the Display() method in what you(re trying to achieve. And beware of the use of the new keyword when declaring a method ;-) A: You didn't show the code you are using to test your classes, but I think it is something like this: SportCar car = new SportCar(); car.Display(); The first thing that is not so clear is why you are writing on the console in the constructor of the abstract class, but in a method of the derived ones. This means that, apart from the order of the messages, Honda Civic is written as soon as you create an instance of each one of your classe, while the other messages are written only when you call the Display method (even if you write Constructor in the method). @Seb gave you the right way to go if you want to do specific things in the constructors of a hierarchy of classes, but if you really wanted to write different versions of the method Display, you must be careful to the use of override and new. If a method is virtual or abstract, you should always use override, and leave the use of new to the cases in which you want to hide the method defined in the base classes. You can find an example (using cars like you :-)) here: [http://msdn.microsoft.com/en-us/library/ms173153(v=vs.80).aspx]. If you use override, the method being executed is determined at run time and depends on the type of the object. If you use new the method being executed is determined at compile time and depends on the type of the variable you assign your object to. For instance, if you execute this piece of code with your classes: Console.WriteLine("This is the constructor"); SportCar car = new SportCar(); Console.WriteLine("This is the first call to display"); car.Display(); Vehicle4Wheels car2 = car; Console.WriteLine("This is the second call to display"); car2.Display(); The result is: This is the constructor Honda Civic This is the first call to display Derived222 class Constructor. Derived111 class Constructor. This is the second call to display Derived111 class Constructor. Replacing the new with an override you obtain what you are probably expecting: This is the constructor Honda Civic This is the first call to display Derived222 class Constructor. Derived111 class Constructor. This is the second call to display Derived222 class Constructor. Derived111 class Constructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Writing rules in Fortify Does anybody know how to write a rule in HP Fortify SCA to check for an XML tag value in an XLM file? I have an XML like this with a regular expression and want to write a rule which checks whether the element matches a regex. <xml> <email>[a-z]@.com]</email> </xml> A: This is done with an XML style ConfigurationRule. I'm not sure if you want to match the value against a regular expression, or determine that the value is itself a regular expression. But regardless I will provide the structure of the rule and you are on your own for the pattern. <?xml version="1.0" encoding="UTF-8"?> <RulePack xmlns="xmlns://www.fortifysoftware.com/schema/rules" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="RulePack"> <RulePackID>D1B37203-B532-4F4F-BF1F-BA8796CABF21</RulePackID> <SKU>SKU-D1B37203-B532-4F4F-BF1F-BA8796CABF21</SKU> <Name><![CDATA[ rulepack name ]]></Name> <Version>1.0</Version> <Description><![CDATA[Description for .xml]]></Description> <Rules version="3.11"> <RuleDefinitions> <ConfigurationRule formatVersion="3.11"> <RuleID>1C80C1A2-10DF-40C3-B1B7-FCC3D7BD42F7</RuleID> <VulnKingdom>Code Quality</VulnKingdom> <VulnCategory>Email in XYZ Configuration</VulnCategory> <DefaultSeverity>5.0</DefaultSeverity> <Description formatVersion="3.2"></Description> <ConfigFile type="xml"> <Pattern>test.*\.xml</Pattern> </ConfigFile> <XPathMatch expression="/xml/email[text()='abc@foo']" reporton="/xml/email" /> </ConfigurationRule> </RuleDefinitions> </Rules> </RulePack>
{ "language": "en", "url": "https://stackoverflow.com/questions/7634663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: remove a set of characters from a script How to remove <p> and </p> from a text in javascript? I have a string <p> This is a text</p> and I want to remove the <p> and the </p>. How can I do that in Javascript? A: Use the replace() function. For example: "<p> This is a text</p>".replace(/<\/?p>/g,"").
{ "language": "en", "url": "https://stackoverflow.com/questions/7634664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google maps tiles doesn't load I'm developing a simple Google Maps app for Android. I'm using Eclipse and an Android Virtual Device. When running the app, no tiles are shown, and I get the message "Couldn't get connection factory client". I've read and looks like it is a bug, but some people say they got their apps working. I've tried using API 1.6, 2.1, 2.2 over my virtual device (2.2) and none of them work. I got my API key from the MD5 obtained from the debug.keystore. How can I solve the problem? I just found people with the same problem, but any solutions. Manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="uniovi.pfc" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="4" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <uses-library android:name="com.google.android.maps"/> <activity android:name=".SimpleMap2Activity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > </uses-permission> <uses-permission android:name="android.permission.INTERNET" > </uses-permission> <user-permission android:name="android.permission.ACCESS_COARSE_LOCATION"> </user-permission> </manifest> XML: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.google.android.maps.MapView android:id="@+id/mapview1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:enabled="true" android:clickable="true" android:apiKey="0YSU8-p-YkHYQ2lit-vAsh2U0jW5zV3l_YQVlvw" /> </LinearLayout> Code: package uniovi.pfc; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import android.os.Bundle; import android.view.KeyEvent; import android.view.Window; import android.view.WindowManager; public class SimpleMap2Activity extends MapActivity { private MapView mapView=null; private MapController mapController=null; private GeoPoint geoPoint=null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); mapView = (MapView) findViewById(R.id.mapview1); mapController = mapView.getController(); String coordinates[] = { "40.747778", "-73.985556" }; double lat = Double.parseDouble(coordinates[0]); double lng = Double.parseDouble(coordinates[1]); geoPoint = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)); mapController.animateTo(geoPoint); mapController.setZoom(5); mapView.invalidate(); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_I: mapController.zoomIn(); break; case KeyEvent.KEYCODE_O: mapController.zoomOut(); break; } return super.onKeyDown(keyCode, event); } } A: Finally, the problem was the maps apiKey. This topic is not very well explained over the internet. Shortly, I would explain as following: * *To use maps into an Android Virtual Machine, you use debug.keystore *To use maps into a real Android device, you need to create a key into a new keystore. Eclipse can do it for you if you right-click the project and export as a signed apk. *In both cases, you need to go to console, and execute a Java tool called keytool.exe at java jdk /bin/ folder. *If keytool gives you the SHA1 code and not the MD5, the problem can be that you are using Java 7. Add -v parameter to the keytool call to enter verbose mode, and you'll get also the MD5 Google asks you for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unit tests on the UI in MVC3 I have an MVC project and lots of TDD unit tests for testing the passing of data which all work fine. However, I am now going to add some tests for the GUI. How would I go about testing something such as the below: If home/page1, pressing "next" submit should goto "/Page2". I still dont quite understand how to do tests on UI based features. A: If you want to test the actions of the controller you can do something like that (i'm assuming a lot of things in this test but I hope you get the essentials) [Test] public void Page1_Post_IfallDataOK_ShouldSaveAndReturnPage2() { var controller = new HomeController(repository.Object); //repository is: Mock<IRepository> var result = controller.Page1(new MyModel() {MyValue = "test"}); Assert.IsInstanceOfType(typeof(RedirectToRouteResult), result); var redirect = (RedirectToRouteResult)result; Assert.AreEqual("Page2", redirect.RouteValues["action"]); repository.Verify(x => x.Save(It.IsAny<MyModel>()), Times.Once()); } A: http://blog.davidebbo.com/2011/06/precompile-your-mvc-views-using.html and http://blog.davidebbo.com/2011/06/unit-test-your-mvc-views-using-razor.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7634666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Horizontal Scrollbar does not work in winforms user control I've created an user control and added it to a form and enabled Auto Scroll property (True). When I resize the form, this user control horizontal scrollbar still remains the same width and does not change its length, due to which I am not able to see the user control contents when the form size is changed or the user control size is changed. Can anyone assist me in this on how to make the horizontal scrollbar works as expected: like when the form resizes, the horizontal scrollbar allows the user to see the contents of user control (which is the default beaviour). A: The Auto Scroll property(True) is a form property. It effects the behavior of the form in a case where you have controls outside the form visible area, it behaves like this: if Auto Scroll = true -> then you will have scrollbars in the form so you will be able to scroll to the unvisible controls or part of controls If Auto Scorll = false -> then scollbars wont be added to the form in any case, and the controls will remain unvisible. If you have content inside a control that is not visible, try changing the control's properties "Scrollable" to "true" or "Scrollbars" to "both", Depends on the control's type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Post a comment against a url If you add a facebook plugin in your site and comment on it, that comments are stored against a url(i.e. your site url) and you can retrieve all those comments by using graph api like below : https://graph.facebook.com/comments/?ids=< URL >. Here is my question : how to post a comment using graph api for the same url ? Thanks,Ranjith
{ "language": "en", "url": "https://stackoverflow.com/questions/7634674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to use some C source code in iPhone project? I found a speech synthesizer that supports many languages (http://espeak.sourceforge.net/index.html). But the source code that is available is written in C. What can i do to make it work on iPhone? A: Objective-C is a strict super set of C. Which means you can use any C code in your Obj-C project. A: Yes, as long as it's been ported to the LLVM C-compiler. You can create a statically linked framework out of it, and then link into your project. Apple does not allow dynamically-loaded frameworks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to resolve the confliction between "I'm currently working on a Spring MVC project and have some issue with using "<MVC:resource "tag of SpringMVC to load static resource. So I downloaded the springMVC showcase project and did some change on it to check this tag. Since my project is a simple one, seems to me the two tags for "conversionservice" is not necessary. However after I removed this two tag, something wired happend. If I have both the tag for static resources "<resources mapping="/resources/.." and the "<context:component-scan base-package="org.springframework.samples.mvc" />" tag (in controllers.xml) configged, then I cann't access any uri that anotated on controllers- it returns a 404 not found error. if I comment out the resource mapping tag, then those controllers works fine. Anyone have ever experience this situation? Any idea how to get around that? <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven conversion-service="conversionService"> <argument-resolvers> <beans:bean class="org.springframework.samples.mvc.data.custom.CustomArgumentResolver"/> </argument-resolvers> </annotation-driven> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <!-- Only needed because we install custom converters to support the examples in the org.springframewok.samples.mvc.convert package --> <beans:bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <beans:property name="formatters"> <beans:bean class="org.springframework.samples.mvc.convert.MaskFormatAnnotationFormatterFactory" /> </beans:property> </beans:bean> <!-- Imports user-defined @Controller beans that process client requests --> <beans:import resource="controllers.xml" /> </beans:beans> A: <context:annotation-config/> just don't work on Spring 3.1.0, but <mvc:annotation-driven/> just works, I referenced this post A: I got the same issue and what I did is to remove the "**" in the resource tag. A: I had faced similar issue - SO Question You can either use <mvc:annotation-driven/> or provide handler mapping yourself with order of higher precedence - <bean id="annotationUrlMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="order" value="0" /> </bean> <bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7634683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Paypal Vs Worldpay we are using Paypal Pro's Hosted solution for payments and finding that a lot of orders aren't completed when customers go to the payment page (one customer complained that they could only select Australia and United States for the shipping country!), we've found a lot of inconsistency with Paypal's service and 25% of orders aren't complete. Worldpay seems like good alternative, does anyone have experience of both Worldpay and Paypal, is Worldpay more reliable? Is Worldpay's documentation any good? Paypal's is terrible. Are there any other alternatives? We're trying to keep it simple by having the IMA and gateway all in one and process around £3k-£4k of payments a month. A: Take a look at Avangate - www.avangate.com A: This question is a few months old, but I'll answer it anyway. PayPal's documentation is quite bad, but WorldPay isn't much better. In fact, they have documentation in place for somethings they don't yet support, and it can be difficult at times to figure out whether it's your code or that the service does not exist. This applies, in particular, to recurring payments. We used to have PayPal, but we switched to WorldPay. My personal view is that PayPal is more flexible. WorldPay has its limitations - especially if you are selling SaaS and need some real flexibility, and as things get complicated for us, we have to get creative to work with it. But at the end of the day, WorldPay support is a million times better than PayPal. For us, they are slightly cheaper (and will become cheaper this year hopefully as we have done some volume with them). Support responds to emails pretty regularly if not a 100%. Plus you can call. They're even happy to look at server logs and tell you why or how something got lost if it got lost. To sum up and answer your question: * *On Documentation - they are almost the same as PayPal. *On service, they are MUCH, MUCH better. *On price, they will eventually get better and hold money for only 48 hours before it hits your account (this is negotiable, btw). *Depending on what you want, there are other options available. If you want recurring payments and your IMA and PSP to come from one source, WorldPay is a good alternative, especially if you are based in the UK. *If IMA and PSP being the same is not important, I suggest checking out SagePay (UK) and Authorize.net (US) - IMHO they are both quite good. SagePay has its limitations, though, especially if you want recurring billing. Please note, the above is based on my experience of selling customized, subscription based SaaS, not an online store.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In the Ruby programming language, what is the name of $: I want to know more about $: but I don't how is called. :015 > $: => ["/Users/Nerian/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/site_ruby/1.9.1", "/Users/Nerian/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/site_ruby/1.9.1/x86_64-darwin11.1.0", "/Users/Nerian/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/site_ruby", "/Users/Nerian/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/vendor_ruby/1.9.1", "/Users/Nerian/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/vendor_ruby/1.9.1/x86_64-darwin11.1.0", "/Users/Nerian/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/vendor_ruby", "/Users/Nerian/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1", "/Users/Nerian/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/x86_64-darwin11.1.0"] * *What is the name of this? *How and when is it used? *Should it be used at all, is it a good practice or a bad practice? *Is it supported by all Ruby implementations? *Any docs about it? A: Ruby have some PRE-DEFINED VARIABLES Pre-defined variables $! The exception information message set by 'raise'. $@ Array of backtrace of the last exception thrown. $& The string matched by the last successful match. $` The string to the left of the last successful match. $' The string to the right of the last successful match. $+ The highest group matched by the last successful match. $1 The Nth group of the last successful match. May be > 1. $~ The information about the last match in the current scope. $= The flag for case insensitive, nil by default. $/ The input record separator, newline by default. $\ The output record separator for the print and IO#write. Default is nil. $, The output field separator for the print and Array#join. $; The default separator for String#split. $. The current input line number of the last file that was read. $< The virtual concatenation file of the files given on command line (or from $stdin if no files were given). $> The default output for print, printf. $stdout by default. $_ The last input line of string by gets or readline. $0 Contains the name of the script being executed. May be assignable. $* Command line arguments given for the script sans args. $$ The process number of the Ruby running this script. $? The status of the last executed child process. $: Load path for scripts and binary modules by load or require. $" The array contains the module names loaded by require. $DEBUG The status of the -d switch. $FILENAME Current input file from $<. Same as $<.filename. $LOAD_PATH The alias to the $:. $stderr The current standard error output. $stdin The current standard input. $stdout The current standard output. $VERBOSE The verbose flag, which is set by the -v switch. $-0 The alias to $/. $-a True if option -a is set. Read-only variable. $-d The alias to $DEBUG. $-F The alias to $;. $-i In in-place-edit mode, this variable holds the extension, otherwise nil. $-I The alias to $:. $-l True if option -l is set. Read-only variable. $-p True if option -p is set. Read-only variable. $-v The alias to $VERBOSE. $-w True if option -w is set. http://www.zenspider.com/Languages/Ruby/QuickRef.html A: * *The canonical (english) name of the $: global is $LOAD_PATH. *As the name says, it is an Array of library search paths, i.e. an array of Strings representing all the folders where the interpreter will search libraries in (when it encounters a require "mylibrary" instruction) *It can be used with the same caution that has to be paid when dealing with globals. Actually, it is often used when writing test or demo scripts included in gems or libraries, so that the test modifies the load path in order to find the library under test before installing it (e.g. $: << "../lib" assuming the script is in a sibling of lib) *It is used by all canonical Ruby versions/implementation. Note though that the current directory . was part of $: on 1.8.x, and has been removed for security reasons on 1.9.x. *Docs is available on every Ruby primer (picaxe book, ruby docs site). A: It's equivalent to $LOAD_PATH. So I guess you can call it "load path". Google ruby load_path and you should find lots of usefull information. Personnaly I prefer to read $LOAD_PATH but $: is part of language so I guess it's ok to use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: python: adding to a dict gives error playlist = {} playlist.update(position, title) here position and title are two strings. I am getting the following error: TypeError: update expected at most 1 arguments, got 2 could some please help? thanks A: You can only update a dict with another dictionnary (you could also give it an iterable of tuples (key, value) : playlist = {item1 : value1} playlist.update({position : title}) print playlist >>> {item1 : value1, position : title} playlist.update([(item2, value2),]) print playlist >>> {item1 : value1, position : title, item2: value2} A: dict.update() expects a dictionary: playlist = {} playlist.update({position: title}) If you just want to set a single key, don't use update - use bracket notation instead: playlist[position] = title A: You must pass a dict as argument: >>> a = {} >>> a.update({'a': 1}) >>> a {'a': 1} A: playlist[position] = title This is the way you should do this. Update is handy when you try to copy elements of one dict into another one. A: Use this: playlist[position] = title playlist.update is to be used with a dictionary as an argument: playlist.update({position: title}) A: You have already got the answer. Posting a few good links: http://docs.python.org/library/stdtypes.html#dict.update python dictionary update method http://www.tutorialspoint.com/python/dictionary_update.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7634688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get elements width and height How can i get height and width of element which doesn't a part of DOM yet? For example: var t = $('<div style="position:absolute;height:100px;width:100px;background-color:steelblue;" >lalala</div>'); var height = t.height(); // height is 0! A: Works for me as well. You could try var height = t.innerHeight(); though as demonstrated in this fiddle. If that doesn't work for you (well possible depending on the browser), consider temporarily adding the element to the DOM: var t = $('<div style="position:absolute;height:100px;width:100px;background- color:steelblue;" >lalala</div>').hide().appendTo('body'); var height = t.height(); t = t.detach().show();
{ "language": "en", "url": "https://stackoverflow.com/questions/7634693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QT Ruby bindings signal-slot with hash param Im using qtbindings for Ruby (https://github.com/ryanmelt/qtbindings) and i would emit a signal with an hash param... Something like this: require 'Qt' class Foo < Qt::Object signals 'my_signal(Hash)' slots 'my_slot(Hash)' def initialize(parent = nil) super(parent) connect(self, SIGNAL('my_signal(Hash)'), self, SLOT('my_slot(Hash)')) end def emit_my_signal emit my_signal({:foo => :bar}) end def my_slot(hash) puts hash.inspect end end o = Foo.new o.emit_my_signal If I run this script I get the error: Cannot handle 'Hash' as slot argument (ArgumentError). If I use int instead of Hash everything is fine. There is a way to do this?? How? Thanks. A: Ok, I've found a solution: pass the string of the Ruby Object ID... Not use the ID as Fixnum because Ruby Fixnum objects may be up to 62 bits, but C ints are 32 bit. When you get the object id you can try to retrieve the object with ObjectSpace._id2ref(object_id_as_string.to_i). My solution code: require 'Qt' class Foo < Qt::Object signals 'my_signal(const QString&)' slots 'my_slot(const QString&)' def initialize(parent = nil) super(parent) connect(self, SIGNAL('my_signal(const QString&)'), self, SLOT('my_slot(const QString&)')) end def emit_my_signal emit my_signal({:foo => :bar}.object_id.to_s) end def my_slot(object_id) hash = ObjectSpace._id2ref(object_id.to_i) puts hash.inspect end end o = Foo.new o.emit_my_signal May be that the garbage collector go to destroy the hash object and the attempt to retrieve the object fail...
{ "language": "en", "url": "https://stackoverflow.com/questions/7634699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Declare variable of composite type in PostgreSQL using %TYPE Question: How can I declare a variable of the same type a parameter in a stored function? The simple answer is use %TYPE, this works: CREATE OR REPLACE FUNCTION test_function_1(param1 text) RETURNS integer AS $BODY$ DECLARE myVariable param1%TYPE; BEGIN return 1; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; But the problem is when param1 is a composite type: CREATE TYPE comp_type as ( field1 text ) CREATE OR REPLACE FUNCTION test_function_2(param1 comp_type) RETURNS integer AS $BODY$ DECLARE myVariable param1%TYPE; BEGIN return 1; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; This doesn't work: ERROR: type comp_type does not exist [SQL State=42704] So how can I do when param1 is a composite type? (Note: Just myVariable comp_type is not a good option because my function is slightly more complex.) Edited: I had a mistake on copy&paste, the real error is: ERROR: invalid type name "param1%TYPE" Position: 130 [SQL State=42601] And using param1%ROWTYPE the error is: ERROR: relation "param1" does not exist Where: compilation of PL/pgSQL function "test_function_2" near line 3 [SQL State=42P01] A: Use %ROWTYPE in that case. Simple case Tests by A.H. and DavidEG have shown this won't work. Interesting problem! You could try a workaround. As long as your definition is like the example you can simply resort to CREATE FUNCTION test(param1 comp_type) RETURNS integer LANGUAGE plpgsql VOLATILE AS $func$ DECLARE myvar comp_type; BEGIN RETURN 1; END $func$; But your real problem is probably not as simple? The real problem As expected, the real problem turns out to be more complex: a polymorphic input type. Workaround for that scenario was harder, but should work flawlessly: CREATE FUNCTION test(param1 anyelement, OUT a integer, OUT myvar anyelement) RETURNS record LANGUAGE plpgsql VOLATILE AS $func$ BEGIN myvar := $1; -- myvar has the required type now. -- do stuff with myvar. myvar := NULL; -- reset if you don't want to output .. a := 1; END; $func$; Call: SELECT a FROM test('("foo")'::comp_type); -- just retrieve a, ignore myvar See full output: SELECT * FROM test('("foo")'::comp_type); Note for Postgres 9.0+ There has been a crucial update in Postgres 9.0. The release notes: * *Allow input parameters to be assigned values within PL/pgSQL functions (Steve Prentice) Formerly, input parameters were treated as being declared CONST, so the function's code could not change their values. This restriction has been removed to simplify porting of functions from other DBMSes that do not impose the equivalent restriction. An input parameter now acts like a local variable initialized to the passed-in value. In addition to my workaround, you can (ab)use input variables directly now. Dynamic field names See: * *How to clone a RECORD in PostgreSQL *How to set value of composite variable field using dynamic SQL
{ "language": "en", "url": "https://stackoverflow.com/questions/7634704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using Mongoid tree for many to many relationships in rails? I just wanted to seek some advice on database design with mongoid and rails. If I have complex objects that need the ability to reference each other, would this be an appropriate solution. class Tree include Mongoid::Document include Mongoid::Tree end class Group < Tree end class People < Tree end class Cars < Tree end etc... So they can all belong to each other, be siblings or be children. Would this improve performance as they would all be in the same collection? Compared to if I was to use a habtm relationship between say 2, 3 or 4 models. Not entirely sure if separate models called in the same collection is faster or an appropriate design. The main reason I tried this design was because I was reading the the idea behind nosql is to use nest objects to minimize calls to the database. Does it make any difference referencing a child object in the same collection compared to a separate collection? Or even across multiple collections? There's a few questions here but hopefully someone could help point me in the right direction :) A: yes, good choice! You want to use Inheritance like this to store them in the same collection. You'll only have to access one collection - which should make it faster accessing children / parents.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight page with multiple page names in google analytics I'm using Google Analytics to track traffic on my Silverlight page. The same pages in my app are showing up under different names in the top content page. For example, I have /Home with the most pageviews, then /ClientBin/???.xap/Home with fewer pageviews and then /Default.aspx/Home with even fewer pageviews. It's the same with other pages (/ManageUsers, /ClientBin/???.xap/Manageusers, /Default.aspx/Manageusers) and so on. The pageviews are different, so we can't just add them together since we are not sure why this is happening. I know you can set a default homepage to account for differences in say / and /index.html, but that does't cover all our cases. What I need to know is why does this happen? Can we just add them together or are some of them a subset of others? Some of our users are using Out-of-browser, does that count as one of those three pages or is it mixed in with the others? A: With some testing using Fiddler I think I've come to a conclusion. * *The /ClientBin/???.xap/Home and similar pages are from Out-of-browser. *The /Default.aspx/Home and similar pages are from when you run the site from Visual Studio (debugging). *The /Home and similar pages are when the site is accessed on the server. So in our example we add together the /Home and /ClientBin/???.xap/Home visit numbers to get the real numbers (ignore /Default.aspx/...).
{ "language": "en", "url": "https://stackoverflow.com/questions/7634709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Preference ringtone default value I have this in my preferences.xml <RingtonePreference android:key="ringtone_uri" android:title="@string/preferences_select_ringtone" android:showDefault="true" android:srinlent="true" android:summary="@string/preferences_select_ringtone_summary" /> And every time when I first start fresh install of an app, the default value in silent :(, When I tap on the ringtone preference the dialog is opened with silent selected as default. I want by default "Default ringtone" to be selected. How can I do this How can I set the default value to be "default ringtone" not silent, I do not know why is this silent as my default I do not set in any place in my code, the silent is the default from android system ... A: The easiest way to set default value to default ringtone <RingtonePreference android:showDefault="true" android:showSilent="true" android:defaultValue="content://settings/system/notification_sound" ....... > </RingtonePreference> A: I was searching how to set default value for the ringtone, and realized that when the preference is not set than the value is empty and the silent is selected as default. But I do this defaultstr = Uri.parse(PreferenceManager.getDefaultSharedPreferences(context).getString("r_uri", android.provider.Settings.System.DEFAULT_RINGTONE_URI.toString())); //than I do this, I save the default ringtone to my setting if (defaultstr.equals(android.provider.Settings.System.DEFAULT_RINGTONE_URI)) { PreferenceManager.getDefaultSharedPreferences(context).edit().putString("r_uri", android.provider.Settings.System.DEFAULT_RINGTONE_URI.toString()).commit(); } I hope this will help to someone else. btw I freak out finding this workaround, and I was starching my head for hours A: Just disable the "Silent" item : <RingtonePreference android:key="ringtone_uri" android:title="@string/preferences_select_ringtone" android:showDefault="true" android:srinlent="true" android:summary="@string/preferences_select_ringtone_summary" android:showSilent="false">
{ "language": "en", "url": "https://stackoverflow.com/questions/7634711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Assembly resource missing exception with MonoTouch I'm facing an assembly resource missing exception with MonoTouch. I don't know what to do. The context: I've ported some existing code from SL to WP7 and MonoTouch. Internationalization is performed via satellite assemblies. Resources XYZ.Designer.cs is generated using the ResXFileCodeGeneratorEx. So under MonoTouch: I've the XYZ.de.resx, XYZ.fr.resx, etc... The compilation from MonoDevelop gives me the de/XYZ.resources.dll, fr/XYZ.resources.dll, etc... On the simulator, I get a System.Resources.MissingManifetResourcesException! A quick check on the app package shows me that the satellite assemblies de/XYZ.resources.dll, fr/XYZ.resources.dll are really missing. Cheers, patrick A: This was my mistake, a typo on the definition of the default namespace. Once the default namespace is ok, everything works as expected. Sorry guys.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python decoding Unicode is not supported I am having a problem with my encoding in Python. I have tried different methods but I can't seem to find the best way to encode my output to UTF-8. This is what I am trying to do: result = unicode(google.searchGoogle(param), "utf-8").encode("utf-8") searchGoogle returns the first Google result for param. This is the error I get: exceptions.TypeError: decoding Unicode is not supported Does anyone know how I can make Python encode my output in UTF-8 to avoid this error? A: Looks like google.searchGoogle(param) already returns unicode: >>> unicode(u'foo', 'utf-8') Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> unicode(u'foo', 'utf-8') TypeError: decoding Unicode is not supported So what you want is: result = google.searchGoogle(param).encode("utf-8") As a side note, your code expects it to return a utf-8 encoded string so what was the point in decoding it (using unicode()) and encoding back (using .encode()) using the same encoding?
{ "language": "en", "url": "https://stackoverflow.com/questions/7634715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "81" }
Q: Convert JSON empty array to empty string I have some JSON that looks like this: { "ST": "Security", "C1": "Login failures", "C2": "1", "C3": {}, "P1": "2", "P2": "administrator", "P3": {}, "P4": {}, "DESCR": "failed login attempts", "SID": "88", "AV": "NO", "SC": "0", "CN": {} } I also have this jQuery loop to filter out values: $.each(data, function(key, value) { var innerArr = []; $.each(value, function(innerKey, innerValue) { innerArr.push(innerValue); }); valueArr.push(innerArr); }); The problem is that on items C3, P3, P4 & CN in my example, the each loop is pushing the value [object Object] into my value collection. Is there a way to make these items empty strings rather than objects? A: You could use: ... if(typeof innerValue == "object") innerValue = JSON.stringify(innerValue); valueArr.push(innerValue); .... The stringify method of the JSON object turns an object into a string. The empty object {} will turn in "{}". If you want to add an empty string instead, use: if(typeof innerValue == "object"){ innerValue = JSON.stringify(innerValue); if(innerValue == "{}") innerValue = ""; } valueArr.push(innerValue); If you're 100% sure that your object is empty, you don't have to use JSON.stringify. typeof innerValue == "onject" would then be sufficient, to check whether you have to add "" instead of innerValue. An alternative method to check whether an object is empty or not: if(typeof innerValue == "object"){ var isEmpty = true; for(var i in innerValue){ isEmpty = false; break; } if(isEmpty) innerValue = ""; else { //Object not empty, consider JSON.stringify } } valueArr.push(innerValue); A: $.each(data, function(key, value) { var innerArr = []; $.each(value, function(innerKey, innerValue) { if (typeof innerValue == 'object') { innerValue = ''; } innerArr.push(innerValue); }); valueArr.push(innerArr); }); A: FYI, you can use .parseJSON function and get results easily var obj = jQuery.parseJSON('{"ST":"Security"}'); alert( obj.ST === "Security" ); A: $.each(data, function(key, value) { var innerArr = []; $.each(value, function(innerKey, innerValue) { innerValue = ($.isEmptyObject(innerValue)) ? '' : innerValue; innerArr.push(innerValue); }); valueArr.push(innerArr); }); Edit: If you didn't want to rely on jQuery's isEmptyObject() function, you could implement one yourself: Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; // Get the size of an object var size = Object.size(myArray); A: What is the inside loop for? It loops on each single letter of the String values. $.each(data, function(key, value) { var innerArr = []; if (jQuery.isEmptyObject(value)) { value = ''; } ... }); Anyway you can use jQuery.isEmptyObject() to test easily if value is an empty object and modify it to an empty string. A: $.each(data, function(key, value) { var innerArr = []; $.each(value, function(innerKey, innerValue) { innerArr.push(innerValue); }); //valueArr.push(innerArr); valueArr.push(innerArr.join()); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7634719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: xsl-fo: fop hangs up using table-header I'm trying to generate PDF using Apache FOP Version 0.94. I want to use table-header in my pattern, but when I apply it fop hangs up without any messages. When I paste code in table-body everything works fine. <?xml version="1.0" encoding="utf-8"?> <x:stylesheet version="1.1" xmlns:x="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <x:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="no"/> <x:template name="layout-master-set"> <fo:layout-master-set> <fo:simple-page-master master-name="Portrait" margin-left="1mm" margin-right="1mm" margin-top="1mm" margin-bottom="1mm" page-width="210mm" page-height="297mm"> <fo:region-body margin-left="15mm" margin-right="10mm" margin-top="10mm" margin-bottom="5mm"/> <fo:region-before border-style="none" border-width="thin" extent="15mm"/> <fo:region-after/> </fo:simple-page-master> <fo:simple-page-master master-name="Landscape" margin-bottom="1mm" margin-top="1mm" margin-left="1mm" margin-right="1mm" page-height="210mm" page-width="297mm"> <fo:region-body margin-right="9mm" margin-left="15mm" margin-top="13mm" margin-bottom="6mm"/> <fo:region-before/> <fo:region-after/> </fo:simple-page-master> </fo:layout-master-set> </x:template> <x:template match="/"> <fo:root> <x:call-template name="layout-master-set"/> <x:apply-templates select="data"/> </fo:root> </x:template> <x:template match="data"> <fo:page-sequence font-family="Times" master-reference="Landscape"> <fo:flow flow-name="xsl-region-body"> <fo:block font-size="9pt"> <fo:table table-layout="fixed" width="100%" empty-cells="show"> <fo:table-column column-number="1" column-width="9mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="2" column-width="70mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="3" column-width="16mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="4" column-width="14mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="5" column-width="14mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="6" column-width="11mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="7" column-width="11mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="8" column-width="8mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="9" column-width="10mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="10" column-width="13mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="11" column-width="17mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="12" column-width="20mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="13" column-width="11mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="14" column-width="21mm" border="black, solid, 0.3mm"/> <fo:table-column column-number="15" column-width="24mm" border="black, solid, 0.3mm"/> <fo:table-header> <fo:table-row font-size="8.5pt"> <fo:table-cell number-rows-spanned="2" display-align="center" text-align="center" > <fo:block>Но-</fo:block> <fo:block>мер</fo:block> <fo:block>по</fo:block> <fo:block>по-</fo:block> <fo:block>рядку</fo:block> </fo:table-cell> <fo:table-cell number-columns-spanned="2" display-align="center" text-align="center"> <fo:block>Товар</fo:block> </fo:table-cell> <fo:table-cell number-columns-spanned="2" display-align="center" text-align="center"> <fo:block>Единица</fo:block> <fo:block>измерения</fo:block> </fo:table-cell> <fo:table-cell number-rows-spanned="2" display-align="center" text-align="center"> <fo:block>Вид</fo:block> <fo:block>упаков-</fo:block> <fo:block>ки</fo:block> </fo:table-cell> <fo:table-cell number-columns-spanned="2" display-align="center" text-align="center"> <fo:block>Количество</fo:block> </fo:table-cell> <fo:table-cell number-rows-spanned="2" display-align="center" text-align="center"> <fo:block>Масса</fo:block> <fo:block>брутто</fo:block> </fo:table-cell> <fo:table-cell number-rows-spanned="2" display-align="center" text-align="center"> <fo:block>Кол-во</fo:block> <fo:block>(масса</fo:block> <fo:block>нетто)</fo:block> </fo:table-cell> <fo:table-cell number-rows-spanned="2" display-align="center" text-align="center"> <fo:block>Цена,</fo:block> <fo:block>руб. коп.</fo:block> </fo:table-cell> <fo:table-cell number-rows-spanned="2" display-align="center" text-align="center"> <fo:block>Сумма без</fo:block> <fo:block>учета НДС,</fo:block> <fo:block>руб. коп.</fo:block> </fo:table-cell> <fo:table-cell number-columns-spanned="2" display-align="center" text-align="center"> <fo:block>НДС</fo:block> </fo:table-cell> <fo:table-cell number-rows-spanned="2" display-align="center" text-align="center"> <fo:block>Сумма с</fo:block> <fo:block>учетом НДС,</fo:block> <fo:block>руб. коп.</fo:block> </fo:table-cell> </fo:table-row> <fo:table-row font-size="8.5pt"> <fo:table-cell column-number="2" display-align="center" text-align="center"> <fo:block>наименование,</fo:block> <fo:block>характеристика, сорт, артикул</fo:block> <fo:block>товара</fo:block> </fo:table-cell> <fo:table-cell column-number="3" display-align="center" text-align="center"> <fo:block>код</fo:block> </fo:table-cell> <fo:table-cell column-number="4" display-align="center" text-align="center"> <fo:block>наиме-</fo:block> <fo:block>нование</fo:block> </fo:table-cell> <fo:table-cell column-number="5" display-align="center" text-align="center"> <fo:block>код по</fo:block> <fo:block>ОКЕИ</fo:block> </fo:table-cell> <fo:table-cell column-number="7" display-align="center" text-align="center"> <fo:block>в</fo:block> <fo:block>одном</fo:block> <fo:block>месте</fo:block> </fo:table-cell> <fo:table-cell column-number="8" display-align="center" text-align="center"> <fo:block>мест,</fo:block> <fo:block>штук</fo:block> </fo:table-cell> <fo:table-cell column-number="13" display-align="center" text-align="center"> <fo:block>ставка,</fo:block> <fo:block>%</fo:block> </fo:table-cell> <fo:table-cell column-number="14" display-align="center" text-align="center"> <fo:block>сумма,</fo:block> <fo:block>руб. коп.</fo:block> </fo:table-cell> </fo:table-row> <fo:table-row> <fo:table-cell display-align="center" text-align="center"> <fo:block>1</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>2</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>3</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>4</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>5</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>6</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>7</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>8</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>9</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>10</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>11</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>12</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>13</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>14</fo:block> </fo:table-cell> <fo:table-cell display-align="center" text-align="center"> <fo:block>15</fo:block> </fo:table-cell> </fo:table-row> </fo:table-header> <fo:table-body> <fo:table-row text-align="center"> <fo:table-cell number-columns-spanned="7" border-left="white, solid, 0.3mm" border-bottom="white, solid, 0.3mm" display-align="center" text-align="right"> <fo:block margin-right="1mm">Итого</fo:block> </fo:table-cell> <fo:table-cell> <fo:block></fo:block> </fo:table-cell> <fo:table-cell> <fo:block></fo:block> </fo:table-cell> <fo:table-cell> <fo:block></fo:block> </fo:table-cell> <fo:table-cell> <fo:block>X</fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <x:value-of select='/data/requisites/req[@name="Total Summ wo NDS"]/@value'/> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block>X</fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <x:value-of select='/data/requisites/req[@name="Total NDS"]/@value'/> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <x:value-of select='/data/requisites/req[@name="Total Summ"]/@value'/> </fo:block> </fo:table-cell> </fo:table-row> <fo:table-row text-align="center"> <fo:table-cell number-columns-spanned="7" border-left="white, solid, 0.3mm" border-bottom="white, solid, 0.3mm" display-align="center" text-align="right"> <fo:block margin-right="1mm">Всего по накладной </fo:block> </fo:table-cell> <fo:table-cell> <fo:block></fo:block> </fo:table-cell> <fo:table-cell> <fo:block></fo:block> </fo:table-cell> <fo:table-cell> <fo:block></fo:block> </fo:table-cell> <fo:table-cell> <fo:block>X</fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <x:value-of select='/data/requisites/req[@name="Total Summ wo NDS"]/@value'/> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block>X</fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <x:value-of select='/data/requisites/req[@name="Total NDS"]/@value'/> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <x:value-of select='/data/requisites/req[@name="Total Summ"]/@value'/> </fo:block> </fo:table-cell> </fo:table-row> </fo:table-body> </fo:table> </fo:block> </fo:flow> </fo:page-sequence> </x:template> </x:stylesheet> resulting document (when the table header moved to table body)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google chrome does not start when running through Twist with Seleniumn Where i work uses Throughworks Twist 2.2 with Selenium for testing automation. For some odd reason on my particular machine the chrome driver starts but does not load chrome. The console reports no errors and i have no feedback on which to progress with. I installed Twist in the exact same way as everyone else here and it works for them. Twist will run with firefox for me but it is not as reliable as chrome and really impinges on development. The Twist site is typically useless source of information. I'n not expecting answers but would appreciate any hints as to where i can start looking into this. A: Turns, out Chrome driver was trying to launch a Chrome version installed under another user account, that was probably out of date. Delete old user profile and it works. It would be good to find out where Chrome Driver gets this config from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace a substring in C# I have the following string, "Last Run: 2011-10-03 13:58:54 (7m 30s ago) [status]" and I would like to replace "7m 30s" (it is not a fixed string) with another string I have generated. How can I do that with string manipulation in C#? A: string str = "Last Run : (3m 4s ago) [status]"; str = str.Replace("3m 4s", "yournewstring"); UPDATE : Ref : Kash's answer. If time is not fixed, it might be in hour,day, minute and second then regular expression is best choice as it's done by Kash. You can do it like below : string str = "Last Run: 2011-10-03 13:58:54 (7m 30s ago) [status]"; string replacement = "test"; string pattern = @"\((.+?)\s+ago\)"; Regex rgx = new Regex(pattern); string result = rgx.Replace(str, "(" + replacement + " ago)"); MessageBox.Show(result); A: You should consider using String.Format instead for this string result = String.Format("Last Run : ({0} ago) [status]", theTime); This is only if you have control over the string in question. A: You can try this : string s = "Last Run : (3m 4s ago) [status]"; s = s.Replace("3m 4s", myString); A: Use String.Replace() function for that and also see the below code. stirng YourString = "Last Run : (3m 4s ago) [status]"; YourString = YourString.Replace("3m 4s","Your generated String"); A: You can either use the String.Replace method on your string like: var myString = "Last Run : (3m 4s ago) [status]"; var replacement = "foo"; myString = myString.Replace("3m 4s ago", replacement); Or probably you want to use a regular expression like: var rgx = new Regex(@"\d+m \d+s ago"); myString = rgx.Replace(myString, replacement); The regular expression above is just an example and not tested. A: For the most convenient way to resolve this, use a combination of RegEx and String.Replace like the below code. I am assuming you do not have access to the generation of this input string (Last Run: 2011-10-03 13:58:54 (7m 30s ago) [status]). It basically has 3 stages: Locate the pattern: I am using the braces in the input string and "ago" as the pattern to locate the duration that you need to replace. "((.+?)\s+ago)" is the pattern used. It uses the lazy quantifier "?" to ensure it does minimal matching instead of a greedy match. May not be applicable to your example here but helps if the method will be reused in other scenarios. Create the backreference group to get the exact substring 7m 30s Regex.Match uses the pattern and creates the group that will contain "7m 30s". Please note the 1st group is the entire match. The 2nd group is what will be in the braces specified in the pattern which in this case is "7m 30s". This should be good even if later you get a duration that looks like: "Last Run: 2011-10-03 13:58:54 (1d 3h 20m 5s ago) [status]" Replace the occurence Then String.Replace is used to replace this substring with your replacement string. To make it more generic, the method Replace below will accept the inputstring, the replacement string, the pattern and the group number of the backreference (in this case only one group) so that you can reuse this method for different scenarios. private void button1_Click(object sender, EventArgs e) { string inputString = "Last Run: 2011-10-03 13:58:54 (7m 30s ago) [status]"; string replacementString = "Blah"; string pattern = @"\((.+?)\s+ago\)"; int backreferenceGroupNumber = 1; string outputString = Replace(inputString, replacementString, pattern, backreferenceGroupNumber); MessageBox.Show(outputString); } private string Replace(string inputString, string replacementString, string pattern, int backreferenceGroupNumber) { return inputString.Replace(Regex.Match(inputString, pattern).Groups[backreferenceGroupNumber].Value, replacementString); } This has been tested and it outputs "Last Run: 2011-10-03 13:58:54 (Blah ago) [status]". Notes: * *You can modify the Replace method appropriately for IsNullOrEmpty checks and/or null checks. *The button1_Click was my sample eventhandler that I used to test it. You can extract part of this in your core code. *If you do have access to the generation of the input string, then you can control the duration part while you are generating the string itself instead of using this code to replace anything. A: string input = "Last Run: 2011-10-03 13:58:54 (7m 30s ago) [status] "; string pattern = @"(\d+h \d+m \d+s|\d+m \d+s|\d+s)"; string replacement = "yay"; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); Console.WriteLine("Original String: {0}", input); Console.WriteLine("Replacement String: {0}", result); This is the example of http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx just changed the input and the pattern... The pattern can be improved because maybe in the input string you only receive the seconds or the hours, minutes and seconds.... Kinda of an improvement in the regex A: How about: Regex.Replace(yourString, @"\(.+\)", string.Format("({0} ago)", yourReplacement)); A bit brute force but should work and is simple. Explanation @"\(.+\)" will match a complete pair of brackets with anything between them (so make sure you will only ever have one pair of brackets else this won't work). string.Format("({0} ago)", yourReplacement) will return "(yourReplacement ago)" A: Don't use string.Replace. Just output a new string: TimeSpan elapsed = DateTime.Now.Subtract(lastRun); string result = string.Format("Last Run: {0} ({1} ago) [status]", lastRun, elapsed.ToString("%m'm '%s's'")); This assumes that the lastRun variable is populated with the last run time. A: this.lastrun is the string as I have defined in the question. this.lastRun = this.lastRun.Replace(this.lastRun.Substring(lastRun.IndexOf("(") + 1, (lastRun.IndexOf(")") - lastRun.IndexOf("(") - 1)) , retstr + " ago");
{ "language": "en", "url": "https://stackoverflow.com/questions/7634723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update Line series Chart with data consistently? I have a simple line series chart using WPFToolKit. I would like to have new data coming in to be updated on the chart every 5 minutes. But I have no idea how to go about it. The way I am showing data now is this. public Window1() { InitializeComponent(); showColumnChart(); } private void showColumnChart() { List<KeyValuePair<double,double>> Power = new List<KeyValuePair<double, double>>(); Power.Add(new KeyValuePair<double, double>(30, 40)); Power.Add(new KeyValuePair<double,double>(50, 60)); //Setting data for line chart lineChart.DataContext = Power; } Also, do I have to use a database? Any help would be appreciated. Thanks, A: Check http://www.c-sharpcorner.com/UploadFile/mahesh/WPfTimer09292009090518AM/WPfTimer.aspx (using Dispatcher Timer, you can achieve that).
{ "language": "en", "url": "https://stackoverflow.com/questions/7634728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Play Scala Anorm "Magic[Country]().using("Countries")" In looking at the docs for Play Scala Anorm, they show specifying a alternate table name as using this syntax: object Country extends Magic[Country]().using("Countries") When i try to use this i get: Error raised is : ';' expected but '.' found. What is the correct Scala syntax for this to work? A: Well there is an error in the example. You can do val Country = new Magic[Country]().using("Countries") but you certainly cannot do that with an object declaration You can use another constructor of Magic object Country extends Magic[Country](Some("Countries")) (see object User extends Magic[User]().using("users") can not compiled)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rankings in Azure Table I am just stuck in a design problem. I want to assign ranks to user records in a table. They do some action on the site and given a rank on basis of leader board. And the select I want on them could be on Top 10, User's position, Top 10 logged in today etc. I just can not find a way to store it in Azure table. Than I thought about storing custom collection object (a sorted list) in blob. Any suggestions? A: Table entities are sorted by PartitionKey, RowKey. While you could continually delete and recreate users (thus allowing you to change the PK, RK) to give the correct order, it seems like a bad idea or at least overkill. Instead, I would probably store the data that you use the compute the rankings and periodically compute and store the rankings (as you say). We do this a lot in our work - pre-compute what the data should look like in JSON view, store it in a blob, and let the UI query it directly. The trick is to decide when to re-compute the view. After a user does an item that would cause the rankings to be re-computed, I would probably queue a message and let a worker process go and re-compute the view. This prevents too many workers from trying to update the data at once.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: protected inheritance error #include<iostream> using namespace std; class base { protected: int a; public: base(int i) { a=i; } }; class derived :protected base { public: derived(){} void show() { cout<<a; } }; int main() { base obj(2); derived obj1; obj1.show(); return 0; } Why is this program giving error as In constructor derived::derived(): error: no matching function for call to base::base() Please explain. As i have read in stackoverflow that in case of inheriting as protected, protected members of base class became protected member of derived class. If I am wrong then please share a good link to clear my misconception A: Once you define a constructor for any class, the compiler does not generate the default constructor for that class. You define the parameterized constructor(base(int i)) for base and hence the compiler does not generate the no argument constructor for base. Resolution: You will need to define a constructor taking no arguments for base yourself. Add this to your base class: base():a(0) { } EDIT: Is it needed to define default constructor to every class? Or is it necessary to have the constructor that matches the derived type also present in base type? The answer to both is NO. The purpose of constructors in C++ is to initialize the member variables of the class inside the constructor. As you understand the compiler generates the default constructor(constructor which takes no arguments) for every class. But there is a catch, If you yourself define (any)constructor(one with parameters or without) for your class, the compiler does not generate the default constructor for that anymore. The compiler reasoning here is "Huh, this user writes a constrcutor for his class himself, so probably he needs to do something special in the constructor which I cannot do or understand", armed with this reasoning the compiler just does not generate the default no argument constructor anymore. Your code above and you assume the presence of the default no argument constructor(When derived class object is created). But since you already defined one constructor for your base class the compiler has applied its reasoning and now it refuses to generate any default argument constructor for your base class. Thus the absence of the no argument constructor in the base class results in the compiler error. A: You need to implement an empty constructor in base or invoke the defined base(int) constructor explicitly from derived c-tor. Without it, when derived c'tor is activated, it is trying to invoke base() [empty c'tor], and it does not exist, and you get your error. A: You must give a value to the base constructor: class Derived : protected base { public: Derived() : base(0) { } }; Depending on your implementation, give the value to the base constructor. However, you may want the Derived constructor to take also int as an argument, and then pass it to the base one. A: You haven't defined a default constructor for Base.. When you instantiate an instance of Derived, it will call the Derived() constructor, which will in turn try to call the Base() default constructur which doesn't exist as you haven't defined it. You can either declare an empty constructor for base Base::Base() or call the existing one as below: #include<iostream> using namespace std; class base { protected: int a; public: base(int i) { a=i; } }; class derived :protected base { derived(): Base(123) {} --this will call the Base(int i) constructor) void show() { cout<<a; } }; int main() { base obj(2); derived obj1; obj1.show(); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.Net Website project with 'add view' tooling There are many posts on this, most of which suggest adding the MVC project type GUID to the .*proj file. THe website project model doesn't have a project file though, so is there some way to get support for the add view dialog and tooling with a hybrid website / MVC project? A: There is no way to achieve what you want in a WebSite (at least not currently). The Add Controller functionality is implemented as a VSPackage that gets loaded when the MVC project type GUID is detected (that's why all the other posts mention it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7634747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android sectioned listview with complex view I want to use Jeff S. example for sectioned listview with headers. But I want to use more complex item view. Can you suggest me which approach is best to do this. I found two ways * *Put information in Map<String,String> item = new HashMap<String,String>(); using item.put() - example here 2.Using getView on ArrayAdapter (without overriding other methods ) - example here Which way is better? Thanks A: Depending on the complexity of your listitems it might be better to write your own adapter by extending BaseAdapter. This link has a nice tutorial on how to write your own adapters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET - JSON casting var a = JSON.Deserialize<object>(e.ExtraParams["address"]); The JSON [{"id":"","country":"MYcOUNTRY","city":"citycitycity","street":"street","block":"house","building":"building","additionalInfo":"fdsfdsfdsfds","latitude":"32.9206000","longitude":"35.1003000"}] and the class for storing information about address [Serializable] class BEAddress{ public string Id { get; set; } public string Country { get; set; } public string City { get; set; } public string Street { get; set; } public string Block { get; set; } public string Building { get; set; } public string Latitude { get; set; } public string Longitude { get; set; } public string AdditionalInfo { get; set; } } I can't savvy how to cast the object a to BEAddress? UPDATE: The way I seriliaze this data <script type="text/javascript"> var <%=ClientID%>_getAddress = function () { var jsonObj = []; jsonObj.push({ Id: <%=AddressIdHdn.ClientID%>.getValue(), Country: <%=cmbCountries.ClientID%> .getRawValue(), City: <%=cmbCities.ClientID%> .getRawValue(), Street: <%=txtStreet.ClientID%> .getValue(), Block: <%=txtBlock.ClientID%> .getValue(), Building: <%=txtBuilding.ClientID%> .getValue(), AdditionalInfo: <%=txtAdditionalInfo.ClientID%> .getValue(), Latitude: <%=txtLatitude.ClientID%> .getValue(), Longitude: <%=txtLongitude.ClientID%> .getValue() }); return jsonObj; } </script> A: I would imagine you'd need to do the following: BEAddress aVar = JSON.Deserialize<BEAddress>(e.ExtraParams["address"]); At the moment you're turning your JSON into a bog standard 'object' so you'd need to turn the JSON into a specific 'BEAddress' object as per the example above. A: What happens if you try the following: var a = JSON.Deserialize<BEAddress>(e.ExtraParams["address"]); What you're currently doing is deserializing into an generic object whereas you need a BEAddress. Also place the [Serializable] attribute onto BEAddress
{ "language": "en", "url": "https://stackoverflow.com/questions/7634757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to restore and store two String values? I have two values how can i store and restore it. public void SetCaseInfo(String PatientType, String Teethsselected) { // All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString(PatientType, Teethsselected); editor.commit(); } public String getCaseInfo() { SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0); String value = settings.getString(PatientType, Teethsselected); return value; } is it correct? A: In your code, PatientType must not change so you can be able to retrieve Teethsselected You are not saving the 2 strings public void SetCaseInfo(String PatientType, String Teethsselected) { // All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("teeth", Teethsselected); editor.putString("patient", PatientType); editor.commit(); } public String getTeethsselected() { SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0); String value = settings.getString("teeth", "default"); return value; } public String getPatientType() { SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0); String value = settings.getString("patient", "default"); return value; } A: You are storing only one value here: editor.putString(PatientType, Teethsselected); here PatientType is the key, not the value you want to save. Likewise, you are restoring only one value here: String value = settings.getString(PatientType, Teethsselected); Teethsselected is the default value for the key PatientType. If it's what you intended, than yes, it is correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Time (CLR Timespan) column using EF4.1 Code-First approach and SqlCe 4.0 I'be been trying to map a Timespan property to a SqlCe 4.0 database using EntityFramework 4.1 Code-First approach, and of course I'm getting a NotSupportedException saying there's no store corresponding EDM type 'Time' and CLR type 'Timespan'. I was already expecting this, but, according to this article, there's a conversion support since SqlCe 3.5 that maps a nvarchar(16) in the value form of 'hh:mm:ss.nnnnnnn' to a Time column. Does anyone know if it's possible to use this with EF4.1 Code-First? Regards A: The linked article refers to Merge Replication, not data type mapping in EF. You must either use a string and convert to and from timespan in code, or use datetime.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Embedding your site's functionality into anothers with Rails 3 (XSS vs iframes) We are looking to integrate the display of some of our models, as well as a payment process, with some of our client's websites. It seems that everybody is going the Iframe route, but this also looks to be rather outdated when compared to XSS techniques. How would one go about using XSS in rails 3 to enable multi page browsing functionality of elements of our site in another's site? As I understand it, we need to get a correct JSON protocol going, custom rendering in the client's website of the JSON, as well as maintaining state between page changes in the payment process and shopping cart. Iframes certainly seem easier, but I am open to discussion around this, and an explanation of using XSS. A: You need JSONP to do Cross domain scripting. This is a good article explaining it: http://emphaticsolutions.com/2011/01/21/functional-widgets-with-rails-javascript-jsonp.html Here's a discussion on iframe vs jsonp: JSONP vs IFrame? Also learn more about JSONP: https://www.google.com/search?q=writing%20widgets%20with%20jsonp
{ "language": "en", "url": "https://stackoverflow.com/questions/7634769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Calulating date difference in minutes by using HQL/SQL query I have a field of time Timestamp in my MySQL database which is mapped to a date datatype in my Bean. Now I want a query by which I can fetch all records in the database for which the difference between the current timestamp and the one stored in the database is > 20 minutes. How can I do it? What I want is select T from MyTab T where T.runTime - currentTime > 20 minutes I tried the following Query query = getSession().createQuery("Select :nw - T.runTime from MyTab T"); query.setDate("nw", new Date()); It returns some values like -2.0110930179433E13 . How can I model this in SQL/Hibernate? Even if I get some native SQL query (MySQL) then it's ok. A: I guess this link might help: https://forum.hibernate.org/viewtopic.php?p=2393545 and this one is also very helful: Hibernate Dialects + datediff function Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Registering a Firebreath .dll from local hard drive in Firefox How can I register a Firebreath .dll file thats deployed locally on a users hard drive. In IE, I can use ShellExecute in JavaScript to run a shell command to register the .dll How can I do the same for an NPAPI browser ? Thanks ! A: You can't register a .dll from inside the browser; if IE is letting you call ShellExecute from javascript that frightens me greatly. You certainly can't do that from firefox. The recommended way to install a FireBreath plugin is using an MSI file (which is built-in if you have WiX 3.5 or later installed when you run the prep script), though alternate methods include wrapping that MSI in an EXE installer, using an XPI/CRX/CAB file (though that doesn't work on Safari and only the CAB file of those three can install for all browsers). You can't directly register it from the browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SaveChanges() doesn't work (Entity Framework, C#, Windows Forms) I have a very weird problem. I try to submit changes to the database (using Entity Framework) like this: private ProfEntities pe = new ProfEntities(); //... var row = pe.Irregular_Veebs.Single(e => e.id == id); //selecting one row by id row.seen = true; //changing seen property to true pe.SaveChanges(); it looks simple but it doesn't work: when I look in Database Explorer, the "seen" field is still false. AM I doing something wrong? A: If you're using file database you probably explore db which is in your solution folder. To see changes you should open db from Release or Debug folder
{ "language": "en", "url": "https://stackoverflow.com/questions/7634784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In DDD where to keep custom exceptions (application exceptions)? In Infrastructure layer? I'm building a app with following architecture: UI - Application - Domain - Infrastructure I have a Application Layer that need use custom exceptions. Where I keep these custom exceptions? In Infrastructure layer? The problem is my Application Layer don't have reference to Infrastructure layer. What is the correct way? Update: Here's my code that throw a exception in Application Layer: public void InsertNewImage(ImagemDTO imagemDTO) { if (isValidContentType(imagemDTO.ImageStreamContentType)) { string nameOfFile = String.Format("{0}{1}", Guid.NewGuid().ToString(), ContentTypeHelper.GetExtension(imagemDTO.ImageStreamContentType)); string path = String.Format("{0}{1}", ImageSettings.PathToSave, nameOfFile); _fileService.SaveFile(imagemDTO.ImageStream, path); Imagem imagem = new Imagem() { Titulo = imagemDTO.Titulo, Descricao = imagemDTO.Descricao, NomeArquivo = nameOfFile }; _imagemRepository.Add(imagem); _dbContext.SaveChanges(); } else { throw new WrongFileTypeException(String.Format("{0} is not allowed.", ContentTypeHelper.GetExtension(imagemDTO.ImageStreamContentType))); } } Even ImageSettings is a ConfigurationSection is in my Application Layer because it uses it. I don't see other way I can transfer my ImageSettings (which should stay in Infrastrucuture Layer) to Infrastructure Layer, someone can help? public class ImageSettings : ConfigurationSection { /// <summary> /// Caminha onde será salvo as imagens /// </summary> [ConfigurationProperty("pathToSave", IsRequired = true)] public string PathToSave { get { return (string)this["pathToSave"]; } set { this["pathToSave"] = value; } } /// <summary> /// Extensões permitidas pra upload /// </summary> [ConfigurationProperty("allowedExtensions", IsRequired = true)] public string AllowedExtensions { get { return (string)this["allowedExtensions"]; } set { this["allowedExtensions"] = value; } } /// <summary> /// Tamanho das imagens /// </summary> [ConfigurationProperty("imageSize")] public ImageSizeCollection ImageSize { get { return (ImageSizeCollection)this["imageSize"]; } } } A: This is most likely related to your previous question. Exceptions are part of the contract that is defined by application layer and is implemented by infrastructure (DIP and Onion architecture). They should be defined in Appliction terms and handled by Application, but thrown from Infrastructure. For example, in your Application code: public class NotificationException : Exception {...} public interface ICanNotifyUserOfSuccessfullRegistration { /// <summary> /// ... /// </summary> /// <exception cref="NotificationException"></exception> void Notify(); } And in Infrastructure: public class SmsNotificator : ICanNotifyUserOfSuccessfullRegistration { public void Notify() { try { // try sending SMS here } catch(SmsRelatedException smsException) { throw new NotificationException( "Unable to send SMS notification.", smsException); } } } A: In DDD where to keep custom exceptions (application exceptions)? In Infrastructure layer? * *No Why? * *In a Clean Architecture, a center layer never depends on the outside, always the inverse *"The fundamental rule is that all code can depend on layers more central, but code cannot depend on layers further out from the core. In other words, all coupling is toward the center.". Please check the article from Jeffrey Palermo. I've written an article with Onion Architecture with a code sample. Please check this. But basically, you should add your custom exception to your layer (Application in this case). Just create a folder "Exceptions" and then add your user-defined exception there. Please check this link for my details about how to create user-defined exceptions A: Do you have a layer where cross-cutting concerns (such as logging or dependency injection) are addressed and which is referenced by all other projects in your solution? If so, this is where youd should put these custom exceptions. I guess that by "infrastructure layer" you actually mean this cross-cutting layer, but if so, it seems strange that your application layer is not referencing it. Alternatively, you could keep these exceptions in the application layer itself, provided that these exceptions are used only by that layer and perhaps by the UI layer too. A: Acaz Souza - you're incorrect in saying the Application Layer shouldnt reference the Infrastructure Layer. I suggest you read "Domain Driven Design Quickly", which is available for free from InfoQ. Look at the diagram below, which illustrates my point. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7634787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Cocoa/OSX - NSWindow standardWindowButton behaving strangely once copied and added again In my app I change the position of the standardWindowButtons close / miniturize / expand like so: //Create the buttons NSButton *minitButton = [NSWindow standardWindowButton:NSWindowMiniaturizeButton forStyleMask:window.styleMask]; NSButton *closeButton = [NSWindow standardWindowButton:NSWindowCloseButton forStyleMask:window.styleMask]; NSButton *fullScreenButton = [NSWindow standardWindowButton:NSWindowZoomButton forStyleMask:window.styleMask]; //set their location [closeButton setFrame:CGRectMake(7+70, window.frame.size.height - 22 - 52, closeButton.frame.size.width, closeButton.frame.size.height)]; [fullScreenButton setFrame:CGRectMake(47+70, window.frame.size.height - 22 -52, fullScreenButton.frame.size.width, fullScreenButton.frame.size.height)]; [minitButton setFrame:CGRectMake(27+70, window.frame.size.height - 22 - 52, minitButton.frame.size.width, minitButton.frame.size.height)]; //add them to the window [window.contentView addSubview:closeButton]; [window.contentView addSubview:fullScreenButton]; [window.contentView addSubview:minitButton]; Now when the window appears with the buttons there is two problems: 1. They are grey and not their correct color 2. when the mouse is over them they do not show the + - or x sign can anyone tell me what I am doing wrong. Thanks. A: I'm fully aware that this question is old and Valentin Shergin's answer is correct. It prevents the utilize of any Private API, unlike Google did in Chrome. Just wanted to share a method for those who don't feel like subclass NSView just to put those buttons in an existed view (such as self.window.contentView). As I just wanted to reposition the NSWindowButtons via setFrame:, I found out that once the window was resized, the tracking areas seems to "fix" themselves automagically, without any Private API usage (at least in 10.11). Thus, you can do things like the following to apply "fake resize" to the window that you repositioned your buttons: NSRect frame = [self.window frame]; frame.size = NSMakeSize(frame.size.width, frame.size.height+1.f); [self.window setFrame:frame display:NO animate:NO]; frame.size = NSMakeSize(frame.size.width, frame.size.height-1.f); [self.window setFrame:frame display:NO animate:YES]; (I did it within my main window's NSWindowDelegate windowDidBecomeMain:. Should work as long as the window is loaded and visible.) A: Here is the mechanics of this hover magic: Before drawing itself standard circled button (such as NSWindowMiniaturizeButton) calls their superview undocumented method _mouseInGroup:. If this method returns YES circled button draws itself with icon inside. That's all. If you place these buttons inside your own view, you can simply implement this method and control this mouse-hover-appearance as you want. If you just move or relayout these buttons and they still be subviews of NSThemeFrame (or something similar), you have to swizzle method _mouseInGroup: for this class, and probably it doesn't worth it because we have perfectly simple previous method. In my case I have custom NSView that contains my standard buttons as subviews and this code makes all described above magic: - (void)updateTrackingAreas { NSTrackingArea *const trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:(NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect) owner:self userInfo:nil]; [self addTrackingArea:trackingArea]; } - (void)mouseEntered:(NSEvent *)event { [super mouseEntered:event]; self.mouseInside = YES; [self setNeedsDisplayForStandardWindowButtons]; } - (void)mouseExited:(NSEvent *)event { [super mouseExited:event]; self.mouseInside = NO; [self setNeedsDisplayForStandardWindowButtons]; } - (BOOL)_mouseInGroup:(NSButton *)button { return self.mouseInside; } - (void)setNeedsDisplayForStandardWindowButtons { [self.closeButtonView setNeedsDisplay]; [self.miniaturizeButtonView setNeedsDisplay]; [self.zoomButtonView setNeedsDisplay]; } A: You're not adding them again. You're moving them to contentView. The buttons are originally in window.contentView.superview. [window.contentView.superview addSubview:closeButton]; [window.contentView.superview addSubview:fullScreenButton]; [window.contentView.superview addSubview:minitButton]; Should get you the correct behaviour without requiring a trackingArea. A: Call [button highlight:yes] for each button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: store the form values of textboxes automatically in database In c# windows application, I want to store the textbox values automaticaly into a database table as they are being entered.the database row should be updated as the user fills in all the textboxes. how to do it? A: your question is really vague and generic. I assume you are working with Windows Forms. Start reading some of the articles linked here: Windows Forms Data Binding especially those about Navigate and Binding Data in Windows Forms. A: In order to save it as they are changing, you can use event TextBox.TextChanged: void textBox1_TextChanged(object sender, EventArgs e) { string text = this.textBox1.Text; // your saving } Ok. If you want to save it as the input "is finished", you can use the event TextBox.Leave the same way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: How do I deploy a CLR Stored Procedure via the MsBuild command line? I can deploy a SqlClr project project from Solution Explorer by right clicking it an selecting Deploy. However, I would like a command line version where I can also specify custom ConnectionString. A: The command is msbuild MySqlClrProject.csproj /T:deploy. This assumes the code is built, and, at least on my machine, build the debug build by default. If you want to rebuild the solution, deploy the release binaries, and use a custom connection string, the command is msbuild MySqlClrProject.csproj /T:Clean;Build;Deploy /p:Configuration=Release;ConnectionString="Data Source= .;Initial Catalog=dropme;Integrated Security=True" You need to do this from a x86 2010 command prompt (MSBuild 4.0). It does not work in Visual Studio 2008 (MSBuild 3.5). I don't have Visual Studio 2012 to see if it works there. If you attempt to run this from a 64 bit command prompt you will get the following: c:\Users\jdearing\Documents\MySqlClrProject\MySqlClrProject.csproj(48,11): error MSB4019: The imported project "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\SqlServer.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk. Below is an example of what running the command successfully looks like: Setting environment for using Microsoft Visual Studio 2008 x86 tools. C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC>cd c:\Users\jdearing\Documents\MySqlClrProject c:\Users\jdearing\Documents\MySqlClrProject>msbuild MySqlClrProject.csproj /T:deploy Microsoft (R) Build Engine Version 4.0.30319.1 [Microsoft .NET Framework, Version 4.0.30319.261] Copyright (C) Microsoft Corporation 2007. All rights reserved. Build started 7/11/2012 4:58:04 PM. Project "c:\Users\jdearing\Documents\MySqlClrProject\MySqlClrProject.csproj" on node 1 (Deploy target(s)). SqlClrDeploy: Beginning deployment of assembly MySqlClrProject.dll to server . : dropme The following error might appear if you deploy a SQL CLR project that was built for a version of the .NET Framework that is incompatible with the target instance of SQL Server: "Deploy error SQL01268: CREATE ASSEMBLY for assembly failed because assembly failed verification". To resolve this issue, open the properties for the project, and change the .NET Framework version. Deployment script generated to: c:\Users\jdearing\Documents\MySqlClrProject\bin\Debug\MySqlClrProject.sql Dropping [MySqlClrProject].[SqlAssemblyProjectRoot]... Creating [MySqlClrProject].[SqlAssemblyProjectRoot]... The transacted portion of the database update succeeded. Deployment completed AfterDeploy: ---SqlReference--- Data Source=.;Initial Catalog=dropme;Integrated Security=True Done Building Project "c:\Users\jdearing\Documents\MySqlClrProject\MySqlClrProject.csproj" (Deploy target(s)). Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:09.37 c:\Users\jdearing\Documents\MySqlClrProject>
{ "language": "en", "url": "https://stackoverflow.com/questions/7634794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there a way to show all docvariables from a word file? I have a Microsoft-Word File which contains several DocVariables. In our application we fill/replace these DocVariables with content. With the shortcut Alt+F9 I can switch in a mode in which I can see the DocVariable. But in the document I have now, there are DocVariable which I cannot see. Is there a way/mode in Word 2007 in which I can see all the DocVariables which are defined in the Word-File? A: As far as I know there is not a way to do this with MS Word's built in features. You could write a custom VBA script that would get a list of all the DocVariables. But even easier than that I use the following program when I need to do what you are saying: http://gregmaxey.mvps.org/word_tip_pages/cc_var_bm_doc_prop_tools_addin.html It is a free add-in for Word that has done the job very well the times I used it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why ThreadAbortException does not throw in catch block Suppose I have this code: static void Main(string[] args) { var thread = new Thread(() => { try { throw new InvalidOperationException(); } catch (Exception) { Thread.Sleep(Timeout.Infinite); } }); thread.Start(); Thread.Sleep(TimeSpan.FromSeconds(1)); thread.Abort(); thread.Join(); } It starts thread, then thread is going into sleep in catch block and after that we are trying abort thread. Abort method have to raise ThreadAbortException. But in catch block it does not happen. It's documented: The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur. My question is why. Why is it working that way? Because in catch block we can raise any exceptions and all works like it have to. UPDATE: From the link by Jordão. Accepted because it's the most understandable clarification. Constrained Execution Regions The .NET Framework 2.0 introduces Constrained Execution Regions (CER), which impose restrictions both on the runtime and on the developer. In a region of code marked as a CER, the runtime is constrained from throwing certain asynchronous exceptions that would prevent the region from executing in its entirety. The developer is also constrained in the actions that can be performed in the region. This creates a framework and an enforcement mechanism for authoring reliable managed code, making it a key player in the reliability story for the .NET Framework 2.0. For the runtime to meet its burden, it makes two accommodations for CERs. First, the runtime will delay thread aborts for code that is executing in a CER. In other words, if a thread calls Thread.Abort to abort another thread that is currently executing within a CER, the runtime will not abort the target thread until execution has left the CER. Second, the runtime will prepare CERs as soon as is possible to avoid out-of-memory conditions. This means that the runtime will do everything up front that it would normally do during the code region's JIT compilation. It will also probe for a certain amount of free stack space to help eliminate stack overflow exceptions. By doing this work up front, the runtime can better avoid exceptions that might occur within the region and prevent resources from being cleaned up appropriately. To use CERs effectively, developers should avoid certain actions that might result in asynchronous exceptions. The code is constrained from performing certain actions, including things like explicit allocations, boxing, virtual method calls (unless the target of the virtual method call has already been prepared), method calls through reflection, use of Monitor.Enter (or the lock keyword in C# and SyncLock in Visual Basic®), isinst and castclass instructions on COM objects, field access through transparent proxies, serialization, and multidimensional array accesses. In short, CERs are a way to move any runtime-induced failure point from your code to a time either before the code runs (in the case of JIT compiling), or after the code completes (for thread aborts). However, CERs really do constrain the code you can write. Restrictions such as not allowing most allocations or virtual method calls to unprepared targets are significant, implying a high development cost to authoring them. This means CERs aren't suited for large bodies of general-purpose code, and they should instead be thought of as a technique to guarantee execution of small regions of code. A: The problem is that the thread you're attempting to abort is running inside a catch clause. This will abort the thread: static void Main(string[] args) { var thread = new Thread(() => { Thread.Sleep(Timeout.Infinite); }); thread.Start(); Thread.Sleep(TimeSpan.FromSeconds(1)); thread.Abort(); thread.Join(); } From this article: In the .NET Framework 2.0, the CLR delays graceful thread aborts by default over CERs, finally blocks, catch blocks, static constructors, and unmanaged code. This feature exists to keep the .NET framework more reliable in the face of certain asynchronous exceptions. Read the article I linked for the full story. Your code basically misbehaves and a host would probably escalate that thread to a rude thread abort: Rude thread aborts and rude application domain unloads are used by CLR hosts to ensure that runaway code can be kept in check. Of course, failure to run finalizers or non-CER finally blocks due to these actions presents the CLR host with new reliability problems, since there's a good chance these actions will leak the resources the back-out code was supposed to clean up. A: I suspect the point is that while you're in a catch or finally block, you're probably trying to clean up after yourself already. If an asynchronous exception can be triggered at that point, it's going to be really hard to do any sort of reliable cleanup. Joe Duffy's blog post about asynchronous exceptions is likely to clarify this more than I can... A: This is by design, this was introduced in Fx 3 or 4. You can look up the different versions form your own link and find different descriptions. Allowing an AbortException inside those protected regions (as in Fx 1.x) can lead to very unpredictable situations and an unstable Process. Note that Thread.Abort() is (was) generally dis-advised. And so is long-running code in any catch or finally clause. Disallowing Abort to interrupt a catch clause addresses some of the issues with Abort. But it's still not perfect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to validate the mail in the server side How to validate Email in server side . I know how to do that in client side but what about the server side? A: You can try this. String mail = "[email protected]"; string expression = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|" +@"0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z]" +@"[a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"; Match match = Regex.Match(mail, expression, RegexOptions.IgnoreCase); if (match.Success) Response.Write("VALID EMAIL"); else Response.Write("INVALID EMAIL"); return; A: You could use a RegularExpressionValidator: <asp:RegularExpressionValidator id="regEmail" ControlToValidate="txtEmail" Text="(Invalid email)" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Runat="server" /> As far as the regular expression to use, just pick one that suits your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Move a pin according to the position of the user In my iPhone application, I want to drop a pin at my current location using mapView and I also need to move another pin or a ball as my position changes. How can I do this? A: To display user location, just add : mapView.showsUserLocation = YES; To get it, use the method userLocation which gives you a MKUserLocation. You can then add a id<MKAnnotation> object with addAnnotation method to display another pin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send object to restful service I am using restEasy(Restful implementation for jboss) ejb3.0, Jboss5.1.1 AS I did restful service which accepting simple object. this is at the server side: @POST @Path("testObjects") @Consumes("application/xml") @Produces("text/plain") public String testObjects(GrandSun sun) { System.out.println(sun.toString()); return "success"; } this is the object which I have declared at the server side: package com.mirs.wma.web.data; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class GrandSun { int m = 1; int g = 2; } I test it via restfull client which sending xml string and it works fine. <?xml version="1.0" encoding="UTF-8"?> <grandSun> <m>111</m> <g>22</g> </grandSun> What I am looking for is a restful client which will be able to send the whole object (as is) without needing me to convert manually to xml format. Is there any option to do it via annotation? I will just need to annotate the object at the client side and send it as is to the restful service? thanks, ray. thanks, ray. A: Most IDEs can generate a WebService client-stub from a WSDL. This will provide the infrastructure needed to convert objects automatically into XML requests and deserialize the result. Failing that, check out wsdl2java. It will generate the stubs for you. A: Using RestEasy own client, along with a JAXB marshaller (I prefer Jackson but jettison comes stock with RestEasy I think). While on the server side POJOs are unmarshalled, the client side is responsible for marshalling the POJO. Hope this gives you a few hints.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Matlab RGB color representation ([255 255 255] and [1 1 1]) What's the difference between above two representation of white color? I'm a bit confused, and how they are used? A: The two equivalent representations are uint8([255 255 255]) and double([1 1 1]) These are just the integer and floating-point representations. Note that uint8([1 1 1]) will be (almost) black and that double([255 255 255]) will usually cause an error. Note that the integer version is only generally permitted by the image-handling functions, like imread, imwrite and image. Everything else will expect the floating-point representation. A: These two representations of white color refer to the RGB color model in which Red, Green and Blue lights are added together (additive color model) to produce the desired color. Each one of the three basic light is usually coded with an 8 bits integer which therefore ranges from 0 to 255 (0 meaning total absence of this light). In Matlab, these codes are often normalized by 255 and are floats between 0 and 1. Note that this is not the case when you open an image using imread for exemple, so you have to be careful and refer to the relevant parts of the documentation. Example: if you want to specify a particular color with an RGB code for a plot you can use plot(data,'color',[0 1 1]);. This plot your data with the color cyan (green+blue). See Matlab color specification for other ways of specifying colors in Matlab.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to catch error code in PHP i want to add records to table 'pool' with attribute ID and empName from database employees theform.html <FORM NAME ='form2' METHOD ='POST' ACTION ='result.php' enctype="multipart/form-data"> <B>Board Write</B> <BR> <INPUT TYPE = Text Name = empID value = 'write ID here'> <INPUT TYPE = Text Name = empName VALUE = 'write name here'><P> <INPUT TYPE = 'Submit' Name = Submit2 VALUE = 'Post'> </FORM> result.php <?PHP $ID = $_POST['empID']; $NAME = "'" . $_POST['empName'] . "'"; $server = "127.0.0.1"; //connect to server $user_name = "root"; $password = ""; $database = "employees"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if($db_found){// there is a database $tableSQL = "INSERT INTO pool(ID, empName) VALUES " . "(" . $ID . "," . $NAME . ")"; $result = mysql_query($tableSQL); if($result){ print "success!"; } else{ print "fail!"; } } mysql_close($db_handle); //close the connection; ?> in the database, ID is unique and also an INT datatype, i want to catch the error code where the user inputs an ID value that already existing in the database. how do we do this? A: You can use mysql_errno() (or mysqli_errno(), if you use mysqli) to get the error number after a query if it failed (check the return value of mysql_query()). It should be error #1022 (ER_DUP_KEY) according to the mysql error documentation A: In general, it is better to prevent SQL errors than to catch them. For example, check whether a duplicate exists before you even try to insert the record. To avoid the issue altogether, you could use an auto-increment field for the ID, and allow the database to assign new numbers automatically. Then the user would never need to enter it, so there would never be a clash due to duplicates. If you do still need to check for errors, then you can use the mysql_error() or mysql_errno() functions to get the error details. A: // returns true if duplicated function duplicate_catch_error ($database_connection) { $mysql_error = array (1022 => "Can't write; duplicate key in table '%s'",1062 => "Duplicate entry '%s' for key %d", 1586 => "Duplicate entry '%s' for key '%s'"); // also allows for the use of sscanf if (array_key_exists(mysql_error($database_connection),$mysql_error)) // checks if error is in array return true; else return false; } hope this answers your question, also mysql is now depreciated. Use mysqli if you didn't already know :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to post on facebook wall, without opening dialog box? I'am having a quiz program on my site where user logs in through their facebook account and play the quiz. After successfully completing the quiz I want to post their score and rank on their wall. Facebook login and logout is working fine. How do I show their score and rank on their wall without displaying a dialog box? I'm using this code to post the score and rank on user's wall- require 'src/facebook.php'; <?php $facebook = new Facebook(array( 'appId' => 'APP ID', 'secret' => 'SECRET KEY', )); ?> <script> FB.init({ appId:'APP ID', cookie:true, status:true, xfbml:true }); FB.ui({ method: 'feed', message: '<?php echo "My score is ".$myscore." and rank is ".$rank; ?>'}); </script> This code is opening a dialog box for me but that is with empty input field. If user will hust click on 'Publish' button then nothing will be posted on their wall and if they edit the text in input field then they will post wrong information. Either this field should be un editable or this box should not be there. Please suggest me a solution with code example. A: That's because FB not allowing pre-editing the message field. If you want to publish something in the user's Wall, you should have 'publish_stream' permission from the user, that way you will be able to post messages without requesting the user to enter something in it's message box or pressing the Publish button. But for this you have to call FB.api to access Graph API to access the user's Wall. For more details, see Graph API. Adding to this code you wrote, you should use OAuth2 methods by adding 'oauth: true' to the FB.init parameter. A: You should request "publish_stream" permissions to be able to publish Feed Stories without showing dialog to user. Sample code may look like this: FB.login(function(response) { if (response.authResponse) { console.log('Posting message'); FB.api('/me', 'post', {message: 'Beware, boiling water...'}); } else { console.log('User cancelled login or did not fully authorize.'); } }, {scope: 'publish_stream'});
{ "language": "en", "url": "https://stackoverflow.com/questions/7634812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running cron job from browser I have several cron jobs that run automatically, and I was requested to add a button that says 'run now' in the browser... Is this possible? Some of these cron jobs need to be executed from command line as they take around 15 minutes... Is it possible to execute them from the browser, not as a normal php function but somehow trigger an external php from the browser? A: You're looking for the exec() function. If it's a 15 minute task, you have to redirect its output and execute in in the background. Normally, exec() waits for the command to finish. Example: exec("somecommand > /dev/null 2>/dev/null &");
{ "language": "en", "url": "https://stackoverflow.com/questions/7634813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF service calls includes same information in every call I have a web service that will be consumed by some application (web site currently). The calls are almost all specific to a certain client but still the same. So one call might be getAllFoo() but I would need some parameter to say from which client the Foo is. It would become bothersome quickly if I just add a standard parameter to all calls so I was hoping to do it a little bit DRY and automatic. Something that would be included in all service calls. Is IDispatchMessageInspector the right thing for me here? What kind of info could that include and can I access that info inside the methods? Should I create some sort of attribute perhaps for the calls? If anyone could point me towards a solution for this it would be great. Edit Another solution I'm thinking off. Where the service call to a specific client happens on the consumer side, it will be known at instanceCreation so I could instance the ServiceClient with a known client. Could I use this solution for the ClientBase<> extender somehow. Let's say I'm serving Domain1 (let's call the client Domain to not confuse it with a serviceclient/consumer) I create a InformationProvider consumer side that has a ClientBase<IInformationService> field. I ensure that the DomainName (domain1) is set at construction so I could parhaps do the same thing when instancing the ClientBase<IInformationService> so It somehow let's the service know what domain I'm calling for. I'm just still learning about WCF so I'm not sure how one would do this. A: I can understand that you want to keep you solution simple and tidy, but ultimately - as you say yourself - ... I would need some parameter to say from which client... The obvious and simplest solution is to include a client parameter on all your service calls where it is required. Surely there'll be service calls that don't require the client parameter, and in those cases you don't need to include the parameter. You may be able to do something clever where a client identifier is passed discreetly under the covers, but beware of doing unnecessarily clever things. I would pass the client as a simple parameter because it is being used as a parameter. Two reasons come to mind: * *if someone maintains your code they quickly understand what's going on. *if someone needs to use the service it is obvious how to use it. A: A possible pattern: * *Make sure you service instantiates per session. This means you'll have to use wsHttpBinding, netTcpBinding, or a custom binding as http does not support sessions. *Always call an initialization operation when each session is instantiated that sets the client id for that service. *Put this initialization operation inside a constructor for a proxy. The steps involved would be something like this: [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)] public class MyService : IMyService { private int clientId; public void StartUp(int clientId) { this.clientId = clientId; and then client side, assuming you use the generated proxy, wrap the client inside another proxy. public class ExtendedClient : MyServiceClient { public ExtendedClient(int clientid) : base() { this.StartUp(clientid); } Now you should instantiate the ExtendedClient, it will create the channel and prime the service by delivering the client id. I would personally prefer to simply send the client id for each service call, but if you are able to use a session-able binding then this should work. Just some information on WCF for you. If you have a stateless service, then you'll need to include the client as a parameter in every service call. This does not mean you need to include the client everywhere throughout your code - you could, for example, retrieve it inside the ClientBase constructor. But you will need to add it to every OperationContract and all the service implementations. The alternative is to have a stateful service - the instance that you first use will remain for you to reuse (except for timeouts / exceptions). In this case you can potentially send the client just once, and then the service will know about the client for subsequent calls. This is the pattern described above. It means that you cannot use http binding. I believe that by doing this you're only increasing the potential for problems in your application (stateful services, having to ensure the initialization operation completes, more service calls being made).
{ "language": "en", "url": "https://stackoverflow.com/questions/7634823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: dompdf table rendering issue I'm using DomPDF to generate invoices in a project I'm working on. I've done so several times before and never had any trouble but since today however It got so slow that the maximum execution time gets reached. I've confirmed that this happens because of: $dompdf->render() I'm generating some tables to display the data in. but is seems to find this table quite difficult. Does anyone know what could be the problem? dompdf and my table can be found: http://pastebin.com/G585VQma (figured I'd put it on pastebin to save some space) A: dompdf doesn't support splitting table cells through pages, so you need to change the tables with cellspacing="10" into block elements like divs with the same styling, or at least not put the tables with many lines inside of these tables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is mLeft and mRight showing in hierarchyViewer? I'm trying to see my view properties using hierarchyviewer tool. My first problem is that my view seems to be invisible although I didn't do anything to make it invisible. My second problem is I see to values, mRight and mLeft which I expect to be the padding space to the parent. I actually don't know what mLeft and mRight means. But I don't expect to get a value greater than zero for mLeft. What can be causing this? A: mLeft is the absolute position in pixels of the left border of this particular view, and mRight is the same value for the right hand side. It's difficult to say what's causing your invisibility problem without more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tri state image button cant get both mouse over & pressed work together Hi I'm trying to create a three state button using three images. I cannot get both mouse over and pressed triggers work together. In the code below, mouse over works fine but the pressed image does not show when the button is pressed. <Button x:Name="button"/> <Button.Template> <ControlTemplate TargetType="{x:Type Button}"> <Grid> <Image x:Name="Normal" Source="run.png" Visibility="Visible"/> <Image x:Name="Pressed" Source="pressed.png" Visibility="Hidden"/> <Image x:Name="Over" Source="over.png" Visibility="Hidden"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="Pressed" Property="Visibility" Value="Visible"/> <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/> <Setter TargetName="Over" Property="Visibility" Value="Hidden"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="Over" Property="Visibility" Value="Visible"/> <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/> </Trigger> <Trigger Property="IsMouseOver" Value="False"> <Setter TargetName="Over" Property="Visibility" Value="Hidden"/> <Setter TargetName="Normal" Property="Visibility" Value="Visible"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate></Button.Template></Button> Any ideas? A: Triggers are evaluated in the order they appear in the XAML, so I think you most probably just need to re-order them as below: <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="False"> <Setter TargetName="Over" Property="Visibility" Value="Hidden"/> <Setter TargetName="Normal" Property="Visibility" Value="Visible"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="Over" Property="Visibility" Value="Visible"/> <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="Pressed" Property="Visibility" Value="Visible"/> <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/> <Setter TargetName="Over" Property="Visibility" Value="Hidden"/> </Trigger> </ControlTemplate.Triggers> This way the IsPressed settings will override the IsMouseOver equivalents.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the videos from iPhone in our app How can we get the video which are stored in the iphone library and Can we save that in our local database in our app and then we will delete the video from the iPhone Library, so that the video cannot be able to access in the iPhone library, but it can be used in the app. A: NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType]; NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL]; NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString * fetchPath = [documentsDirectory stringByAppendingPathComponent:@"TestDemo"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:fetchPath] == YES) { [fileManager removeItemAtPath:fetchPath error:nil]; } NSError * error = nil; if (Videourl == nil) { return; } [appDelegateIphone showLoadingViewforLandScapeRight]; [[NSFileManager defaultManager] copyItemAtURL:url toURL:[NSURL fileURLWithPath:fetchPath] error:&error]; A: You can use UIImagePickerController for retrieving images and videos from the iPhone Library. You are not able to delete any image or videos from the iPhone library. A: Use the UIImagePickerController class, and set the sourceType to be UIImagePickerControllerSourceTypePhotoLibrary (this will present the user with the dialogue to choose an item from their iPhone library). The delegate method didFinishPickingMediaWithInfo will then return a URL to the video the user has selected. You cannot delete a video stored in the iPhone library. However, you could use the UIImagePickerController to prompt the user to record a video. You can then save this video to the file area of your app. By default it will not be saved to the iPhone library. Check out the Apple documentation for more info. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }