text
stringlengths
8
267k
meta
dict
Q: Extract key from array I just wonder if i can get the keys from below code $keys = array_keys($_POST); //this will return all key $key = array_key($_POS['username']) //i dont know this this is possible, im trying to get the 'username' is it possible? A: array_keys($_POST); for the single key: list($key) = array_keys($_POST); or reset($_POST); $key = key($_POST); A: slier, are you looking for array_keys($_POST); ? A: You can get a list of all the keys with something like array_keys($_POST). If you just want to know whether a "username" was posted, isset($_POST['username']) would work. But if you're trying to take $_POST['username'] and know that its key was "username", you won't be able to reliably do that short of looping through the array like foreach ($_POST as $key => $value). A: if(array_key_exists('username',$_POST)){ $_POST['username']; } or for ($_POST as $key=>$value){ //Iterate and use $key } A: array_keys($_POST) is what you're looking for
{ "language": "en", "url": "https://stackoverflow.com/questions/7575864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get rid of this code duplication while still maintaining elegant events? Ok so let's say I have two classes, class A and class B. They both need to perform a common operation but it wouldn't make sense to have them both derive from the same object so instead we go with composition. Basically, "has a" makes sense where "is a" doesn't. Now each of the two classes instantiate this object and use it to perform the common operation and all is good. Everything is fine, now. The problem arises when each of these two classes have to expose an event that the common routine must raise. Uh oh. Now what? Well, we could do something like this in each of the two classes: public event EventHandler CommonEvent { add { theCommonObject.CommonEvent += value; } remove { theCommonObject.CommonEvent -= value; } } But now this code needs to be duplicated in each of the two classes and readers of the code may be somewhat confused by this code as well. add and remove are not very commonly seen keywords, at least. Still, there is duplicate code in both of the two classes and not only that, but this solution will not always work! For example, what if theCommonObject is locally instantiated in a single method and its scope is only within that one method. Well then, in that case we cannot even use the shortcut code posted earlier and we have to completely duplicate the code in both classes. Not only that but it just screams inelegance because we're basically just re-raising a copy of the event to clients. Example code that would have to be duplicated in each class in this case: public event EventHandler SomeCommonEvent; private void SomeMethod() { theCommonObject = new theCommonObject(); theCommonObject.DoSomething(); theCommonObject.SomeCommonEvent += thisClass_SomeCommonEvent; } private void thisClass_SomeCommonEvent(object sender, EventArgs e) { var handler = SomeCommonEvent; if (handler != null) { handler(this, e); } } As you can see, in both cases there is duplicate code but in the second there is even more because the object is local to a method rather than a member variable. I cannot really think of a way around this, other than using inheritance but I don't think it makes semantic sense to do so, and many often claim that composition is superior to inheritance in terms of complexity-reduction, ease-of-understanding, et cetera. A: You say you have a "has-a" relationship. From that, and based on your proposed solution that duplicates code, I assume your class A looks something like: public class A { private SomeCommonObject theCommonObject; public event EventHandler CommonEvent { add { theCommonObject.CommonEvent += value; } remove { theCommonObject.CommonEvent -= value; } } public A() { theCommonObject = new SomeCommonObject(); } } Where's the problem? theCommonObject can never be "locally instantiated in a single method and its scope is only within that one method." Yes, add and remove are not commonly used. So what? Clients of the class never see the add and remove. They still subscribe to the event using the traditional += syntax. The add and remove syntax is a non-issue as far as clients are concerned. And you, the developer, who is creating the class, are expected to know about these things. A: You could use static helper to get code one time but it's also 'bad' Problem is implementation can be written one time with derived, you decided not to derive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: I've received my first Exception. Now what do I do? I'm new to all this crazy Android/Java programming stuff. I have an app that (somehow) I managed to figure out how to add in-app billing items to. I'm pretty sure the error is related to in-app billing, but I'm not able to reproduce the problem on any of my devices. NullPointerException in ComponentName.<init>() java.lang.RuntimeException: Unable to destroy activity {ca.ajwest.BeerConverter/ca.ajwest.BeerConverter.BeerConverter}: java.lang.NullPointerException at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3035) at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3100) at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3216) at android.app.ActivityThread.access$1600(ActivityThread.java:132) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1037) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:143) at android.app.ActivityThread.main(ActivityThread.java:4196) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:507) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at android.content.ComponentName.<init>(ComponentName.java:75) at android.content.Intent.<init>(Intent.java:2893) at ca.ajwest.BeerConverter.BillingHelper.stopService(BillingHelper.java:270) at ca.ajwest.BeerConverter.BeerConverter.onDestroy(BeerConverter.java:615) at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3017) ... 12 more Could somebody please direct me to some resources where I can learn more about this output or something? Does anybody have any similar experiences? Here's the source if that helps at all. Thanks for your help. A: You should look your line 270 in BillingHelper.java and line 615 in BillingConverter. In error log, you should look for mainly two things; first, a line number which is related with your application names, second; name of the exception. You see that Caused by: java.lang.NullPointerException at android.content.ComponentName.<init>(ComponentName.java:75) at android.content.Intent.<init>(Intent.java:2893) at ca.ajwest.BeerConverter.BillingHelper.stopService(BillingHelper.java:270) at ca.ajwest.BeerConverter.BeerConverter.onDestroy(BeerConverter.java:615) says, there is a null pointer exception in one of your classes. Line numbers are also noted to check. There should be a variable, which isn't initialized or already destroyed. I hope that helps. A: You got an "Exception", while executing your code. Basically, something went wrong. Oracle's definition is "An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions." Take a look here to learn more In particular you got the NPE, NullPointerException From Javadoc: Thrown when an application attempts to use null in a case where an object is required. These include: * *Calling the instance method of a null object. *Accessing or modifying the field of a null object. *Taking the length of null as if it were an array. *Accessing or modifying the slots of null as if it were an array. *Throwing null as if it were a Throwable value. In other words, your program expected some object and got nothing in return.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to count nodes in XML that have been read into a string I'm sure the solution is pretty trivial to the experienced, but it's not to me. I have read an XML file into a string, strSiteList. Here's a shortened sample of the XML: <siteList> <site code="s0000001"> <nameEn>Edmonton</nameEn> <provinceCode>AB</provinceCode> </site> <site code="s0000002"> <nameEn>Vancouver</nameEn> <provinceCode>BC</provinceCode> </site> </siteList> How do I count the number of times a site appears? I've started with this: XDocument loaded = XDocument.Parse(strSiteList); int sitesCount = loaded.Nodes().Count(d => "some code that should work...arg..."; But I am lost as to whether it's the right way to start this or not. Thanks! A: A particular site? That sounds to me like: string site = "s0000002"; XDocument loaded = XDocument.Parse(xml); int sitesCount = loaded.Descendants("site") .Count(x => (string) x.Attribute("code") == site); For all sites, just: int sitesCount = loaded.Descendants("site").Count(); A: You can use simple XPath expression (using "System.Xml.XPath" required): XDocument loaded = XDocument.Parse(xml); int sitesCount = loaded.XPathSelectElements("siteList/site").Count(); A: Assuming that it's been read in correctly, you should be able to do this: int sitesCount = loaded.Descendants("site").Where(x => x.Attribute("code").Value == "1234").Count(); You can also do this: int sitesCount = loaded.Descendants("site").Count(x => x.Attribute("code").Value == "1234"); If you're looking for a count of all the sites, you can just do this: int sitesCount = loaded.Descendants("site").Count();
{ "language": "en", "url": "https://stackoverflow.com/questions/7575875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ActionScript 3 Trying to access a nested Moviclip and can't get it to work Im fairly new in Actionscript. That being said, I'm trying to access a nested Movieclip in a MovieClip. My code looks like this if (ground.hitTestPoint(char.getChildByName("charBox").x, char.getChildByName("charBox").y,true)) { falling = false; jumping = false; jumpSpeed = 1; fallSpeed = 0; speed = 15; } This is just a snippet of the hitTest. the "charBox" is the Movieclip I'm trying to access in the char Movieclip. So where did I go wrong? A: char.charBox.x Should work to get the x value if you have an instance of a MovieClip inside the parent clip Class like so: public var charBox:MovieClip = new MovieClip(); Or you have the instance name of that clip set to 'charBox' if you're using the Flash IDE, note the instance name is different than the name in the Flash IDE library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting error while trying to alter table in an sql block I create a test.sql file and inside I put: begin alter table table1 enable row movement; alter table table1 shrink space; end; / Is this not allowed? Because I get error: Encountered the symbol "ALTER" when expecting one of the following: begin case declare exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimited-identifier> <a bind variable> << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe A: You cannot issue DDL as static SQL in a PL/SQL block. If you want to put those commands in a PL/SQL block, you'd need to use dynamic SQL, i.e. BEGIN EXECUTE IMMEDIATE 'alter table table1 enable row movement'; EXECUTE IMMEDIATE 'alter table table1 shrink space cascade'; END; / It may be easier, however, to just issue consecutive SQL statements rather than issuing a single PL/SQL block.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Android viewpager, control which views to re-render my viewpager currently only re-renders views that are two views away from what is visually seen. example (shown respectively) ViewA, ViewB, CurrentView, ViewD, ViewE not rendered, rendered, rendered, rendered, not rendered` how would I force it to reload a particular view X many views away from the currentView, there are some use case scenarios where I want it to, and other cases when I dont want it to. But currently I only know how to reload the entire adapter - where it perhaps pulls from an arraylist I'm really not sure how to control the Viewpager - very few examples out there. All I know how to do is reset the entire list on "notifyDataSetChanged" insight appreciated A: use this method mViewPager.setOffscreenPageLimit(2) and you can set the limit of offscreen pages A: I think your going too need to decouple your view and data logic (array list in this case?). If you don't want the view to change, don't change the data layer. When you call notifyDataSetChanged everything will mimic your data layer. If you want a view to change, change the data layer and call notifyDataSetChanged. To put it simpler, the view just draws what the data tells it to, and expect that the view could update at any time. It is very similar to how listview works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: invalid conversion from 'char' to 'char*' using strcpy Ok so here are the parts of my code that I'm having trouble with: char * historyArray; historyArray = new char [20]; //get input cin.getline(readBuffer, 512); cout << readBuffer <<endl; //save to history for(int i = 20; i > 0; i--){ strcpy(historyArray[i], historyArray[i-1]); //ERROR HERE// } strcpy(historyArray[0], readBuffer); //and here but it's the same error// The error that i'm receiving is: "invalid conversion from 'char' to 'char*' initializing argument 1 of 'char* strcpy(char*, const char*)' The project is to create a psudo OS Shell that will catch and handle interrupts as well as run basic unix commands. The issue that I'm having is that I must store the past 20 commands into a character array that is dynamically allocated on the stack. (And also de-allocated) When I just use a 2d character array the above code works fine: char historyArray[20][]; but the problem is that it's not dynamic... And yes I do know that strcpy is supposed to be used to copy strings. Any help would be greatly appreciated! A: historyArray points to (the first element of) an array of 20 chars. You can only store one string in that array. In C, you could create a char** object and have it point to the first element of an array of char* objects, where each element points to a string. This is what the argv argument to main() does. But since you're using C++, it makes a lot more sense to use a vector of strings and let the library do the memory management for you. A: Two solutions. The first is if you for some reason really want arrays, the other is more recommended and more "C++"ish using std::strings. char * historyArray[20]; // Create an array of char pointers // ... historyArray[i] = new char[SIZE]; // Do this for each element in historyArray Then you can use strcpy on the elements in historyArray. Second solution which I repeat is recommended (I've fixed a few other things): string historyArray[20]; getline(cin, readBuffer); // Make readbuffer an std::string as well cout << readBuffer << endl; for(int i = 19; i > 0; i--){ // I think you meant 19 instead of 20 historyArray[i] = historyArray[i-1]; } historyArray[0] = readBuffer; A: Stop using C idioms in a C++ program: std::deque<std::string> historyArray; //get input std::string readBuffer; std::getline(std::cin, readBuffer); std::cout << readBuffer << std::endl; //save to history historyArray.push_front(readBuffer); if(historyArray.size() > 20) historyArray.pop_back(); As a result, we have: * *No buffer-overflow threat in readBuffer / getline() *No pointers, anywhere, to confuse us. *No arrays to overstep the ends of *Arbitrarily long input strings *Trivially-proven memory allocation semantics A: Error 1: You're indexing past your array bounds with i being set to 20. Error 2: historyArray[i] is a char, not a char *. You need &historyArray[i]. A: strcpy(&historyArray[i], &historyArray[i-1]); Array notation gives references while strcopy wants pointers. Convert references to pointers with address-of (&) operator. A: historyArray[i] is a char. It is a single character. You want to use a sting. Your fundemental problem is that historyArray is a char* which means that it points to a memory range containing characters. You want it to be a char** which is a pointer to a pointer to a string. Your initialization code would be char** historyArray; historyArray = new char* [20]; for (int i = 0; i < 20; i++) { historyArray[i] = new char [512]; //Big enough to have a 512 char buffer copied in } A: char * historyArray; historyArray = new char [20]; //get input cin.getline(readBuffer, 512); cout << readBuffer <<endl; //save to history for(int i = 20; i > 0; i--){ strcpy(&(historyArray[i]), &(historyArray[i-1])); //ERROR HERE// } strcpy(historyArray, readBuffer); //and here but it's the same error// But that will only fix the compiler errors, not the logical errors in the code. Your using C++ so the string solution: vector<string> history; cin.getline(readBuffer,512); history.push_back(readBuffer); Alternatively if you want one long string containing everything from readBuffer: string history; cin.getline(readBuffer,512); history = history += string(readBuffer); For example...
{ "language": "en", "url": "https://stackoverflow.com/questions/7575891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails, is it ok to look up objects in views? A controller points to a view. In that view is it acceptable to find objects <% @XXX = XXXX.where(..... %> or is that bad? Trying to work through performance issues which is why I ask. Thanks A: Putting query logic in the model has more to do with maintainability then it does with performance. Since most of the ActiveRecord/ARel logic deals with lightweight relation objects that only trigger the actual query based on certain methods, generally those provided via Enumerable (each/map/inject/all/first), which are usually called from the view anyway, the actual query gets triggered in the view, and not anywhere else. Here's an example of the difference between limit(3) and first(3) from an app I'm working on atm. ruby-1.9.2-p180 :018 > PressRelease.limit(3).is_a? ActiveRecord::Relation => true ruby-1.9.2-p180 :019 > PressRelease.first(3).is_a? ActiveRecord::Relation PressRelease Load (2.8ms) SELECT "press_releases".* FROM "press_releases" ORDER BY published_at DESC => false As you can see, limit does not actually trigger a query, where first does. When it comes to performance you are usually trying to ensure that your queries are not executed in your controller/model so that you can wrap them in a cache block within your view, thus eliminating that query from most requests. In this case you really want to make sure your not executing the query in your controller by calling any of the Enumerable methods. A quick example of a blog that lists the last 10 blog posts on the home page that is setup with caching might look like this. # app/controllers/posts_controller.rb class PostsController < ApplicationController def index # Something like this would trigger the query at this point and should be # avoided in the controller # @posts = Post.first(10) # So @posts here will be the Relation returned from the last_ten scope, not # an array @posts = Post.last_ten end ... end # app/models/post.rb class Post < ActiveRecord::Base # Will return an ActiveRecord::Relation scope :last_ten, order('created_at DESC').limit(10) end # app/views/posts/index.html.erb <ul> # The query will actually trigger within the cache block on the call to each, # preventing the query from running each time and also reducing the template # rendering within the cache block. <%= cache(posts_cache_key) do %> <% @posts.each do |post| %> .. <% end %> <% end %> </ul> For clarity, all this would be the exact same as doing # app/views/posts/index.html.erb <ul> <%= cache(posts_cache_key) do %> <% Post.order('created_at DESC').limit(10).each do |post| %> ... <% end %> <% end %> </ul> Except that if you now want to modify the logic for how it pulls the query, say you wanted to add something like where(:visible => true).where('published_at' <= Time.now) your jumping into your view instead of making changes in the model where the logic should be. Performance wise the difference is insignificant, maintenance-wise the latter turns into a nitemare rather quickly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Apache Solr 4 most functional autosuggest component Which one of the Solr components is the best: TermsComponent works well for us now but with limitations, ie: - we can't print out the image for associated document in the same response SpellCheckComponent will have same limitations as TermsComponent SearchComponent with NGrams This one seems to be the step in the right direction but ran into a few limitations as well: we'd like to be able to show all document grouped by doc type and suggest results in the following format: Platforms [IMG] XBOX (12) [IMG] PS2 (9) Category Action - Fighting (20) Action - Military (13) Publisher [IMG] Sony (20) [IMG] Microsoft (13) Games [IMG] Halo 2 [IMG] Halo 3 suggest Real Product Name + Image + ID + Number of matches sorted by the weight. Which is more likely to produce best results and minimize the load? We've got just under 25K documents A: You should be able to do this with a combination of ngrams, and faceting. You would search against the ngrams to get the documents you want, then use the facet queries to output your results properly. A: I wrote a blog post about making auto complete suggestions with Solr. Check it out, it might be useful! I wrote about the following different ways and the related pros and cons: * *Facet using facet.prefix parameter *Ngrams *TermsComponent *Suggester Unfortunately there isn't yet a complete solution ready to go, but the article can help you making the right choice depending on your requirements. Since you want to show a complex result and not just words, you should consider using NGrams. It is actually the most flexible solution, and you can combine it with faceting as already mentioned in the other answer you got.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to rotate a circular image button on its own axis in android app? I have the following animation code : <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate android:fromDegrees="0" android:toDegrees="360" android:pivotX="50%" android:pivotY="50%" android:repeatCount="100" android:duration="1000" /> </set> //imageButton layout code <ImageButton android:id="@+id/anime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/start" android:layout_centerHorizontal="true" android:paddingLeft="10dip" android:paddingTop="150dip" android:paddingBottom="10dip" android:paddingRight="10dip" android:background="@null" > </ImageButton> However, my circular image button is not rotating on its own axis. Rather, its following a circular path. Can anyone kindly help me out fix this animation ? Thanks. A: The pivot calculation in the animation is taking into account the padding of the ImageView. Since the padding is irregular (the top padding is different from the rest of the sides) the pivot of the animation is not aligned with the real center of your image. A: the padding for the imagebutton should be uniform.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP in_array Find Any Matches I am trying to figure out how to match any words within an array. For example, the code bellow works for finding "Test Name" within an array but does not find "Another Test Name" (due to the word "Another") within the array. Any ideas? if (in_array($html[$i], $eventsarray)) { $topeventaa = "yes"; } else { $topeventaa = "no"; } A: Taken from http://php.net/manual/en/function.in-array.php <?php /** * Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values. * * @param string $string Needle to find * @param array $array Haystack to look through * @result array Returns the elements that the $string was found in */ function find ($string, $array = array ()) { foreach ($array as $key => $value) { unset ($array[$key]); if (strpos($value, $string) !== false) { $array[$key] = $value; } } return $array; } ?> A: If you want to match any of the words to those in your array, you may want to use explode on your string and then check each token as you do in your example. A: We probably need more information, but you can create variable with the pattern matching you need with preg_match and pass it as the argument in your search. preg_replace and str_replace may be helpful, depending on what exactly you're trying to accomplish. A: You may want to look into recursive function calls, like when traversing through all the directories within a directory tree. I'd splice the array up to the index where it was found, leaving the remainder to be passed back into the same function to search through again. Depending on what results you want from knowing the number of occurrences of words within a string could we then start to break down the problem and write some code. A: Justin, there's no direct way--no existing built-in function--to do what I believe you seek; you must iterate over the array yourself, along the lines of $topeventaa = "no"; for ($eventsarray as $key=>$value){ if (0 <= strpos($html[$i], $eventsarray[$key])) { $topeventaa = "yes"; break; } } A: Use preg_grep instead of in_array to find all elements of an array matching a given pattern.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get authorId from Device - android I am using Android Market api. I use it to retrieve all the comments to my app: http://code.google.com/p/android-market-api/wiki/HowToGetAppComments My question is how can I know what is the authorId of the current user? I just need to know if that user already write a comment or not. Thanks! A: The example code at the link you posted shows this: public void onResult(ResponseContext context, CommentsResponse response) { System.out.println("Response : " + response); // response.getComments(0).getAuthorName() // response.getComments(0).getCreationTime() // ... } Based on the source code , to get theauthorID of the first comment for example, you should be able to use String id = response.getComments(0).getAuthorID();
{ "language": "en", "url": "https://stackoverflow.com/questions/7575900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding routing interface in Erlang I have a machine with multiple network interfaces each of which connects to a different network. I want to, from an Erlang application, find which interface will be used to connect to a given host. For example I have a machine with interfaces, eth0 and eth1. eth0 is on a 10.x.x.x network, eth1 is on a 192.168.0.x network. I want a function that give the ip address 10.0.1.2 will tell me eth0 and given the ip address 192.168.0.74 will tell me eth1. A: While you can read the list of interfaces and their addresses and masks in standard (if undocumented) Erlang with inet:getifaddrs/0, you can't get the list of routes which provides the other information you need to get the route for address. On most hosts (those that don't have a complicated routing setup as they generally don't forward packets) you usually just need the default route together with the interface addresses and masks in order to figure out how the host will route a packet for a given address. To begin, you need a list of interfaces and their routes. The getifaddrs/0 function gives you a proplist by interface and a list of addresses and masks. Because interfaces can have multiple addresses assigned to them you need a little bit of list parsing: routes() -> {ok, IFData} = inet:getifaddrs(), lists:append([ routes(IF, IFOpts) || {IF, IFOpts} <- IFData ]). routes(IF, Opts) -> {_,Routes} = lists:foldl(fun parse_opts/2, {undefined, []}, Opts), [{IF, Route} || Route <- Routes]. parse_opts({addr, Addr}, {undefined, Routes}) -> {{addr, Addr}, Routes}; parse_opts({netmask, Mask}, {{addr, Addr}, Routes}) when tuple_size(Mask) =:= tuple_size(Addr) -> {undefined, [{Addr, Mask} | Routes]}; parse_opts(_, Acc) -> Acc. Now that you have a list of route information Routes::[Route::{Interface::string(), {Addr::tuple, Mask::Tuple}}] you can find the matching routes: routes_for(Targ, Routes) -> [ RT || RT = {_IF, {Addr, Mask}} <- Routes, tuple_size(Targ) =:= tuple_size(Addr), match_route(Targ, Addr, Mask) ]. To match a route you need to mask the target address and compare that to the masked interface address. Masking an address provides the network address. match_route(Targ, Addr, Mask) when tuple_size(Targ) =:= tuple_size(Addr), tuple_size(Targ) =:= tuple_size(Mask) -> lists:all(fun (A) -> A end, [element(I, Targ) band element(I, Mask) =:= element(I, Addr) band element(I, Mask) || I <- lists:seq(1, tuple_size(Targ)) ]). You can then sort the routes in order of preference by comparing the number of high one bits in the mask. Handily, the bytes-of-mask-as-tuple format Erlang uses to represent masks compares directly as below: sort_routes(Routes) -> lists:sort(fun ({_, {_AddrA, MaskA}}, {_, {_AddrB, MaskB}}) -> MaskA > MaskB end, Routes). Now put it all together: route(Targ) -> route(Targ, routes()). route(Targ, Routes) -> sort_routes(routes_for(Targ, Routes)). routes_for(Targ, Routes) -> [ RT || RT = {_IF, {Addr, Mask}} <- Routes, tuple_size(Targ) =:= tuple_size(Addr), match_route(Targ, Addr, Mask) ]. On my machine right now I have the following routes: [{"lo0", {{0,0,0,0,0,0,0,1}, {65535,65535,65535,65535,65535,65535,65535,65535}}}, {"lo0",{{127,0,0,1},{255,0,0,0}}}, {"lo0", {{65152,0,0,0,0,0,0,1},{65535,65535,65535,65535,0,0,0,0}}}, {"en0",{{192,168,1,7},{255,255,255,0}}}, {"en0", {{65152,0,0,0,1548,52991,65242,57142}, {65535,65535,65535,65535,0,0,0,0}}}, {"vmnet1",{{172,16,0,1},{255,255,255,0}}}, {"vmnet8",{{192,168,148,1},{255,255,255,0}}}] So when finding a route to 127.0.1.1 (an address in the 127.0.0.0/8 network), I get: route({127,0,0,1}) -> [{"lo0",{{127,0,0,1},{255,0,0,0}}}]. Unfortunately I can't get a route for {8,8,8,8} for instance, because I only have information on directly attached networks. If I add the default route to the mix (via 192.168.1.1), I get: route({8,8,8,8}, routes() ++ [{{192,168,1,1}, {{0,0,0,0},{0,0,0,0}}}]). [{{192,168,1,1},{{0,0,0,0},{0,0,0,0}}}] route({127,0,0,1}, routes() ++ [{{192,168,1,1}, {{0,0,0,0},{0,0,0,0}}}]). [{"lo0",{{127,0,0,1},{255,0,0,0}}}, {{192,168,1,1},{{0,0,0,0},{0,0,0,0}}}] From here you'd have to a) come up with that extra route information I had to add manually (call os:cmd("netstat -rn") maybe?) and b) implement a second level of lookup for routes that return gateways (you need to recursively call route until you get back a route with an interface name -- a directly attached network, not a gateway address). The above code is available as a gist: interfaces.erl
{ "language": "en", "url": "https://stackoverflow.com/questions/7575906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cannot find type parameter if it is an inner class of the subclass in Java Why does the following code have a compile error: Foo.java: public abstract class Foo<T> { public abstract T getInner(); } MyFoo.java: public class MyFoo extends Foo<MyFooInner> { public static class MyFooInner { } public MyFooInner getInner() { return new MyFooInner(); } } Compiling the second class results in: MyFoo.java:1: cannot find symbol symbol: class MyFooInner public class MyFoo extends Foo<MyFooInner> { ^ 1 error Is there a way around this problem besides putting the inner class in its own file? A: Use the following notation: public class MyFoo extends Foo<MyFoo.MyFooInner> {... UPDATE: Static nested classes are effectively a top level class as specified here: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience. So, the only way you can refer to a static nested class is mentioning its parent class somewhere. Otherwise it is a reference to an imported class or to a class within the same package. UPDATE: To explain it even more, another way to reference the class is to import it like this: import my.package.MyFoo.MyFooinner; public class MyFoo extends Foo<MyFooInner> {... A: To build on @Andrey Adamovich's answer, the reason for this is that types identified in a class declaration must make sense to members outside that class. This is the same as if I had written the following in another class file: MyFooInner mfi = new MyFooInner() This would not compile because that class wouldn't know what MyFooInner was - I would either need to qualify it by writing MyFoo.MyFooInner or else use import MyPackage.MyFoo.MyFooInner;. The same logic applies to class declarations. For the same reason, nested classes that are declared private cannot be used in the parent class's declaration at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: bfcache causing issue with jQuery ajax request I have a document that, when ready ($(function (){ ... })), creates a request to load some data into a table. Users can then add items to this table. When items are added a request is sent to the server to save the item and then the row is added to the table client-side (very trivial application). If a user adds a row and then navigates to a different page and then presses their back button, the request is made to re-load all the rows. However, bfcache takes over and serves that last request's result cached rather than a hit to the server! I had thought that a real new request would be made, but this isn't the case. Obviously, refreshing works as expected. On the server side I'm using ASP.NET MVC 3, there is no caching on any of the action responses. The obvious solution is to add cache: false to the specific request or use $.ajaxSetup({ cache: false }) globally. This really isn't ideal because it should be the server controlling when requests should be cached. Is there any easy way to disable the bfcache for ajax requests? Or is there an easy way to detect loading via bfcache so that I could cache: false only if the page was loaded from back/forward?
{ "language": "en", "url": "https://stackoverflow.com/questions/7575910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to merge server-side templating and AJAX to maximize reusability Consider the following general issue before I go to the specific problem: You use server-side templating (e.g. Smarty) to generate a page in a particular way depending on a particular state. However, you can also change the state and update that page dynamically using Javascript. How do you construct such a system that does not involve replicating one's work in both Javascript and PHP? Now, for the specific question that relates to the above. I have a navigation bar for an educational website. Depending on the URL provided by the user, you can be at various levels of navigation: field, subject, course, section, lesson. For example, if the user accesses the following index.php?field=Social_Sciences, the following XML will be returned and parsed by PHP and sent to Smarty such that the appropriate subjects are listed: <subjects> <subject> <id>81</id> <name>Sociology</name> <description>Sociology</description> <path>/data/material/Social_Sciences/Sociology/</path> </subject> <subject> <id>82</id> <name>Economics</name> <description>Economics</description> <path>/data/material/Social_Sciences/Economics/</path> </subject> </subject> Similarly, if a user goes to index.php?field=Social_Sciences&subject=Economics, PHP would parse the following and send it to Smarty: <courses> <course> <id>65</id> <name>Introduction to Microeconomics</name> <description>Introduction to Microeconomics</description> <path> /data/material/Social_Sciences/EconomicsIntroduction_to_Microeconomics/ </path> </course> <course> <id>66</id> <name>Introduction to Macroeconomics</name> <description>Introduction to Macroeconomics</description> <path> /data/material/Social_Sciences/EconomicsIntroduction_to_Macroeconomics/ </path> </course> </courses> Now, the problem is the user can also dynamically navigate using AJAX--that is, they can click through the navigation without reloading the page. That means the navigation XML then has to be parsed by jQuery, which means I have to write the same code to parse the XML twice--once in PHP and once in Javascript. After this system proved unwieldy, I started only using AJAX even on the initial load but this is sub-optimal in terms of speed and number of requests. (If you think this is trivial, there are other examples of such issues in my code.) How can one continue to use PHP templating and dynamic AJAX updating without re-writing the same parsing code twice in both languages? A: JSON If you're php actions were returning JSON objects, then I would recommend jQuery's beta product .template() In a perfect world, you're in html 5 and can send the jQuery.template() parser equivalents of your smarty work from the server outright, as found on pandora.com's html 5 enabled player if you look at the bottom of the page source. it will kind of look like this: <!DOCTYPE html> <html> <head> <!--- pilfered from jQuery.com's demo linked above ---> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#aControl").click(function(event){ $.get("/your/url").success(function(text, response, jQxhr){ $("#iWillPrintACourseTemplate").tmpl(response).appendTo("#tbodyDestination"); }).error(function(text, response, jQxhr){ }); }); }); </script> </head> <body> <script id="iWillPrintACourseTemplate" type="text/x-jquery-tmpl"> <tr class="detail"><td><p>stuff : ${id} - ${}</p><p>${description}</p><p>${path}</p></td></tr> </script> <div><a id="aControl" href='#'>click me</a></div> <table> <thead/> <tfoot/> <tbody id="tbodyDestination"> </tbody> </table> </body> </html> not html 5 then you have to move the jQuery html 5 <script type='text/x-jquery-tmpl'/> declaration into your javascript via a $.template("name", html with templating ${} in it); i would get the html with templating ${} stuff via an ajax call. Why? I would try to keep your html templates server side. to allow easy translation between a SMARTY template and a jQuery.Template() should their syntax ever diverge.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: testing a rails helper that uses cookies I have a method in app/helpers/application_helper.rb that calls cookies. Which is totally allowed; this method is working wonderfully in my dev environment and knows what I mean when I say cookies. I am testing this helper with TestUnit (in test/unit/helpers/application_helper_test.rb) and getting the error NoMethodError: undefined method `cookies' for nil:NilClass Even for four tests that do not set cookies. This has nothing to do with needing to 'set cookies in the test using cookie_jar', because the issue isn't that I'm setting cookies and my helper isn't recognizing them, the issue is that the object cookies is being called on is nil. I wasn't sure which controller object cookies was being called on, so I p'd them all and found that, out of @controller, @request, and @response, only @response is nil. So I tried setting it to "cow". And indeed! My error changes: NoMethodError: undefined method `cookies' for "cow":String So it seems like I just need to stub out @response. How do I do that? Or am I way out of line here and overcomplicating things? A: Add this setup to all of your tests that exercise this method: @response.stubs(:cookies).returns({})
{ "language": "en", "url": "https://stackoverflow.com/questions/7575920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager I'm getting user reports from my app in the market, delivering the following exception: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1109) at android.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:399) at android.app.Activity.onBackPressed(Activity.java:2066) at android.app.Activity.onKeyUp(Activity.java:2044) at android.view.KeyEvent.dispatch(KeyEvent.java:2529) at android.app.Activity.dispatchKeyEvent(Activity.java:2274) at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1803) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1855) at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1277) at android.app.Activity.dispatchKeyEvent(Activity.java:2269) at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1803) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.widget.TabHost.dispatchKeyEvent(TabHost.java:297) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112) at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1855) at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1277) at android.app.Activity.dispatchKeyEvent(Activity.java:2269) at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1803) at android.view.ViewRoot.deliverKeyEventPostIme(ViewRoot.java:2880) at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2853) at android.view.ViewRoot.handleMessage(ViewRoot.java:2028) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:132) at android.app.ActivityThread.main(ActivityThread.java:4028) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:491) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602) at dalvik.system.NativeStart.main(Native Method) Apparently it has something to do with a FragmentManager, which I don't use. The stacktrace doesn't show any of my own classes, so I have no idea where this exception occurs and how to prevent it. For the record: I have a tabhost, and in each tab there is a ActivityGroup switching between Activities. A: Please check my answer here. Basically I just had to : @Override protected void onSaveInstanceState(Bundle outState) { //No call for super(). Bug on API Level > 11. } Don't make the call to super() on the saveInstanceState method. This was messing things up... This is a known bug in the support package. If you need to save the instance and add something to your outState Bundle you can use the following: @Override protected void onSaveInstanceState(Bundle outState) { outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE"); super.onSaveInstanceState(outState); } In the end the proper solution was (as seen in the comments) to use : transaction.commitAllowingStateLoss(); when adding or performing the FragmentTransaction that was causing the Exception. A: Check if the activity isFinishing() before showing the fragment and pay attention to commitAllowingStateLoss(). Example: if(!isFinishing()) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); DummyFragment dummyFragment = DummyFragment.newInstance(); ft.add(R.id.dummy_fragment_layout, dummyFragment); ft.commitAllowingStateLoss(); } A: Do not use commitAllowingStateLoss(), it should only be used for cases where it is okay for the UI state to change unexpectedly on the user. https://developer.android.com/reference/android/app/FragmentTransaction.html#commitAllowingStateLoss() If the transaction happens in ChildFragmentManager of parentFragment, use parentFragment.isResume() outside to check instead. if (parentFragment.isResume()) { DummyFragment dummyFragment = DummyFragment.newInstance(); transaction = childFragmentManager.BeginTransaction(); trans.Replace(Resource.Id.fragmentContainer, startFragment); } A: I had a similar problem, the scenario was like this: * *My Activity is adding/replacing list fragments. *Each list fragment has a reference to the activity, to notify the activity when a list item is clicked (observer pattern). *Each list fragment calls setRetainInstance(true); in its onCreate method. The onCreate method of the activity was like this: mMainFragment = (SelectionFragment) getSupportFragmentManager() .findFragmentByTag(MAIN_FRAGMENT_TAG); if (mMainFragment == null) { mMainFragment = new SelectionFragment(); mMainFragment.setListAdapter(new ArrayAdapter<String>(this, R.layout.item_main_menu, getResources().getStringArray( R.array.main_menu))); mMainFragment.setOnSelectionChangedListener(this); FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); transaction.add(R.id.content, mMainFragment, MAIN_FRAGMENT_TAG); transaction.commit(); } The exception was thrown because the when configuration changes (device rotated), the activity is created, the main fragment is retrieved from the history of the fragment manager and at the same time the fragment already has an OLD reference to the destroyed activity changing the implementation to this solved the problem: mMainFragment = (SelectionFragment) getSupportFragmentManager() .findFragmentByTag(MAIN_FRAGMENT_TAG); if (mMainFragment == null) { mMainFragment = new SelectionFragment(); mMainFragment.setListAdapter(new ArrayAdapter<String>(this, R.layout.item_main_menu, getResources().getStringArray( R.array.main_menu))); FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); transaction.add(R.id.content, mMainFragment, MAIN_FRAGMENT_TAG); transaction.commit(); } mMainFragment.setOnSelectionChangedListener(this); you need to set your listeners each time the activity is created to avoid the situation where the fragments have references to old destroyed instances of the activity. A: If you inherit from FragmentActivity, you must call the superclass in onActivityResult(): @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); ... } If you don't do this and try to show a fragment dialog box in that method, you may get OP's IllegalStateException. (To be honest, I don't quite understand why the super call fixes the problem. onActivityResult() is called before onResume(), so it should still not be allowed to show a fragment dialog box.) A: Fragment transactions should not be executed after Activity.onStop() ! Check that you do not have any callbacks that could execute transaction after onStop(). It is better to fix the reason instead of trying to walk around the problem with approaches like .commitAllowingStateLoss() A: Possibly the smoothest and the simplest solution I found in my case was to avoid popping the offending fragment off the stack in response to activity result. So changing this call in my onActivityResult(): popMyFragmentAndMoveOn(); to this: new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { popMyFragmentAndMoveOn(); } } helped in my case. A: It's October 2017, and Google makes Android Support Library with the new things call Lifecycle component. It provides some new idea for this 'Can not perform this action after onSaveInstanceState' problem. In short: * *Use lifecycle component to determine if it's correct time for popping up your fragment. Longer version with explain: * *why this problem come out? It's because you are trying to use FragmentManager from your activity(which is going to hold your fragment I suppose?) to commit a transaction for you fragment. Usually this would look like you are trying to do some transaction for an up coming fragment, meanwhile the host activity already call savedInstanceState method(user may happen to touch the home button so the activity calls onStop(), in my case it's the reason) Usually this problem shouldn't happen -- we always try to load fragment into activity at the very beginning, like the onCreate() method is a perfect place for this. But sometimes this do happen, especially when you can't decide what fragment you will load to that activity, or you are trying to load fragment from an AsyncTask block(or anything will take a little time). The time, before the fragment transaction really happens, but after the activity's onCreate() method, user can do anything. If user press the home button, which triggers the activity's onSavedInstanceState() method, there would be a can not perform this action crash. If anyone want to see deeper in this issue, I suggest them to take a look at this blog post. It looks deep inside the source code layer and explain a lot about it. Also, it gives the reason that you shouldn't use the commitAllowingStateLoss() method to workaround this crash(trust me it offers nothing good for your code) *How to fix this? * *Should I use commitAllowingStateLoss() method to load fragment? Nope you shouldn't; *Should I override onSaveInstanceState method, ignore super method inside it? Nope you shouldn't; *Should I use the magical isFinishing inside activity, to check if the host activity is at the right moment for fragment transaction? Yeah this looks like the right way to do. *Take a look at what Lifecycle component can do. Basically, Google makes some implementation inside the AppCompatActivity class(and several other base class you should use in your project), which makes it a easier to determine current lifecycle state. Take a look back to our problem: why would this problem happen? It's because we do something at the wrong timing. So we try not to do it, and this problem will be gone. I code a little for my own project, here is what I do using LifeCycle. I code in Kotlin. val hostActivity: AppCompatActivity? = null // the activity to host fragments. It's value should be properly initialized. fun dispatchFragment(frag: Fragment) { hostActivity?.let { if(it.lifecyclecurrentState.isAtLeast(Lifecycle.State.RESUMED)){ showFragment(frag) } } } private fun showFragment(frag: Fragment) { hostActivity?.let { Transaction.begin(it, R.id.frag_container) .show(frag) .commit() } As I show above. I will check the lifecycle state of the host activity. With Lifecycle component within support library, this could be more specific. The code lifecyclecurrentState.isAtLeast(Lifecycle.State.RESUMED) means, if current state is at least onResume, not later than it? Which makes sure my method won't be execute during some other life state(like onStop). * *Is it all done? Of course not. The code I have shown tells some new way to prevent application from crashing. But if it do go to the state of onStop, that line of code wont do things and thus show nothing on your screen. When users come back to the application, they will see an empty screen, that's the empty host activity showing no fragments at all. It's bad experience(yeah a little bit better than a crash). So here I wish there could be something nicer: app won't crash if it comes to life state later than onResume, the transaction method is life state aware; besides, the activity will try continue to finished that fragment transaction action, after the user come back to our app. I add something more to this method: class FragmentDispatcher(_host: FragmentActivity) : LifecycleObserver { private val hostActivity: FragmentActivity? = _host private val lifeCycle: Lifecycle? = _host.lifecycle private val profilePendingList = mutableListOf<BaseFragment>() @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun resume() { if (profilePendingList.isNotEmpty()) { showFragment(profilePendingList.last()) } } fun dispatcherFragment(frag: BaseFragment) { if (lifeCycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) == true) { showFragment(frag) } else { profilePendingList.clear() profilePendingList.add(frag) } } private fun showFragment(frag: BaseFragment) { hostActivity?.let { Transaction.begin(it, R.id.frag_container) .show(frag) .commit() } } } I maintain a list inside this dispatcher class, to store those fragment don't have chance to finish the transaction action. And when user come back from home screen and found there is still fragment waiting to be launched, it will go to the resume() method under the @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) annotation. Now I think it should be working like I expected. A: I was getting this exception when i was pressing back button to cancel intent chooser on my map fragment activity. I resolved this by replacing the code of onResume(where i was initializing the fragment) to onstart() and the app is working fine.Hope it helps. A: Courtesy: Solution for IllegalStateException This issue had annoyed me for a lot of time but fortunately I came with a concrete solution for it. A detailed explanation of it is here. Using commitAllowStateloss() might prevent this exception but would lead to UI irregularities.So far we have understood that IllegalStateException is encountered when we try to commit a fragment after the Activity state is lost- so we should just delay the transaction until the state is restored.It can be simply done like this Declare two private boolean variables public class MainActivity extends AppCompatActivity { //Boolean variable to mark if the transaction is safe private boolean isTransactionSafe; //Boolean variable to mark if there is any transaction pending private boolean isTransactionPending; Now in onPostResume() and onPause we set and unset our boolean variable isTransactionSafe. Idea is to mark trasnsaction safe only when the activity is in foreground so there is no chance of stateloss. /* onPostResume is called only when the activity's state is completely restored. In this we will set our boolean variable to true. Indicating that transaction is safe now */ public void onPostResume(){ super.onPostResume(); isTransactionSafe=true; } /* onPause is called just before the activity moves to background and also before onSaveInstanceState. In this we will mark the transaction as unsafe */ public void onPause(){ super.onPause(); isTransactionSafe=false; } private void commitFragment(){ if(isTransactionSafe) { MyFragment myFragment = new MyFragment(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.frame, myFragment); fragmentTransaction.commit(); } } -What we have done so far will save from IllegalStateException but our transactions will be lost if they are done after the activity moves to background, kind of like commitAllowStateloss(). To help with that we have isTransactionPending boolean variable public void onPostResume(){ super.onPostResume(); isTransactionSafe=true; /* Here after the activity is restored we check if there is any transaction pending from the last restoration */ if (isTransactionPending) { commitFragment(); } } private void commitFragment(){ if(isTransactionSafe) { MyFragment myFragment = new MyFragment(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.frame, myFragment); fragmentTransaction.commit(); isTransactionPending=false; }else { /* If any transaction is not done because the activity is in background. We set the isTransactionPending variable to true so that we can pick this up when we come back to foreground */ isTransactionPending=true; } } A: Here is a different solution to this problem. Using a private member variable you are able to set the returned data as an intent that can then be processed after super.onResume(); Like so: private Intent mOnActivityResultIntent = null; @Override protected void onResume() { super.onResume(); if(mOnActivityResultIntent != null){ ... do things ... mOnActivityResultIntent = null; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data){ if(data != null){ mOnActivityResultIntent = data; } } A: Short And working Solution : Follow Simple Steps Steps Step 1 : Override onSaveInstanceState state in respective fragment. And remove super method from it. @Override public void onSaveInstanceState( Bundle outState ) { } Step 2 : Use fragmentTransaction.commitAllowingStateLoss( ); instead of fragmentTransaction.commit( ); while fragment operations. A: I think using transaction.commitAllowingStateLoss(); is not best solution. This exception will be thrown when activity's configuration changed and fragment onSavedInstanceState() is called and thereafter your async callback method tries to commit fragment. Simple solution could be check whether activity is changing configuration or not e.g. check isChangingConfigurations() i.e. if(!isChangingConfigurations()) { //commit transaction. } Checkout this link as well A: The exception is threw here (In FragmentActivity): @Override public void onBackPressed() { if (!mFragments.getSupportFragmentManager().popBackStackImmediate()) { super.onBackPressed(); } } In FragmentManager.popBackStatckImmediate(),FragmentManager.checkStateLoss() is called firstly. That's the cause of IllegalStateException. See the implementation below: private void checkStateLoss() { if (mStateSaved) { // Boom! throw new IllegalStateException( "Can not perform this action after onSaveInstanceState"); } if (mNoTransactionsBecause != null) { throw new IllegalStateException( "Can not perform this action inside of " + mNoTransactionsBecause); } } I solve this problem simply by using a flag to mark Activity's current status. Here's my solution: public class MainActivity extends AppCompatActivity { /** * A flag that marks whether current Activity has saved its instance state */ private boolean mHasSaveInstanceState; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onSaveInstanceState(Bundle outState) { mHasSaveInstanceState = true; super.onSaveInstanceState(outState); } @Override protected void onResume() { super.onResume(); mHasSaveInstanceState = false; } @Override public void onBackPressed() { if (!mHasSaveInstanceState) { // avoid FragmentManager.checkStateLoss()'s throwing IllegalStateException super.onBackPressed(); } } } A: Whenever you are trying to load a fragment in your activity make sure that activity is in resume and not going to pause state.In pause state you may end up losing commit operation that is done. You can use transaction.commitAllowingStateLoss() instead of transaction.commit() to load fragment or Create a boolean and check if activity is not going to onpause @Override public void onResume() { super.onResume(); mIsResumed = true; } @Override public void onPause() { mIsResumed = false; super.onPause(); } then while loading fragment check if(mIsResumed){ //load the your fragment } A: If you are doing some FragmentTransaction in onActivityResult what you can do you can set some boolean value inside onActivityResult then in onResume you can do your FragmentTransaction on the basis of the boolean value. Please refer the code below. @Override protected void onResume() { super.onResume; if(isSwitchFragment){ isSwitchFragment=false; bottomNavigationView.getTabAt(POS_FEED).select(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == FilterActivity.FILTER_REQUEST_EVENT && data != null) { isSwitchFragment=true; } } A: In regards to @Anthonyeef great answer, here is a sample code in Java: private boolean shouldShowFragmentInOnResume; private void someMethodThatShowsTheFragment() { if (this.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) { showFragment(); } else { shouldShowFragmentInOnResume = true; } } private void showFragment() { //Your code here } @Override protected void onResume() { super.onResume(); if (shouldShowFragmentInOnResume) { shouldShowFragmentInOnResume = false; showFragment(); } } A: If you have crash with popBackStack() or popBackStackImmediate() method please try fixt with: if (!fragmentManager.isStateSaved()) { fragmentManager.popBackStackImmediate(); } This is worked for me as well. A: In my case I got this error in an override method called onActivityResult. After digging I just figure out maybe I needed to call 'super' before. I added it and it just worked override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data); //<--- THIS IS THE SUPPER CALL if (resultCode == Activity.RESULT_OK && requestCode == 0) { mostrarFragment(FiltroFragment.newInstance()) } } Maybe you just need to add a 'super' on any override you are doing before your code. A: Kotlin extension fun FragmentManager?.replaceAndAddToBackStack( @IdRes containerViewId: Int, fragment: () -> Fragment, tag: String ) { // Find and synchronously remove a fragment with the same tag. // The second transaction must start after the first has finished. this?.findFragmentByTag(tag)?.let { beginTransaction().remove(it).commitNow() } // Add a fragment. this?.beginTransaction()?.run { replace(containerViewId, fragment, tag) // The next line will add the fragment to a back stack. // Remove if not needed. // You can use null instead of tag, but tag is needed for popBackStack(), // see https://stackoverflow.com/a/59158254/2914140 addToBackStack(tag) }?.commitAllowingStateLoss() } Usage: val fragment = { SomeFragment.newInstance(data) } fragmentManager?.replaceAndAddToBackStack(R.id.container, fragment, SomeFragment.TAG) A: There are many related problems with a similar error message. Check the second line of this particular stack trace. This exception is specifically related to the call to FragmentManagerImpl.popBackStackImmediate. This method call, like popBackStack, will always fail with IllegalStateException if the session state has already been saved. Check the source. There is nothing you can do to stop this exception being thrown. * *Removing the call to super.onSaveInstanceState will not help. *Creating the Fragment with commitAllowingStateLoss will not help. Here's how I observed the problem: * *There's a form with a submit button. *When the button is clicked a dialog is created and an async process starts. *The user clicks the home key before the process is finished - onSaveInstanceState is called. *The process completes, a callback is made and popBackStackImmediate is attempted. *IllegalStateException is thrown. Here's what I did to solve it: As it is not possible to avoid the IllegalStateException in the callback, catch & ignore it. try { activity.getSupportFragmentManager().popBackStackImmediate(name); } catch (IllegalStateException ignored) { // There's no way to avoid getting this if saveInstanceState has already been called. } This is enough to stop the app from crashing. But now the user will restore the app and see that the button they thought they'd pressed hasn't been pressed at all (they think). The form fragment is still showing! To fix this, when the dialog is created, make some state to indicate the process has started. progressDialog.show(fragmentManager, TAG); submitPressed = true; And save this state in the bundle. @Override public void onSaveInstanceState(Bundle outState) { ... outState.putBoolean(SUBMIT_PRESSED, submitPressed); } Don't forget to load it back again in onViewCreated Then, when resuming, rollback the fragments if submit was previously attempted. This prevents the user from coming back to what seems like an un-submitted form. @Override public void onResume() { super.onResume(); if (submitPressed) { // no need to try-catch this, because we are not in a callback activity.getSupportFragmentManager().popBackStackImmediate(name); submitPressed = false; } } A: BEWARE, using transaction.commitAllowingStateLoss() could result in a bad experience for the user. For more information on why this exception is thrown, see this post. A: I found a dirty solution for this kind of problem. If you still want to keep your ActivityGroups for whatever reason (I had time limitation reasons), you just implement public void onBackPressed() {} in your Activity and do some back code in there. even if there is no such Method on older Devices, this Method gets called by newer ones. A: Starting from support library version 24.0.0 you can call FragmentTransaction.commitNow() method which commits this transaction synchronously instead of calling commit() followed by executePendingTransactions(). As documentation says this approach even better: Calling commitNow is preferable to calling commit() followed by executePendingTransactions() as the latter will have the side effect of attempting to commit all currently pending transactions whether that is the desired behavior or not. A: I know there is an accepted answer by @Ovidiu Latcu but after some while, error still persist. @Override protected void onSaveInstanceState(Bundle outState) { //No call for super(). Bug on API Level > 11. } Crashlytics still sending me this weird error message. However error now occurring only on version 7+ (Nougat) My fix was to use commitAllowingStateLoss() instead of commit() at the fragmentTransaction. This post is helpful for commitAllowingStateLoss() and never had a fragment issue ever again. To sum it up, the accepted answer here might work on pre Nougat android versions. This might save someone a few hours of searching. happy codings. <3 cheers A: To bypass this issue, we can use The Navigation Architecture Component , which was introduced in Google I/O 2018. The Navigation Architecture Component simplifies the implementation of navigation in an Android app. A: change getFragmentManager() to getChildFragmentManager(). Don't use parent FragmentManager, try to use self. A: as you can see in your crash report, the last line that is throwing the exception is checkStateLoss(FragmentManager.java:1109) if you look at the implementation of checkStateLoss private void checkStateLoss() { if (isStateSaved()) { throw new IllegalStateException( "Can not perform this action after onSaveInstanceState"); } } so a simple solution for me is to find what ever method of the Fragment Manager you are calling in your app that eventually leads to this method being called and simply check if isStateSaved() is false before calling that method. For me it was the show() method. I did like this if (!isStateSaved()) { myDialog.show(fragmentManager, Tag) } A: Add this in your activity @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (outState.isEmpty()) { // Work-around for a pre-Android 4.2 bug outState.putBoolean("bug:fix", true); } } A: I have also experienced this issue and problem occurs every time when context of your FragmentActivity gets changed (e.g. Screen orientation is changed, etc.). So the best fix for it is to update context from your FragmentActivity. A: I ended up with creating a base fragment and make all fragments in my app extend it public class BaseFragment extends Fragment { private boolean mStateSaved; @CallSuper @Override public void onSaveInstanceState(Bundle outState) { mStateSaved = true; super.onSaveInstanceState(outState); } /** * Version of {@link #show(FragmentManager, String)} that no-ops when an IllegalStateException * would otherwise occur. */ public void showAllowingStateLoss(FragmentManager manager, String tag) { // API 26 added this convenient method if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (manager.isStateSaved()) { return; } } if (mStateSaved) { return; } show(manager, tag); } } Then when I try to show a fragment I use showAllowingStateLoss instead of show like this: MyFragment.newInstance() .showAllowingStateLoss(getFragmentManager(), MY_FRAGMENT.TAG); I came up to this solution from this PR: https://github.com/googlesamples/easypermissions/pull/170/files A: Another possible workaround, which I'm not sure if helps in all cases (origin here) : @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { final View rootView = findViewById(android.R.id.content); if (rootView != null) { rootView.cancelPendingInputEvents(); } } } A: I had the exact same problem. It happened because of the destruction of previous activity. when ı backed the previous activity it was destroyed. I put it base activity (WRONG) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SpinnerCustom2.setFragmentManager(getSupportFragmentManager()); onCreateDrawerActivity(savedInstanceState); } I put it into onStart it was RIGHT @Override protected void onStart() { super.onStart(); SpinnerCustom2.setFragmentManager(getSupportFragmentManager()); } A: @Gian Gomen In my case call SUPER solves problem. It seems like more correct solution then commitAllowingStateLoss(), because it solves problem, not hide it. @Override public void onRequestPermissionsResult( final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults ) { super.onRequestPermissionsResult(requestCode,permissions, grantResults); //<--- Without this line crash switch (requestCode) { case Constants.REQUEST_CODE_PERMISSION_STORAGE: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { onPermissionGranted(Constants.REQUEST_CODE_PERMISSION_STORAGE); } break; } A: use remove() instead of popup() if state saved. private void removeFragment() { FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.isStateSaved()) { List<Fragment> fragments = fragmentManager.getFragments(); if (fragments != null && !fragments.isEmpty()) { fragmentManager.beginTransaction().remove(fragments.get(fragments.size() - 1)).commitAllowingStateLoss(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7575921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "560" }
Q: Is it possible to specialize a template definition based on the existence of a nested typedef of a template type parameter? I have a template, template <typename T> class wrapper, that I would like to specialize based on the existence of typename T::context_type. If typename T::context_type is declared, then the constructors and assignment operator overloads of the wrapper<T> instantiation should accept a mandatory typename T::context_type parameter. Additionally, wrapper<T> objects would store "context" in the member data. If typename T::context_type does not exist, then the constructors and assignment operator overloads of wrapper<T> would take one less parameter and there would be no additional data member. Is this possible? Can I get the following code to compile without changing the definitions of config1, config2, and main()? #include <iostream> template <typename T, bool context_type_defined = true> class wrapper { public: typedef typename T::context_type context_type; private: context_type ctx; public: wrapper(context_type ctx_) : ctx(ctx_) { std::cout << "T::context_type exists." << std::endl; } }; template <typename T> class wrapper<T, false> { public: wrapper() { std::cout << "T::context_type does not exist." << std::endl; } }; class config1 { public: typedef int context_type; }; class config2 { public: }; int main() { wrapper<config1> w1(0); wrapper<config2> w2; } A: Yes, it is possible. I have implemented such behavior in the past by using some metaprogramming tricks. The basic build blocks are: BOOST_MPL_HAS_XXX_TRAIT_DEF, to define a metafunction predicate that will evaluate to a true type if the argument is of class type and has a nested type with a given name (context_type in your case). http://www.boost.org/doc/libs/1_47_0/libs/mpl/doc/refmanual/has-xxx-trait-def.html Boost.EnableIf, to define the specializations based on the previously defined trait. http://www.boost.org/libs/utility/enable_if.html # See 3.1 Enabling template class specializations Note that you may be able to get that behavior working directly with SFINAE, something like this may work: template< typename T, typename Context = void > class wrapper { ... }; // Base definition template< typename T > class wrapper< T, typename voif_mfn< typename T::context_type >::type > { ... }; // Specialization However, I like the expressiveness of the solution based on traits and enable if. A: That's possible, and there are many ways to implement this. All of them should go back on some trait class has_type so that has_type<T>::value is true if the member typedef exists, and false otherwise. Let's assume we have this trait class already. Then here's one solution, using C++11 template aliases: template <typename T, bool> class FooImpl { // implement general case }; template <typename T> class FooImpl<T, true> { // implement specific case }; template <typename T> using Foo = FooImpl<T, has_type<T>::value>; // C++11 only Now to make the typetrait: template<typename T> struct has_type { private: typedef char yes; typedef struct { char array[2]; } no; template<typename C> static yes test(typename C::context_type*); template<typename C> static no test(...); public: static const bool value = sizeof(test<T>(0)) == sizeof(yes); }; If you don't have C++11, or if you don't want to rewrite the entire class, you can make the distinction more fine-grained, e.g. by using std::enable_if, std::conditional, etc. Post a comment if you want some specific examples. A: Using @K-ballo's answer, I wrote the following: namespace detail { BOOST_MPL_HAS_XXX_TRAIT_DEF(context_type) } template <typename T, typename Enable = void> class wrapper { public: wrapper() { std::cout << "T::context_type does not exist." << std::endl; } }; template <typename T> class wrapper<T, typename boost::enable_if<detail::has_context_type<T> >::type> { public: typedef typename T::context_type context_type; private: context_type ctx; public: wrapper(context_type ctx_) : ctx(ctx_) { std::cout << "T::context_type exists." << std::endl; } }; Now, the sample code compiles and outputs: T::context_type exists. T::context_type does not exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Reproduce a part of a music clip (cocoa) I'm newbie working with music clips and Cocoa. I have a music clip long 10s and i want to reproduce only the first 4s. How can I do this thing ? If i want to reproduce an interval between start and end for example between second 4 and second 7. How can I do that ? Thanks in advance. A: You could do this with QTKit with a QTMovie object. QTMovie gives you all kinds of ways of editing, working with the audio tracks, selecting time ranges, etc. Spend some time looking over the linked doc and post specific questions if you get stuck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Parsing generic tags in C# I need to parse text that uses various custom tags within it, for instance: <tag>example</tag> Everything I see on here dealing with parsing tagged stuff has some premade format (like HTML) so has a library dedicated explicitly to it. Does C# have anything that can deal with custom tags like this? Or is the ol' "iterate through the characters and do it yourself" the best I can hope for? edit: These tags do appear randomly in otherwise normal text, I only need to locate them or extract what is contained in them Ugh, I can't comment! I've deactivated my addons (using latest firefox), but it is no avail. Clicking comment does nothing, only edit works. Damn, this is frustrating. I can't even view the newer comments that are coming in past the first 5! A: You can try using the HTML Agility Pack - it is an HTML parser that deals with badly formed HTML, but you should be able to use it to query custom elements as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pdf viewer in eclipse widget I need to embed in an eclipse widget a simple pdf viewer,nothing fancy, just to see the content of the pdf. Where do i start ? thank you A: Have you had a look at http://www.jpedal.org/support_siEclipse.php ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7575939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EOF Error in Imaplib I am programming a python applet that watches the unread count of the email boxes for my workplace, and ran into an EOF error when I try to use any imaplib methods after the applet sits idle for about 10 minutes. Everything works fine until the applet has been alive for more than 10 minutes. Here is the relevant code for the imaplib object. conn = imaplib.IMAP4_SSL("imap.gmail.com", 993) def loginIMAP (imapObj): # Login to Helpdesk Google Apps Email account using encryption imapObj.login(base64.b64decode("usrEncryption"), base64.b64decode("pwdEncrytion")) return(getUnread(imapObj)) def closeIMAP (imapObj): imapObj.logout() def getUnread (imapObj): # Check connection status OK try: uc0 = int(re.search("UNSEEN (\d+)", imapObj.status("INBOX", "(UNSEEN)")[1][0]).group(1)) uc1 = int(re.search("UNSEEN (\d+)", imapObj.status("A box 1", "(UNSEEN)")[1][0]).group(1)) uc2 = int(re.search("UNSEEN (\d+)", imapObj.status("A box 2", "(UNSEEN)")[1][0]).group(1)) except: print "Shit's all disconnected n stuff" loginIMAP(conn) unreadCount = [(uc0-(uc1+uc2)),uc1,uc2] if unreadCount[0] < 0: unreadCount[0]=0 return unreadCount usrEncryption and pwdEncryption are just me masking the u/p so our helpdesk logins aren't all public. When I try and call the getUnread(conn) after having the applet open for more than ten minues I get the following output: Traceback (most recent call last): File "C:\Jamin'sApps\Development\Projects\Check HD Box\checkHDBox.py", line 255, in OnRefresh unread = getUnread(conn) File "C:\Jamin'sApps\Development\Projects\Check HD Box\checkHDBox.py", line 119, in getUnread uc0 = int(re.search("UNSEEN (\d+)", imapObj.status("INBOX", "(UNSEEN)")[1][0]).group(1)) File "C:\Jamin'sApps\Development\Python\python2.7.2\lib\imaplib.py", line 710, in status typ, dat = self._simple_command(name, mailbox, names) File "C:\Jamin'sApps\Development\Python\python2.7.2\lib\imaplib.py", line 1070, in _simple_command return self._command_complete(name, self._command(name, *args)) File "C:\Jamin'sApps\Development\Python\python2.7.2\lib\imaplib.py", line 899, in _command_complete raise self.abort('command: %s => %s' % (name, val)) imaplib.abort: command: STATUS => socket error: EOF Traceback (most recent call last): File "C:\Jamin'sApps\Development\Projects\Check HD Box\checkHDBox.py", line 255, in OnRefresh unread = getUnread(conn) File "C:\Jamin'sApps\Development\Projects\Check HD Box\checkHDBox.py", line 119, in getUnread uc0 = int(re.search("UNSEEN (\d+)", imapObj.status("INBOX", "(UNSEEN)")[1][0]).group(1)) File "C:\Jamin'sApps\Development\Python\python2.7.2\lib\imaplib.py", line 710, in status typ, dat = self._simple_command(name, mailbox, names) File "C:\Jamin'sApps\Development\Python\python2.7.2\lib\imaplib.py", line 1070, in _simple_command return self._command_complete(name, self._command(name, *args)) File "C:\Jamin'sApps\Development\Python\python2.7.2\lib\imaplib.py", line 859, in _command raise self.abort('socket error: %s' % val) imaplib.abort: socket error: [Errno 10053] An established connection was aborted by the software in your host machine The exception block doesnt really seem to work for the problem, which is what I really need help with. So how do I keep this connection alive and kicking? Thanks. A: I managed to integrate cxase's into a custom imap class that took care of all my problems. Here is the code for anyone reading this: class IMAPConnection(): def __init__(self): self.imap = imaplib.IMAP4_SSL("imap.gmail.com", 993) def login (self): # Login to Helpdesk Google Apps Email account using encryption self.imap.login(base64.b64decode("username"), base64.b64decode("password")) def logout (self): self.imap.logout() def getUnread (self): # Check connection status OK try: uc0 = int(re.search("UNSEEN (\d+)", self.imap.status("INBOX", "(UNSEEN)")[1][0]).group(1)) uc1 = int(re.search("UNSEEN (\d+)", self.imap.status("A box 1", "(UNSEEN)")[1][0]).group(1)) uc2 = int(re.search("UNSEEN (\d+)", self.imap.status("A box 2", "(UNSEEN)")[1][0]).group(1)) except imap.abort: # Reinstantiate connection and login self.imap = imaplib.IMAP4_SSL("imap.gmail.com", 993) self.login() # Retry unread update block uc0 = int(re.search("UNSEEN (\d+)", self.imap.status("INBOX", "(UNSEEN)")[1][0]).group(1)) uc1 = int(re.search("UNSEEN (\d+)", self.imap.status("A box 1", "(UNSEEN)")[1][0]).group(1)) uc2 = int(re.search("UNSEEN (\d+)", self.imap.status("A box 2", "(UNSEEN)")[1][0]).group(1)) # Is the Helpdesk Negative? Hell no it's not. unreadCount = [(uc0-(uc1+uc2)),uc1,uc2] if unreadCount[0] < 0: unreadCount[0]=0 return unreadCount A: You need to reconnect by re-initialize class, not just login, using conn = imaplib.IMAP4_SSL("imap.gmail.com", 993) A complete example: while True: imap = imaplib.IMAP4_SSL(SERVER) r, d = imap.login(ACCOUNT, PASSWORD) assert r == 'OK', 'login failed' try: # do things with imap except imap.abort, e: continue imap.logout() break
{ "language": "en", "url": "https://stackoverflow.com/questions/7575943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Post photo to someone else's wall or album from mobile device Here's the functionality I want. I want users of my mobile apps (iOS, Android) to be able to post photos from their device to a facebook page of someone else. This facebook page is not owned by the user of my app, nor is the user a friend or fan. Also, the facebook page may be a standard page, or an event page or a fan page, depending on the client. Any solution will work. For example, it may be that I will have to make the app upload all photos to a server owned by me, then from that central server I could use the facebook api to post the photo to a client's facebook page. I could make a sort of go between facebook account and that account could be friends with the client's facebook or be a page admin, etc. Or maybe the client will provide me with their facebook credentials and I could post it as them. Ideally I want to do this all from the app and not have a go between, but whatever works. How can I make this happen? I'm just going to go ahead and say this is not possible. It would be very cool, but not possible. Here's the functionality I wanted. A user goes to a big music festival. The festival has its own app that I developed. Inside the festival's app the user can take a pic and press a button and the pic would be uploaded to the festival's facebook page, not the user's. So the festival's facebook page would get fan photos posted to it straight from the user. The only way I see this as working is by having the app upload all pics to a sort of go between server then have that server post the pic to the festival's facebook page by using the festival's login credentials. This would require the festival to give me, the developer, their login credentials, which they may be reluctant to do. If anyone knows how I can do this straight from the app please let me know. A: Myself am busy with the same thing. Did research for two full days and did not find the answer for our problem. But i think i have an explanation for it. if a user posts a photo to friend/fan_page with the official android FB app it uses a "feed" with a picture(url-link). The user can't see on his own wall that he actually shared or posted a picture on the friend/fan_page. (for example: "Bob - posted a photo on CocaCola") This is probably the reason why the function is disabled because developers could use this to send photo's to all kinds of pages/people without the user knowing be aware of it. I came to this hypotheses because i found a sort of work around. Upload photo to users own album. get the URL of that photo and then post a "feed" with a picture(url-lnk). Facebook then gave this error: "FBCDN image is not allowed in stream" in other words, you can't use photos that are on FB website domain to link to. So think there is quite a bug/lazyness in the facebook developement departmet :P
{ "language": "en", "url": "https://stackoverflow.com/questions/7575944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best method to call c# code from within Excel or Excel VBA Can anyone tell me the best method for calling c# from within Excel. I saw a post somewhere that said the later .NET had good ways to do this - but nothing was specified. A: Not sure if @amit_g's link is what you mean, but the post may also have said that for Excel 2007 and up you can create an add-in in Visual Studio.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Serving AppEngine static files What is the best way to serve static image and javascript files using appengine? From what I can see there are two methods applicable, having the files stored in the war directory of the service you are uploading, at design time. The alternative being using the blobstore, with the files being uploaded after the service has. I see there is a 150mb restriction on the resource files in the war directory (with a 10mb limit per file), but from what I can see this is simpler, 'free' space. Is it slower than the blobstore? The dynamic nature of the blobstore is of little interest to me, so the directory seems the better option. Can anyone offer any advice? Are my conclusions correct? A: It's fine to put javascript and images files in your resources file directory on appengine. In my experience, blobstore and resource files have similar performance characteristics. However, as site speed becomes more important it may make more sense to use a CDN to get the static files to your users more quickly. If the static javascript is something common like jquery or jquery-ui I would recommend using google libraries API right off the bat: http://code.google.com/apis/libraries/devguide.html A: The ideal way to serve static files (image, javascript, css) is to declare them using <static-files> in appengine-web.xml. The opening paragraph of http://code.google.com/appengine/docs/java/config/appconfig.html#Static_Files_and_Resource_Files lays it out nicely: Many web applications have files that are served directly to the user's browser, such as images, CSS style sheets, or browser JavaScript code. These are known as static files because they do not change, and can benefit from web servers dedicated just to static content. App Engine serves static files from dedicated servers and caches that are separate from the application servers. A: If it is just a normal website, which hosts some images and javascript files, generally it should follow the standard way to put them into the war directory. I cannot see much benefit to put those files into blobstore as you have said no interest to the dynamic nature. Not to mention the another level of complexity you added using blobstore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Azure and F# 3.0 Type Providers Do F# 3.0 Type Providers work with SQL Azure? I'm getting an error while trying. Wondering if there are any known issues with this. A: Nevermind I fixed it. I needed to use EntityTypeProvider instead of SqlServerProvider.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: flex4 with php, error referencing function I'm trying to connect to MySql database in flex4. I wrote a php class like this, public function getNames() { $stmt = mysqli_prepare($this->connection, "SELECT names.firstname, names.middlename, names.lastname FROM names"); $this->throwExceptionOnError(); mysqli_stmt_execute($stmt); $this->throwExceptionOnError(); $rows = array(); mysqli_stmt_bind_result($stmt, $row->firstname, $row->middlename, $row->lastname); while (mysqli_stmt_fetch($stmt)) { $rows[] = $row; $row = new stdClass(); mysqli_stmt_bind_result($stmt, $row->firstname, $row->middlename, $row->lastname); } mysqli_stmt_free_result($stmt); mysqli_close($this->connection); return $rows; } I just dragged and droped a datagrid into flex design mode. Then using data-> connect to php option, i selected file name.php from webroot. Then flex4 is giving this error, I have no clue about it, since it generated various services. What is the flex expecting now? protected function dataGrid_creationCompleteHandler(event:FlexEvent):void { getNamesResult.token = name.getNames(); } Description Resource Path Location Type 1061: Call to a possibly undefined method getNames through a reference with static type String. flexphp.mxml /flexphp/src line 12 Flex Problem A: You can't call a function directly in PHP without having some kind of layer that can communicate with Flex since PHP functions aren't publicly available. You should look into AMFPHP or ZendPHP which provides this communication layer (amf remoting).
{ "language": "en", "url": "https://stackoverflow.com/questions/7575964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I prevent Apache CXF from sending a response message? In cases where a given SOAP header element has a given value (for example, if the value of the header tag "response" is "0"), I don't want Apache CXF to return a response at all. How can I do this? It appears that CXF makes the assumption that all calls will receive a response. (I know this seems strange in a web services context, but if your transport is JMS, it seems less strange). A: I've been able to do this with an interceptor that aborts the interceptor chain. I've tested this with an HTTP config (WebSphere returns an empty 200) and an ActiveMQ config (no response comes back to the response queue). package my.super.interceptor; public final class Suppressor extends AbstractSoapInterceptor { public Suppressor() { super(Phase.SETUP); } @Override public void handleMessage(final SoapMessage message) throws Fault { final boolean suppressResponse = this.suppressResponse(message); if(suppressResponse) { log.debug("-> Suppressing response"); message.getInterceptorChain().abort(); } //if you want to suppress both responses and faults, you need //to check them separately. //Change this code to check headers for whatever criteria you want //(Note you may need to change the super(Phase...) ) //The code's a bit messy here - just sketching out the idea for the answer private boolean suppressResponse(final Message message) { final Fault fault = (Fault)message.getContent(Exception.class); if(fault != null) { final String faultMessage = fault.getMessage(); return faultMessage.indexOf("Something-you-want-to-match") > 0; } else { final MessageInfo messageInfo = (MessageInfo)message.get("org.apache.cxf.service.model.MessageInfo"); final String operation = messageInfo.getOperation().getOutputName(); return operation.indexOf("Something-you-want-to-match") > 0; } } and your applicationContext.xml: <jaxws:endpoint ...> <jaxws:outInterceptors> <bean class="my.super.interceptor.Suppressor"/> </jaxws:outInterceptors> <jaxws:outFaultInterceptors> <bean class="my.super.interceptor.Suppressor"/> </jaxws:outFaultInterceptors> </jaxws:endpoint> A: Long explanation: think about SOAP web services in terms of SOAP protocol specification. Web services is not just a fancy layer on top of HTTP, it is actually a way to describe two-way communication with various message exchange patterns implemented. The following patterns are most common ones: * *request-response (In-Out): in HTTP environment this is a typical HTTP request/response call with some request message being sent from client to server and some response message is sent back. In JMS environment you would get two separate and independent messages. *one-way (In-Only): in this model the client send a request but does not expect nor care about the response. In JMS it is equivalent to a simple message sent to the broker. In HTTP on the other hand (at least this is how one-way methods are implemented in Apache CXF) you will get a void method on SEI. Moreover, CXF by default will use a separate thread pool to handle this request, so the client doesn't even wait for the response and the server is not even able to send that response (because the client might have already disconnected). Now the important part: in WSDL you either define a method as request/response (by defining in/out messages) or as one-way (by only providing in message). This is fixed in service contract. You cannot make a method that once returns response (out message to be precise) while other times it does not. Obviously you can define an out message that can be empty or contain some content, but you still have to return something. Short explanation: SOAP protocol is not flexible enough to fulfil your requirement. You either return a response or not. Create two methods and choose which one to call on the client side rather than adding custom headers. Another tip: you might use ESB to perform some sort of transformation so that the response is discarded in presence of some SOAP header. A: @Jared: I am mostly agreed with Tomasz's explanation. One workaround I can think of lets say if use ws-addressing. Ws-addressing allows you to specify <ReplyTo> and <To>. So basically, in scenario you don't want response to be sent to client who has requested, server side code can alter the value of replyTo field and can send response to dummy URI. A: For your particular scenario I think the correct way to implement is to use two operations. One for in-only and other for in-out. The way you try to implement it may cause problems in client side as well. now client has to decide whether to look for a response or not depending on the request. On the other hand since the decision is taken from a value send by the client at the client side it can decide to invoke the in-only or in-out operation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I access the Advanced Security Options Tab from .net? I have a problem with regarding Active Directory programming.I need to access the Security Tab to assign “Permissions for SELF” with .net.How can I do that? A: This is fairly easy to do with the ActiveDirectorySecurity class - http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectorysecurity.aspx.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: edit background layer in png I have an image here a guy http://andybriggs.com/img/streetguy.png. I'm not good at image editing so I don't know if I'm explaining this right. The image is a rectangle and is one layer when opened in gimp. I want to change the white background to gray so it will match the background color on my website. Does that make sense? A: Never mind I figured it out on GIMP: From the toolbar: Layer >> New from Visible; This gives you the foreground layer (the guy) and another layer with the white background. Then click the second layer, the background, and go to the paint bucket and click it on the image. Then go to the Layers, Channels window and in the layers pane click the eye image on the first layer to make it invisible. Then go to Image >> Flatten Image and it's done
{ "language": "en", "url": "https://stackoverflow.com/questions/7575983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php session variables problem in Firefox I set several php session variables in an initial php file. In all other ajax loaded php files the value of those session variables is updated only after refreshing the page. This happens only in Firefox. Does anyone know what may cause this to happen? In IE everything works fine. A: I found a solution. There was a cache issue. Write: header("Cache-Control: no-cache"); header("Pragma: no-cache"); after session_start(); in all your conventional scripts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Associate file extension to Android app and handle the file In my android app I want to associate my app with *.bin extension. Whenever a user click on a *.bin file, I want my app to be started and make a conversion. This link shows associating process, but when the app is onCreate, how can I get the file, its path, etc? I couldn't find how to do that. Thanks in advance. A: when the app is onCreate, how can I get the file, its path, etc? Call getIntent().getData() in your Activity to retrieve the Uri that represents the file or URL that you are to open. A: Your path will be the URI passed from intent: Intent intent = getIntent(); String path = intent.getDataString();
{ "language": "en", "url": "https://stackoverflow.com/questions/7575986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Searching for app takes me to 4oh4 page I have a simular problem as in this post. When I search for iStatus+ and clicking on the app in the search results, I am redirected to http://www.facebook.com/4oh4.php. Sandbox mode is disabled. Here's a screenshot. A: Plug a URL into the Bookmark URL field: This is a bug logged with Facebook and that is the known workaround.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use PHP to upgrade an existing PHP script? I've currently developed an addon for a popular billing system which i plan to give out to many other people, I would like to make it very easy for them to upgrade the addon whenever i create any bug fixes or updates. The script uses PHP and MySQL db, i know how to update the MySQL but i'm looking for someone to point me in the right direction on how i could create a PHP script or code that would download the update file or tarball from my website and then upgrade/replace the current file with the new one, that's it. My concern is just with customers who may be using it on a shared hosting environment or something where they may have problems with upgrades. I was thinking something sorta along the lines of how Wordpress upgrades itself, i thought about the FTP option but i don't want to make the customers have to enter FTP credentials. A: Why don't you just use PHP's ftp functions to compare the files with ftp_mdtm() and download it on difference from your FTP - the customers FTP data won't be used as you just write locally from a local upgrade script with ftp_get(). Maybe unlink() the old file before you download to avoid overwriting problems. Downside is just you need to open your FTP Server for the customers, but the login-data could be in your own scripts - maybe create a custom user that only has access to the update-files. Can't think of any other way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7575989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Speed up this JOIN, MySQL This is similar to another question I posted, but I was told to split them. I have a InnoDB MYSQL table that stores a multi select name ( or 'code' as the table calls it), a parent object's id (parent_id) and the name of the option selected in the multi select (name_id): CREATE TABLE IF NOT EXISTS `v2_CA_venue_option_map` ( `map_id` int(11) NOT NULL auto_increment, `code` varchar(30) NOT NULL, `parent_id` int(11) NOT NULL, `name_id` int(11) NOT NULL, PRIMARY KEY (`map_id`), UNIQUE KEY `3way_unique` (`code`,`parent_id`,`name_id`), KEY `name_id` (`name_id`), KEY `filter` (`code`,`name_id`), KEY `parent_id` (`parent_id`), KEY `code` (`code`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=875156 ; and a simple table to store the names (i figured i would show this because its used in the query): CREATE TABLE IF NOT EXISTS `v2_CA_venue_option_name` ( `name_id` int(11) NOT NULL auto_increment, `name` varchar(255) NOT NULL, PRIMARY KEY (`name_id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Venue Option Names' AUTO_INCREMENT=60 ; CREATE TABLE IF NOT EXISTS `v2_CA_venues` ( `venue_id` int(11) NOT NULL auto_increment, `status` char(1) NOT NULL, `name` varchar(255) NOT NULL, `url_key` varchar(255) NOT NULL, `city` varchar(255) NOT NULL, PRIMARY KEY (`venue_id`), KEY `city` (`city`,`status`), ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ; That I would like to optimize for the following query: SELECT v.name, v.venue_id, v.url_key FROM `v2_CA_venue_option_map` map JOIN `v2_CA_venue_option_map` map2 ON (map2.parent_id = map.parent_id) JOIN `v2_CA_venue_option_map` map3 ON (map3.parent_id = map.parent_id) JOIN `v2_CA_venues` v ON (v.venue_id = map.parent_id) WHERE v.city = 'Nevada City' AND map3.code = 'a_venue_types' AND map3.name_id = 19 AND map.code = 'a_event_types' AND map.name_id = 20 AND map2.code = 'a_event_types' AND map2.name_id = 3 AND v.status = 'a' * *Are the indexes placed on the table offering the best performance for these Joins and WHEREs? *Are any of the indexes useless? The EXPLAIN for the above query: Thank you so much! I am looking for advice on the way to get the best performace out of these tables. A: FOR your v2_CA_venues table, I see you have an index ON( City, Status ). Use this as the FIRST IN your query. Your maps table could have 1000's of entries, but how many for a single "City + Status"... much less. So now that at the top of your query will help optimize the rest. Using the keyword "STRAIGHT_JOIN" tells optimizer to do it in the order you've stated. What you have of an index of 3way_unique index, I would change (or add another index) with the smallest element as first position in the index... I would actually change the order to ( parent_id, name_id, code ). You could have 100 codes, but 1000's of parent_ids. But now, you are looking for a specific parent ID that could have multiple codes... So now, your index would be down to just ex: the ONE Parent_ID and it may have 8 codes and you are looking for 3. You've just reduced your comparison set for the join. SELECT STRAIGHT_JOIN v.name, v.venue_id, v.url_key FROM v2_CA_venues v join v2_CA_venue_option_map map ON v.venue_id = map.parent_id AND map.name_id = 20 and map.code = 'a_event_types' join v2_CA_venue_option_map map2 ON v.venue_id = map2.parent_id AND map2.name_id = 3 and map2.code = 'a_event_types' join v2_CA_venue_option_map map3 ON v.venue_id = map3.parent_id AND map3.name_id = 19 and map3.code = 'a_venue_types' where v.City = 'Nevada City' and v.status = 'a'
{ "language": "en", "url": "https://stackoverflow.com/questions/7575991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Trouble with MYSQL query BETWEEN two epoch timestamps? I have epoch timestamps in my mysql database, I am using a Jquery datepicker to choose BETWEEN two dates. It works great when I choose at minimum between 1 day, but if I choose Sunday - Sunday ( the same day ) it should bring back records that have fallen on that day. I am assuming it is because of the epoch timestamp integrated withing the datepicker.. When you choose a date, like today, it comes back with : BETWEEN 1317103200 AND 1317103200 .... I know how epoch timestamps work and it seems like it is to the second when you convert and do the math... How do I implement a DISTINT value for that FULL DAY -- so it just looks at the full 24 hours and not down to the millisecond??? SELECT category, id, date, title FROM myTable WHERE date BETWEEN $beginDate AND $endDate AND... Thanks so much!! A: Use the mktime() function where $month, $day and $year have been populated with the month, day and year from your date text box: // Assumes date is in this format: dd/mm/yyyy, and your $_GET key is 'date' list($day, $month, $year) = explode('/', $_GET['date']); $beginDate = mktime(0, 0, 0, $month, $day, $year); $endDate = mktime(23, 59, 59, $month, $day, $year);
{ "language": "en", "url": "https://stackoverflow.com/questions/7575997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I 'require' CommonJS modules in the browser? What is the best way to load CommonJS modules as client-side JavaScript code in the browser? CommonJS modules put their functionality in the module.exports namespace and are usually included using require(pathToModule) in a server-side script. Loading them on the client cannot work the same way (require needs to be replaced, asynchronousness needs to be taken into account, etc.). I have found module loaders and other solutions: Browserify, RequireJS, yabble, etc. or ways to simply alter the modules. What do you consider the best way and why? A: I have used RequireJS extensively in the past (implementation on BBC iPlayer in 2010) and it works well. It can handle CommonJS modules, but it needs an additional wrapper, which I find annoying. If you want to use those modules in Node.js as well, you need to use RequireJS on the server side as well, which I don't like doing since it is not idiomatic Node.js JavaScript code. I have used webmake and Browserify in the past year on a few projects. Initially, the compilation step put me off, but having used it extensively this year, I can say that this is not an issue. Browserify has a watch function included, which works very well. Webmake can be hooked up to a watcher (such as watchr) or, you can use the webmake-middleware module, which can be used as part of an Express.js or connect application. This has the advantage that rather than compiling the JavaScript on each save, it is only compiled when you actually request it. Connect makes it trivial to create a server (also static), so you could create a tiny static Node.js server to serve up your files if you want to develop your frontend without a backend. Bonus: There isn't any need for a build script as you always deal with the built code. A: Here is a comprehensive list of your current options ordered by their respective popularity (number of watchers) on GitHub: Options for use of require() in the browser (Wayback Machine archive) A: The CommonJS compiler. Why? It works fine with Node.js (CommonJS) modules /treat module exactly as Node.js and, with UMD, brings minimum extra code to the compiled JavaScript, allows exporting global variables of third-party libraries without touching their code, source maps and a trick that other cannot do: var str = require( "lorem-ipsum.txt" ); console.log( str ); Output: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi... Here are the slides: https://speakerdeck.com/dsheiko/modular-javascript-with-commonjs-compiler A: Use Browserify. Its description is: "Browser-side require() for your node modules and npm packages" which sounds what you need. A: Webmake is one of the options. I use it to pack an application that is build from over 200 modules of over 20 packages. It works. If you want to see some example, check: SoundCloud Playlist Manager. It's strictly client-side and built with Webmake. A: I can't say I've tried the others you've listed here, but I like RequireJS because: * *It works in a similar way to CommonJS *It's easy to use *It implements some of the upcoming new standards *You can use it in Node.js so that you can use the same files in server and client *It includes a minifier/packer for deploying to production *It has plugins. The Text plugin, that lets you load HTML files, is very useful for large applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "81" }
Q: f:param not passed in ajax request I'm having trouble with the following code: <h:inputHidden value="autoCompleteHidden" id="administradorAutocompleteType"> <f:param value="#{suggestionEntitiesDM.usuario}" name="type"></f:param> </h:inputHidden> <p:autoComplete id="administradorAutocomplete" value="#{empresaDM.administradorSeleccionada}" completeMethod="#{suggestionEntitiesDM.suggestionList}" var="administrador" itemLabel="#{administrador.txtNombreUsuario}" forceSelection="true" itemValue="#{administrador}" converter="entityConverter"> <p:ajax event="start" update="administradorAutocomplete" process="administradorAutocompleteType"/> </p:autoComplete> What I want is to send the type parameter in request so that I can get the value by using: String type=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("type"); However I'm just geeting null when referencing the type String, I have even checked the request parameters using Firebug and effectively administradorAutocompleteType=autoCompleteHidden is passed but type=value is never posted. What I am doing wrong?, how can I pass additional request parameters when using the f:ajax JSF 2 tag?. Thanks a lot. A: Found a solution to the problem, the trick was to use f:attribute as suggested in this link: f:param or f:attribute support on primefaces autocomplete? since f:param was not being sent in the request, and the complete method required a fixed parameter to work. A: As stated in this PF forum topic, <p:ajax> is not supported in <p:autoComplete>. Also, passing additional arguments is not possible in completeMethod. I think <p:remoteCommand> is most suitable for your purpose. It generates a JS function which allows you to set a bean property. This JS function is in turn to be called by onstart attribute of <p:autoComplete>. <h:form> <p:autoComplete value="#{bean.text}" onstart="setType()" completeMethod="#{bean.complete}" > </p:autoComplete> <p:remoteCommand name="setType"> <f:setPropertyActionListener target="#{bean.type}" value="foo" /> </p:remoteCommand> </h:form> with private String text; private String type; public List<String> complete(String query) { System.out.println("type: " + type); // type: foo // ... } You can set foo with whatever value you want. It'll be available as type in the scope of the complete() method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I rotate the output in 90 degrees? I have a code and from kladblok.txt there is a file with the following numbers: 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 How can i get the output : 1111111111 2222222222 etc.. Can someone help me? A: The algorithm is very simple: * *Open the file *Allocate a 2 dimensional array which is big enough to contain the numbers *Read the numbers to the array *Close the file *Print the array transposed *Free the array A: If you just want to print it rotated 90 degrees, then just change the start/end/increment of your loops. Say you have int data[10][10] in the original rotation. Then you want to start in the lower left and go up. Move right one space, start again at the bottom and go to the top, etc: int i, j; for (i = ?; i ? ?; i??) { for (j = ?; j ? ?; j??) { /* print element [i][j] (or perhaps [j][i]) */ } /* do a carriage return here */ } /* What should the question marks be? */
{ "language": "en", "url": "https://stackoverflow.com/questions/7576005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Android WebView - catch link if has javascript embedded In my android app I have a WebView loading a webpage. This webpage was built by someone else and each html href does a javascript _dopostback() to get the URL to navigate to. For example: href="javascript:_dopostback(function(params))". My goal is to check to see if a link clicked from the WebView does have the javascript __dopostback() event in the html href. I used onTouch() and created a toast that shows me the URL when something is clicked but it is giving me the URL created after the __dopostback() event. I want the actual __dopostback() reference. For example: in my toast it would say __dopostback(function(params) rather than the URL it creates. Exactly as it does when I mouseover a link on the web page outside of the android browser. I also tried using the HitTestResult.getType() == 0 because I heard that android treats all javascript buttons as UNKNOWN. This works to activate the toast but I can't figure out how to display the javascript:__dopostback(function(params)) in the toast simliar to mousing over the link on a webpage when using a standard browser on my pc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set these complex types in ZEND SOAP AutoDiscovery? Hello I need to write a SOAP server, where I would be able to pass complex types, structuraly that would look like this: <ParcelDetails> <countryType></countryType> <addressType> <countryType></countryType> .... ..... .... .... <contact></contact> </addressType> <ParcelDetails> and I/m using following code to generate WSDL file for this service <?php include_once("Zend/Soap/Wsdl/Strategy/ArrayOfTypeSequence.php"); include_once("Zend/Soap/Wsdl/Strategy/DefaultComplexType.php"); include_once("Zend/Soap/Wsdl/Strategy/Composite.php"); include_once("Zend/Soap/Wsdl/Strategy/ArrayOfTypeComplex.php"); include_once("Zend/Soap/Wsdl/Strategy/AnyType.php"); include_once('Zend/Soap/AutoDiscover.php'); include_once('Zend/Soap/Server.php'); include_once('Zend/Soap/Client.php'); include_once('Zend/Soap/Wsdl.php'); //************************************* // Classes used by getGroup service method below class countryTypeSpace { /** @var country */ public $country = ''; } class addressTypeSpace { /** @var countryType */ public $countryType = ''; .... /** @var contact */ public $contact = ''; } class ParcelDetailsSpace { /** @var countryType */ public $countryType; /** @var addressType[] */ public $addressType; } //************************************* class ServiceClass { /** * ParcelDetails */ public function registerParcel( $username, $pasword) { $group = new ParcelDetailsSpace(); //fill in the array for ($i = 1; $i <= 3; $i++) { $countryType = new countryType(); $countryType->country = 'country'; $addressType = new addressTypeSpace(); $addressType->address = 'Adresas'; $addressType->area = 'Area'; $group->countryType = $countryType; $group->addressType = $addressType; } return $group; } } if(isset($_GET['wsdl'])) { $autodiscover = new Zend_Soap_AutoDiscover('Zend_Soap_Wsdl_Strategy_AnyType'); $autodiscover->setClass('ServiceClass'); $autodiscover->handle(); } else { $soap = new Zend_Soap_Server("http://localhost/zs/zserverComplex.php?wsdl"); $soap->setClass('ServiceClass'); $soap->handle(); } ?> on the client end I'm getting an error: Fatal error: Uncaught SoapFault exception: [VersionMismatch] Wrong Version in C:\Program Files (x86)\EasyPHP-5.3.8.0\www\zs\Zend\Soap\Client.php:1121 Stack trace: # 0 C:\Program Files (x86)\EasyPHP-5.3.8.0\www\zs\Zend\Soap\Client.php(1121): SoapClient->__soapCall('registerParcel', Array, NULL, NULL, Array) # 1 C:\Program Files (x86)\EasyPHP-5.3.8.0\www\zs\zclientDpd.php(6): Zend_Soap_Client->__call('registerParcel', Array) #2 C:\Program Files (x86)\EasyPHP-5.3.8.0\www\zs\zclientDpd.php(6): Zend_Soap_Client->registerParcel(Array) #3 {main} thrown in C:\Program Files (x86)\EasyPHP-5.3.8.0\www\zs\Zend\Soap\Client.php on line 1121 I'v tried different Zend_Soap_Wsdl_Strategy strategies as you might see from includes at the top of my server file, but no success at all I know that probably I'm missing something, but I'm not sure where to look... I would be glad if someone would be able to point me to the right direction, about these complex types and auto discovery, at least, if not the right answer to this problem Because I couldnt get any good info on this Thank you in advance A: I might be out of my league here, but I just wrote a web service in PHP using NuSOAP, and it allows you to define complex types and generates the WSDL for you. Might be something to check out: http://www.scottnichol.com/nusoapintro.htm In NuSOAP, to create a complex type like the one you provided, the code would look something like this: $server = new nusoap_server(); $server->wsdl->addComplexType( "addressType", "complexType", "struct", "all", "", array( "countryType" => array("name" => "countryType", "type" => "xsd:string"), ... "contact" => array("name" => "contact", "type" => "xsd:string") ) ); $server->wsdl->addComplexType( "ParcelDetails", "complexType", "struct", "all", "", array( "countryType" => array("name" => "countryType", "type" => "xsd:string"), "addressType" => array("name" => "addressType", "type" => "tns:addressType") ) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7576016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: NSTimeInterval to unix timestamp I'm getting CMDeviceMotion objects from CMMotionManager. One of the properties of the CMDeviceMotion is timestamp, which is expressed as a NSTimeInterval (double). This allows for "sub millisecond" timestamp precision, according to documentation. [motionManager startDeviceMotionUpdatesToQueue:motionQueue withHandler:^(CMDeviceMotion *motion, NSError *error) { NSLog(@"Sample: %d Timestamp: %f ",counter, motion.timestamp); } Unfortunately, NSTimeInterval is calculated since last device boot, posing significant challenges to using it in its raw form. Does anyone have a working code to convert this NSTimeInterval into a Unix like timestamp (UTC timezone)? Thank you! A: I imagine it is supposed to be used as a relative measure to allow you to sequence motion events correctly, so they went for as lightweight an implementation as possible. I can't think why you'd need the actual date and time of a motion event as they are all dealt with pretty much straight away. But if you really wanted to, you'd have to get the timestamp of one event, use that with the current date to work out the base date, and then use your base date to derive the actual time of subsequent events. A: I had a similar problem when comparing magnetometer values with CoreMotion events. If you want to transform these NSTimeIntervals you just need to calculate the offset once: // during initialisation // Get NSTimeInterval of uptime i.e. the delta: now - bootTime NSTimeInterval uptime = [NSProcessInfo processInfo].systemUptime; // Now since 1970 NSTimeInterval nowTimeIntervalSince1970 = [[NSDate date] timeIntervalSince1970]; // Voila our offset self.offset = nowTimeIntervalSince1970 - uptime;
{ "language": "en", "url": "https://stackoverflow.com/questions/7576017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to download a file from server without user interaction in flex 4 or flex 4.5? The code flow is as follows: user clicks 'download details' button on the page -> on button click handler a call to a RPC method is made using s:CallResponder -> RPC method generates and returns a URL from where to download the file -> the success event handler of the CallResponder gets the url where FileRefrence.download() is used to download the file but throws following error:- Error: Error #2176: Certain actions, such as those that display a pop-up window, may only be invoked upon user interaction, for example by a mouse click or button press. at flash.net::FileReference/download() Code is follows: <fx:Script> <![CDATA[ import mx.rpc.CallResponder; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; protected function downloadButtonClickHandler(event:MouseEvent):void { var web_service:IWeb_service = Web_service.getInstance(); getDetails.token = web_service.getURLDetails(); } public function onGetDetailsResult(event:ResultEvent):void { var response:URLResponse = event.result as URLResponse; if(response != null && response.url != null) { var request:URLRequest = new URLRequest(response.url); fileReference.download(request, "test.html"); } } public function onGetDetailsFault(event:FaultEvent):void { Alert.show("Error in downloading details"); } ]]> </fx:Script> <fx:Declarations> <net:FileReference id="fileReference" /> <s:CallResponder id="getDetails" result="onGetDetailsResult(event)" fault="onGetDetailsFault(event)"/> </fx:Declarations> <s:HGroup width="100%" height="100%"> <s:Button label="Download Details" id="downloadButton" click="downloadButtonClickHandler(event)" /> </s:HGroup> Is there any other way of achieving this as File FileReference needs a user interaction which is not happening int his case? A: I don't think there is a way to download the file via FileReference, due to security restriction, if you don't have the file available beforehand. As far as I'm aware there are two options to handle this scenario: * *Trigger FileReference download via separate button click (e.g. Alert dialog); *Initiate browser's standard download via navigateToURL(myURLRequest, "_self"); Hope this helps. A: Invoke web_service.getURLDetails() before the user clicks on download button (for example after the flex application is created). You can check in the downloadButtonClickHandler method if the url was loaded, or you can start with a disabled button and change the status to enabled after the url was loaded. A: var url:String = "test.xls"; var fileReference:FileReference = new FileReference; var urlRequest:URLRequest = new URLRequest(url); navigateToURL(urlRequest,"_new"); fileReference.download(urlRequest);
{ "language": "en", "url": "https://stackoverflow.com/questions/7576018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 80 byte wrapped format text file? I am having an issue with preparing a text file for one of our vendors. They are having problems reading the file; according to what I was told, the file must be in "80 byte wrapped format". I believe they are using a mainframe system so I'm sure it has something to do with that. When I created the file, I just used a simple StreamWriter with WriteLine() to do it, but if anyone has heard of this issue before, I could use some advice or a short code snippet on what I would need to do differently/add to accomdate their request. Thanks for any help that you can provide. A: That brings back memories (of COBOL, EDI and other uglyness). That usually means that each "record" is terminated with an 0x0d+0x0a (CRLF) or 0xa (LF) on it's own which translate to the following code: writer.Write("{0}\r\n", record); writer.Write("{0}\n", record); Do not use writer.WriteLine. In the case of 80 byte wrapped format, it depends on the vendor. It usually means that "a record" should be max 80 bytes (inclusive of the CRLF chars) otherwise it'll blow up the input buffer on the mainframe. Hoever, I would approach the company and ask them to provide a specification of the format they require precisely so there is no ambiguity. They should be able to either provide this or point you to the relevant vendor's documentation on the file format. You will also probable require a specific encoding i.e. ASCII or EBCDIC if you are unlucky. A: I remember using 80 columns text files ... are you sure they're talking about bytes? Well, if its one byte / char it would be the same. I would put the whole text in one string and then use a simple loop to put a linebreak after 80 chars. A: You need to get more information from your vendor. "80 byte wrapped" can mean several different things. As others have pointed out, they're almost certainly expecting ASCII encoding. The "80 byte" restriction means that no physical line can be more than 80 characters long (i.e. no characters in column 80 or beyond). A logical line, however, can often be longer than 80 bytes. The tricky part is how you separate the logical lines from the physical lines, and there have been any number of different formats for that. Some I've worked with expected logical lines (i.e. records) to be terminated with a CRLF, but physical lines terminated with just a CR. Or just an LF. So a record that's 120 characters in length would be encoded as: 79 characters<CR>41 characters<CR><LF> In some cases, all lines were terminated by CRLF, and the end of a record was signified by an empty line. Or they might be talking about quoted-printable encoding, although that's unlikely. Seriously, get a better description from the vendor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android migration from Opengles 1.0 to Opengles 2.0, textures? I currently have an OpenGLES 1.0 engine with a very large code base, and I'm in the process of migrating to OpenGLES 2.0 Thanks to this I've been able to get past the lack-of-matrices obstacle, but before I continue changing thousands of lines of code I would like to know a few things that I haven't been able to find with Google. First, has the process of applying textures changed at all? I know that the old fixed-pipeline did a lot of the dirty work for you, but I don't know if textures were part of that. Will I have to create shaders for that as well? (think glTexEnvf, glTexParameter, glBindTexture, etc) Second, has there been any changes with blend modes, or will that also need custom shaders? Third, has there been any important change to glDrawElements? (In other words, will my existing calls work without modification) Fourth, can anyone recommend some good books or tutorials for learning how to make shaders and how they work? I learned quite a bit from the large amount of iPhone tutorials on the internet and from the tutorial I linked above, but the latter doesn't contain any in-depth explanations and the former doesn't contain any Android code, and I'm new to shaders >_< A: * *Things like binding textures and the glTexParameters (like filtering or wrapping modes) work like before. But you now have to do the texture application inside the fragment shader yourself. Therefore you now basically implement glTexEnv yourself. *Blending works like before. These operations are done after the fragment shader in the same way like in ES 1. *Not to glDrawElements itself. But now you have to use custom vertex attributes and corresponding vertex shaders for processing them, istead of the builtin attributes (like vertex, normal, color, ...) from ES 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: fgets not terminating at newline According to the manpages, fgets writes a stream of characters to an array until it hits a null or newline character. But when I use fgets with a popen() stream with various shell commands, and then print the resulting array with printf, the newlines are retained and the output looks the same way as though I had gone through a terminal. Why is this? A: The fgets(3) man page reads: If a newline is read, it is stored into the buffer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opacity Gradient Applied to CALayer? I basically want the opacity of every layer in my UITableView instance to "fade out" at the top 10 or so pixels. Is there any way to fade out a CALayer (or more generally, a UIView)'s opacity? It'd be similar in effect to adding a shadow with a CAGradientLayer but instead of covering the table view's other layers with another, it would apply a filter to them to make them transparent according to a gradient. A: Yes, by using the CALayer's mask property, but it's rather inefficient. Typically this sort of effect is done by overlaying a gradient that goes from transparent to the background color on top of your view (but this only works if you know what your background is).
{ "language": "en", "url": "https://stackoverflow.com/questions/7576024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to re-use multiple .xib as a template to another .xib? I want to re-use some .xib files as templates to the major views of my iOS app. Can someone tell me if it's possible, in iOS, to achieve a "template-like" system such as: Header, Logo, Footer, and load them as separate .xib views to fill some placeholders inside another .xib? And how can I do that? Like this: In the same app, I have a Header.xib, Footer.xib, and I want to include them in my MainMenu.xib A: You can reuse one xib files for multiple views just by using it in the initWithNibNamecall. Then even if you have minor differences you can do them programmatically. I would recommend that you define one common setupMyScreen method which takes as a parameter the screenType you have and in a switch statement takes care of all the little modifications. This way it is quite easy to maintain. ps you might want to work on your acceptance level - otherwise one might not realy be inclined to provide answers to your questions... A: It sounds like u want to use multiple views in a single view than u must use UIView template into first one .
{ "language": "en", "url": "https://stackoverflow.com/questions/7576026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Doctrine DQL dynamic ORDER BY parameter Im trying to pass the ORDER BY column as a parameter in DQL, like below: $this->em->createQuery("SELECT t FROM Entities\Topic t ORDER BY :order") ->setParameters( array('order' => 't.name') )->getResult(); I guess it doesn't work because setParameter will escape :order, however the below solution doesn't seem very good: $order = 't.name'; // Dynamic value $this->em->createQuery("SELECT t FROM Entities\Topic t ORDER BY $order") ->getResult(); Is there a better way to solve this? A: In that case use Doctrines Querybuilder: $order = 't.name'; // Dynamic value $qb = $this->_em->createQueryBuilder(); $qb->select('t') ->from('Entities\Topic', 't') ->orderBy($order); A: I know, this is an old question but until today this "problem" still exists. So, if you want to use dynamic ordering, you should use the doctrine queryBuilder. I recently tested the current doctrine types on which one could be used for dynamic ordering. In my case I set the order column in the dql and only wanted to inject ASC/DESC. Now, here is the test output: DQL: SELECT w FROM App\Entity\Worker w ORDER BY w.id :order Type "array" is invalid Type "ascii_string" is invalid Type "bigint" is invalid Type "binary" is invalid Type "blob" is invalid Type "boolean" is invalid Type "date" is invalid Type "date_immutable" is invalid Type "dateinterval" is invalid Type "datetime" is invalid Type "datetime_immutable" is invalid Type "datetimetz" is invalid Type "datetimetz_immutable" is invalid Type "decimal" is invalid Type "float" is invalid Type "guid" is invalid Type "integer" is invalid Type "json" is invalid Type "object" is invalid Type "simple_array" is invalid Type "smallint" is invalid Type "string" is invalid Type "text" is invalid Type "time" is invalid Type "time_immutable" is invalid I'm using Symfony 5.3 and Doctrine 2.9 If someone is interested in the code, I used to test: I simply created a doctrine entity inside my symfony project. Then I created a test method inside the related repository object: public function testOrder(string $order = 'ASC'): array { $query = $this->getEntityManager()->createQuery( 'SELECT w FROM App\Entity\Worker w ORDER BY w.id :order' ); // map taken from: vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Type.php:101 $doctrineTypeMap = [ Types::ARRAY, Types::ASCII_STRING, Types::BIGINT, Types::BINARY, Types::BLOB, Types::BOOLEAN, Types::DATE_MUTABLE, Types::DATE_IMMUTABLE, Types::DATEINTERVAL, Types::DATETIME_MUTABLE, Types::DATETIME_IMMUTABLE, Types::DATETIMETZ_MUTABLE, Types::DATETIMETZ_IMMUTABLE, Types::DECIMAL, Types::FLOAT, Types::GUID, Types::INTEGER, Types::JSON, Types::OBJECT, Types::SIMPLE_ARRAY, Types::SMALLINT, Types::STRING, Types::TEXT, Types::TIME_MUTABLE, Types::TIME_IMMUTABLE, ]; print_r('DQL: ' . $query->getDQL() . "<br/>"); foreach ($doctrineTypeMap as $mappedType) { try { $query->setParameter('order', $order, $mappedType); print_r('Type "' . $mappedType . '" is '); $query->getSQL(); print_r('valid' . "<br/>"); } catch (\Exception $e) { print_r('invalid' . "<br/>"); } } // Prevent symfony from rendering a view die(); } A: I solved this problem by adding the following method to the repository, also using the Query Builder: class SomeEntityRepository extends ServiceEntityRepository { private function addOrderBy(QueryBuilder $qb, string $field, string $dir, string $alias = 'g'): void { if (property_exists($this->getClassName(), $field)) { $dir = strtoupper($dir) === Criteria::DESC ? Criteria::DESC : Criteria::ASC; $qb->addOrderBy($alias . '.' . $field, $dir); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7576029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: changing the color of the text using jquery $(document).ready(function () { $("#btnhighlight").click(function () { alert("yes"); var htext = $("#txthighlighttext").val(); $("#lstCodelist option").each(function () { var sp = $(this).text(); var sp1 = sp.split(' '); $.each(sp1, function (i, l) { if (l == htext) { l.css('color', 'yellow'); } }); }); }); }); var x = "hello world"; I need to change the text color on l. that is suppor I got the text from the string "hello". css( Can I do l.('color', 'yellow'); I am getting javascript error. if I do like this $(this).css('color', 'yellow'); Nothing happening. thanks A: Try: $(l).css('color', 'yellow'); Edit: Ok...you are working with strings and not actual DOM elements. My suggestion is to dynamically place l into an element like <span> and apply the CSS to that and then replace the original text in the DOM. I actually did something similar to this a while back: http://www.randomsnippets.com/2008/03/07/how-to-find-and-replace-text-dynamically-via-javascript/ I'm not saying this is the perfect solution but it will lead you down the right path. A: l in is the element you are iterating, wrap it inside the $ and you are good to go try $.each(sp1, function (i, l) { if (l == htext) { $(l).css('color', 'yellow'); } A: will something like this work? (untested) $('<span>', { 'style': 'color:yellow', html: l }).appendTo('#divName'); A: As it was mentioned l is not a dom element, which means you just need to "push" it inside the next each loop. $("#lstCodelist option").each(function () { var sp = this; //or $(this) and then you do sp.css('color', 'yellow'); var sp1 = $(this).split(' '); $.each(sp1, function (i, l) { if (l == htext) { $(sp).css('color', 'yellow'); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7576032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: minimal number of d flip-flops required for first seven Fibonacci numbers I encountered a problem while preparing for a test. What is the minimal number of d flip-flops required (along) with combinational logic to design a counter circuit that outputs the first seven Fibonacci numbers and then wraps around? A) 3 B) 4 C) 5 D) 6 E) 7 My answer B Seven Fibonacci numbers => 1 1 2 3 5 8 13. To count to 13, we will need to 4 flip-flops hence 4 was my choice. But the correct answer given is solutions was A. Could someone please explain?
{ "language": "en", "url": "https://stackoverflow.com/questions/7576035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In Java, should each query be in a separate thread? If an application is blocking until a query returns a response, doesn't it make sense to execute queries on a thread pool? A: Only if you expect to perform work during that period, otherwise there's no sense doing it. A nice way to do it is to have your API return a Future. Something like: interface QueryService { public FutureTask<QueryResult> query(Query q); } FutureTask<QueryResult> res = query(..); // do work res.get(); // blocks until result is in Of course, you should typically submit your Callables or Runnables to an ExecutorService .
{ "language": "en", "url": "https://stackoverflow.com/questions/7576043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ensure unique column value at application level One of the models in a Rails 3.1 application I'm working on has a "code" attribute that is generated automatically when the record is created and that must be unique. The application should check the database to see if the generated code exists and, if it does, it should generate a new code and repeat the process. I can ensure the field's uniqueness at the database level with add_index :credits, :code, :unique => true (which I am doing) and also in the model with validates_uniqueness_of, but both of these will simply return an error if the generated code exists. I need to just try again in the case of a duplicate. The generated codes are sufficiently long that duplicates are unlikely but I need to be 100% certain. This code generation is handled transparently to the end user and so they should never see an error. Once the code is generated, what's the best way to check if it exists and to repeat the process until a unique value is found? A: Here's a quick example, there is still technically a race condition here, though unless your seeing hundreds or thousands of creates per second it really shouldnt be a worry, worst case is your user gets a uniquness error if two creates are run in such a way that they both execute the find and return nil with the same Url class Credit < ActiveRecord::Base before_validation :create_code, :if => 'self.new_record?' validates :code, :uniqueness => true def create_code self.code = code_generator self.code = code_generator until Credit.find_by_code(code).nil? end end If you absolutely needed to remove the race condition case where two creates are running in tandem and both trigger the find with the same code and return nil you could wrap the find with a table lock which requires DB specific SQL, or you could create a table that has a row used for locking on via pessimistic locking, but I wouldn't go that far unless your expecting hundreds of creates per second and you absolutely require that the user never ever sees an error, it's doable, just kind of overkill in most cases. A: I am not sure if there is a built in way. I have always used a before_create. Here is an example in the context of a UrlShortener. class UrlShortener < Activerecord::Base before_create :create_short_url def create_short_url self.short_url = RandomString.generate(6) until UrlShortener.find_by_short_url(self.short_url).nil? self.short_url = RandomString.generate(6) end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7576045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MVC3/EF4: Editor For a field that an object, e.g., Employee.Supervisor My database has an Employee table, which has a column SupervisorId, which as you would expect is a foreign key into the Employee table. Currently, in my Create.cshtml view/form, for the supervisor field, I have a combo box with Employee.Name as the data text, and Employee.EmployeeId as their data value. Then in the controller I do this: ViewBag.SupervisorId = new SelectList(db.Employees, "EmployeeId", "Name"); This actually works pretty slick, but obviously it won't scale well at all. What I want is to just display the supervisor name in a non-editable text box, and then have a browse button that opens a div (worst case scenario, I'll use a pop up), that allows them to search an employee and select them -> placing their name in the text box. No the ID of supervisor is not visible. I am kind of at a loss about how to go about this. For the search, I suppose I'd use JS to set a hidden form variable with the supervisor's id, when the select a result? Or how do I store the supervisor value, so that it is set correctly on the Employee when submit is clicked? Can someone point me in the right direction, I don't need a coded solution, but just an overview. I am using the free Telerik controls if that helps. Thanks. A: Yes, you could use a read-only textbox to hold the value. No problem there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL subquery/complex query question, tracking state changes I have a table that tracks contact class state changes by date. The question that I am trying to answer is what is the current state of all contacts on a certain date. DROP TABLE IF EXISTS `contact_class_state`; CREATE TABLE `contact_class_state` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `contact_id` int unsigned DEFAULT NULL, -- the contact `contact_class` int unsigned, `state_date` date, PRIMARY KEY (`id`), INDEX (`contact_id`) ) DEFAULT CHARSET=utf8; INSERT INTO `contact_class_state` (`contact_id`, `contact_class`, `state_date`) VALUES (1, 1, '2011-01-01'), (2, 1, '2011-01-01'), (3, 1, '2011-01-01'), (4, 1, '2011-01-01'), (5, 1, '2011-01-01'), (1, 2, '2011-02-01'), (3, 2, '2011-02-01'), (5, 2, '2011-02-01'), (1, 1, '2011-02-15'), (5, 3, '2011-03-01'); For example, the following query: SELECT contact_id, contact_class, state_date FROM contact_class_state WHERE state_date <= '2011-02-27' ORDER BY contact_id, state_date DESC returns +------------+---------------+------------+ | contact_id | contact_class | state_date | +------------+---------------+------------+ | 1 | 1 | 2011-02-15 | | 1 | 2 | 2011-02-01 | | 1 | 1 | 2011-01-01 | | 2 | 1 | 2011-01-01 | | 3 | 2 | 2011-02-01 | | 3 | 1 | 2011-01-01 | | 4 | 1 | 2011-01-01 | | 5 | 2 | 2011-02-01 | | 5 | 1 | 2011-01-01 | +------------+---------------+------------+ While this is technically correct, I only need the first (or last if sorted ASC) row for each contact_id as the latest date will always give me current state of the contact, per the below: +------------+---------------+------------+ | contact_id | contact_class | state_date | +------------+---------------+------------+ | 1 | 1 | 2011-02-15 | | 2 | 1 | 2011-01-01 | | 3 | 2 | 2011-02-01 | | 4 | 1 | 2011-01-01 | | 5 | 2 | 2011-02-01 | +------------+---------------+------------+ I am pretty sure a sub or a complex query would do the trick but I am having a mental block with the SQL. I am also open to other approaches to solve this issue. Thanks! A: If your query is in fact what you want (except then grouped by contact_id), then do exactly that. SELECT * FROM (SELECT contact_id, contact_class, state_date FROM contact_class_state WHERE state_date <= '2011-02-27' ORDER BY contact_id, state_date DESC) table1 GROUP BY contact_id This is tested and works perfect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hierarchical tree with multiple sub items I am trying to wrap my head around how to solve this problem in WPF using an MVVM pattern. I am converting a win32 tree control into WPF. The old tree control uses a Node class hierarchy along these lines (BaseNode being the base class and each following item inheriting from it and extending slightly): BaseNode, GroupNode, VehicleNode, PersonNode, EquipmentNode, SupplyNodes (etc, etc.) Going from this, A GroupNode will have a list of child nodes which could be one or more GroupNodes, one or more VehicleNodes and one or more PersonNodes. A VehicleNode would have a list of PersonNodes that would be the crew for operating the vehicle. The VehicleNode would also have a list of PersonNodes that would be passengers in the vehicle. Each of these is under a 'Dummy' node labeled Crew and Passengers (though they are both PersonNode Types). Outside of this, a VehicleNode and PersonNode would each have EquipmentNodes and SupplyNodes. The tree will have several "Group" nodes that will be expanded to list any items of that type. Hopefully, this text diagram will help solve illustrate the problem. * *Ground Fleet (GroupNode) * *West Coast (GroupNode) *East Coast (GroupNode) * *Truck 1 (VehicleNode) *Truck 2 (VehicleNode) * *Crew (DummyNode) * *Bill the Driver (PersonNode) *Passengers (DummyNode) * *Passenger 1 (PersonNode) *Passenger 2 (PersonNode) * *Equipment (DummyNode) * *Camera (EquipmentNode) *Sunglasses (EquipmentNode) *Supplies (DummyNode) * *Apple (SupplyNode) *Water Bottle (SupplyNode) *Equipment (DummyNode) * *Jack (EquipmentNode) *Tire Iron (EquipmentNode) *Supplies (DummyNode) * *SpareTire (SupplyNode) *Personnel (DummyNode) * *Salesman Tom (PersonNode) *District Manager Sally (PersonNode) So the instance of Truck 2 (VehicleNode) has six child nodes (list of BaseNodes) of various types: List children; // {Bill The Driver(PersonNode), Passenger 1 (PersonNode), Passenger 2 (PersonNode), Jack (EquipmentNode), Tire Iron (EquipmentNode), SpareTire (SupplyNode)} In our existing win32 tree, when we add the Truck 2 node, we manually cycle through the child nodes and add the dummy nodes (As required) and children to create the tree based on the type of nodes in the children list and potentially a property on the child node - the PersonNode has a flag on it to indicate if its a passenger or crew, so we know which parent node to add it should belong to. I'm struggling with how this can be represented in an MVVM approach on a tree that would allow us to retain the Dummy Nodes as above. Any help would be greatly appreciated! A: Use HierarchicalDataTemplate, see a decent example here. You would expose a list of nodes from your ViewModel, and bind that to an ItemsSource of a TreeView. Each node will also have a child property that is another list of nodes. Each of you nodes could just be a simple class, or could actually be ViewModels themselves if you need to put ICommands/Actions/Methods at each node. Each node can be setup however you wish in C# in your ViewModel, since HierarchicalDataTemplate does alot of binding work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails 3 - ActiveRecord Find When Album Name Equals I've got a photo gallery Rails 3.0 app where Photos belong to Album. There are multiple Albums. I'm struggling trying to figure out how to select my Photos from an Album where I have passed in the Album name as a parameter. What is the correct way to do this? A: You haven't really provided much here, your models will be useful. Assuming you have: class Album < ActiveRecord::Base has_many :photos end class Photo < ActiveRecord::Base end And Album has a name field. Then you can do: @photos = Album.find_by_name(params[:name]).photos
{ "language": "en", "url": "https://stackoverflow.com/questions/7576055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Profile Location module - output full Country Name Can anyone tell me how to output the full country and state names using the Profile Location module? (Drupal 6) Currently, it will just spit out WA, US for Washington, United States. The author says that he has added hook_profile_alter to display country and state long string values on user view page, but I'm not sure how to implement this. Can someone help? Thanks. A: Add this function into your custom module: /** * Implementation of hook_profile_alter(). */ function CUSTOMMODULENAME_profile_alter(&$account) { $profile = user_load($account->uid); $category = variable_get('profile_location_category', NULL); $country = variable_get('profile_location_country', NULL); $state = variable_get('profile_location_state', NULL); if ($state) { $account->content[$category][$state]['#value'] = profile_location_get_state($profile->$country, $account->content[$category][$state]['#value']); // Here you can check state names. } if ($country) { $account->content[$category][$country]['#value'] = profile_location_get_country($account->content[$category][$country]['#value']); // Here you can check country names. } } [1]: http://drupal.org/developing/modules
{ "language": "en", "url": "https://stackoverflow.com/questions/7576058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XMLHttpRequest status 0 on second load I am experiencing an interesting issue when I am trying to load some data in .txt format from the same domain using XMLHttpRequest. I am trying to load the data, parse it and then store it in localStorage var xmlhttp; // code for IE7+, Firefox, Chrome, Opera, Safari if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); }else{ // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } var temp; xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ temp = xmlhttp.responseText; }else{ alert("readyState: " + xmlhttp.readyState + "status: " + xmlhttp.status); } } xmlhttp.open("GET","data/somedata.txt", false); xmlhttp.send(); This code only works if I clean the history and cache; however, on second click of the same link, I would received "Readystate: 4, status 0" for some reason. Does this has anything to do with localStorage? if (!localStorage.somedata || localStorage.somedata.count(':') !== somedata.count(':')) { localStorage.somedata = temp; } window.somedata = JSON.parse(localStorage.somedata); A: There are two causes of status code of zero. * *Making calls from the file protocol. *The page is refreshing/navigating away as the request is being made. In your case I would assume it is #2. If you are using a button or a link to make the Ajax call, make sure to cancel the click action with either preventDefault or return false. A: Sounds like a caching issue. Try either switching to a POST method, or appending a timestamp to the GET request querystring and see if that prevents the caching. xmlhttp.open("POST", "data/somedata.txt", false); or: xmlhttp.open("GET", "data/somedata.txt?" + new Date().valueOf(), false); Edit: If those don't work, modify your server configuration to send appropriate response headers for that file or type to not cache the response. Ie: Cache-Control: no-cache A: Try xmlhttp.abort() before opening a new request. It's a long shot but worth the try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FileNotFound Exception in Java (i'm new in Java) ... I want to store some class fields values in a HashMap then write it to a file (the path is passed as an argument) and then restore HashMap and fetch needed info. In my constructor called Carte, i get an exception that file is not found , anyway it's in the right place and saved data is in my xml file. Any ideas on this point An exception has occured : java.io.FileNotFoundException: users/stefan/desktop/lol.xml (No such file or directory) // Salveaza toate obiectele create intr-un fisier public void salveazaObiecteleCreate(String caleSpreFisier) { HashMap table = new HashMap(); table.put("Autorul", numelePrenumeleAutorului); table.put("Denumirea cartii", denumireaCartii); table.put ("Culoarea cartii",culoareaCartii); table.put ("Genul cartii ",gen); table.put ("Limba",limba); table.put ("Numarul de copii",numarulDeCopii); table.put ("Numarul de pagini",numarulDePagini); table.put ("Pretul cartii",pretulCartii); try { File file = new File(caleSpreFisier); FileOutputStream f = new FileOutputStream(file); ObjectOutputStream s = new ObjectOutputStream(f); s.writeObject(table); s.close(); } catch(Exception e){ System.out.println("An exception has occured"); } } public Carte (String caleSpreFisier) { HashMap table = new HashMap(); File file = new File(caleSpreFisier); try { FileInputStream f = new FileInputStream(file); ObjectInputStream s = new ObjectInputStream(f); table = (HashMap)s.readObject(); s.close(); } catch(Exception e){ System.out.println("An exception has occured : "+e); } for (Object key: table.keySet()) { System.out.println(table.get(key)); } } // end of class } A: Look at the message: An exception has occured : java.io.FileNotFoundException: users/stefan/desktop/lol.xml Note that it's "users/stefan/[...]" - it's a relative filename, so will be resolved relative to the current working directory. Are you sure you didn't mean "/users/stefan/desktop/lol.xml" with a leading slash to indicate an absolute filename?
{ "language": "en", "url": "https://stackoverflow.com/questions/7576065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AWTUtilities setWindowOpaque causing problems I have a modal JDialog that I set non-opaque with a call to the com.sun.awt.AWTUtilities method, setWindowOpaque(this, false). I encounter problems when I set the modal JDialog to be non-opaque. For example, when I click on a button a non-opaque dialog, it pop up correctly but after a couple of opening and closing of the dialog, it does open. It is not visible; and, since it is modal, we can't click on the button contained in the parent panel. It's like it is frozen, but that's only because of the modal dialog. If I remove the call to the method setWindowOpaque(this, false), it works without any problem. Does anyone know what is going on? I am using Java version "1.6.0_26" on Windows XP. Thanks. A: Ok, had a similar problem, sometimes the window was not responding, or transparency was broken... weird problems. The solution, at least for me, was calling new TransparentWindow() inside invokeLater: SwingUtilities.invokeLater(new Runnable() { @Override public void run() { TransparentWindow w = new TransparentWindow(); w.setVisible(true); } }); TransparentWindow is a class extending JWindow that uses com.sun.awt.AWTUtilities.setWindowOpaque(window,false); to create a transparent window with rounded transparent corners as explained here: Soft clipping and per-pixel translucency for Swing windows
{ "language": "en", "url": "https://stackoverflow.com/questions/7576066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: wxPython wx.EVT_LIST_ITEM_SELECTED Not Working When Same Item is Clicked Twice in a Row I have the below code for a wxPython panel in which I am trying show the user all the states, but I only want them to be able to select (or check) either Massachusetts or New York. This works when the user clicks once on that state, as the wx.EVT_LIST_ITEM_SELECTED event is called, but if you keep clicking on the same state, this event is not called. It is only called again if the user clicks on a different state. I have tried using a wx.PyEvtHandler to capture the events and find out which ones happen when I click on an item, but the only one I consistently see is the left mouse click event, which doesn't have a GetIndex attribute. Am I missing an event that is telling me that the user is still on the same list item and therefore is not calling either SELECTED or DESELECTED? Any help is greatly appreciated. import wx,wx.grid, ExampleImages #legend images from ObjectListView import GroupListView, ColumnDefn, ObjectListView class NEWLIST(wx.Panel): """Create a new information panel""" def __init__(self, parent, INFOB): wx.Panel.__init__(self, size=(-1, 460), parent=parent, id=wx.ID_ANY) self.dataOlv = GroupListView(self, wx.ID_ANY, style=wx.LC_REPORT|wx.SUNKEN_BORDER) self.dataOlv.useExpansionColumn = True #---------------------------------------------------------------------- myimgsdict = {} def myImageGetter(item): k = item.code.capitalize() myimgsdict[item.code] = self.dataOlv.AddImages(eval("ExampleImages.get%s16Bitmap()"%k)) if item in INFOB.list.dataOlv.GetCheckedObjects() and item.code in ('MA','NY'): return myimgsdict[item.code] #---------------------------------------------------------------------- self.statacolumn = ColumnDefn("Country", "left", 130, "state", useInitialLetterForGroupKey=True,isSpaceFilling=True) self.legendcolumn = ColumnDefn("" , "left", 16, "legend" , imageGetter=myImageGetter) self.totalcolumn = ColumnDefn("Total" , "right", 70, "total") self.inviscolumn = ColumnDefn("" , "right", 0, "region") self.dataOlv.SetColumns([self.statecolumn, self.legendcolumn, self.totalcolumn, self.inviscolumn]) self.dataOlv.InstallCheckStateColumn(self.statecolumn) self.dataOlv.SetSortColumn(self.dataOlv.columns[2]) #---------------------------------------------------------------------- # Create some sizers mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(self.dataOlv, 1, wx.ALL|wx.EXPAND, 5) self.SetSizer(mainSizer) #---------------------------------------------------------------------- def OnItemSelected(event): """Action for when item is seleted by the user""" realIndex = INFOB.list.dataOlv[event.GetIndex()] if realIndex.code not in ('MA','NY'): self.dataOlv.Uncheck(realIndex) #---------------------------------------------------------------------- self.dataOlv.Bind(wx.EVT_LIST_ITEM_SELECTED, OnItemSelected) self.dataOlv.Bind(wx.EVT_LIST_ITEM_ACTIVATED, OnItemSelected) #self.dataOlv.Bind(wx.EVT_COMMAND_LEFT_CLICK, OnItemSelected) self.dataOlv.Bind(wx.EVT_LIST_ITEM_DESELECTED, OnItemSelected) self.dataOlv.Bind(wx.EVT_LIST_CACHE_HINT, OnItemSelected) Thanks! A: EVT_LIST_ITEM_SELECTED is only fired when the item is first selected. You can't select an already selected item. You could bind to EVT_LEFT_DOWN and grab the position of the mouse. Then in the handler, you would use myListCtrl.FindItemAtPos() and pass the position to it. Something like that should work. A: You would want to use a mouse click event rather than an item selected event; Mike Driscoll is right.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cant get background changing images centered I have been strugglign for the last few horus trying to make it so that the background class will be centered in the website, but i have absolute position and fixed in my css for the inside of it because i need it done for a changing fading background image. But my problem is i cant get it centered in the site for example see in div.background i have margin 0 and it still isnt centered it just stays to the left i even tried but it doesnt work... How cani get the background div i made to be centered... <div class="background"> <img src="images/back_1.jpg" width="990" height="660" alt="pic1" /> <img src="images/back_2.jpg" width="990" height="660" alt="pic2" /> <img src="images/back_3.jpg" width="990" height="660" alt="pic3" /> </div> style div.background { margin:auto; width: 990px; position:absolute; left:0px; top:0px; z-index:-1; } div.background img { position:fixed; list-style: none; left:0px; top:0px; } div.background ul li.show { z-index:500 } A: I think you want this: div.background img { position: fixed; list-style: none; left: 50%; margin-left: -495px; top: 0px; } left: 50% moves the left edge of the img to the center of the page, then margin-left: -495px; shifts it back to the left exactly the right amount so that it's centered. A: This wouldn't work. What you should have is something like: div.background { position: absolute top: 0; left: 0; width: 100%; height: 100%; background: no-repeat center center url('images/back_1.jpg'); } and eliminate the individual <img> tags inside the div. You can then use some javascript to swap the background images whenever, since CSS1 only allows a single background image (CSS3 allows multiples). A: Did you try #background { margin: 0 auto; width: 990px; position:absolute; top:0px; z-index:-1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7576069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Zend form setAttribs with json_encode I have a zend form select element that calls a javascript function onchange. The following: $element->setAttribs(array( 'onchange' => 'toggleSelect(this.value, ' . json_encode($this->_testData) . ')')); The problem is, both the ZEND onchange and the json_encode use double quotes, so it becomes: <select onchange="toggleSelect(1, {"foo" : "bar"})"></select> Which complains about an invalid property id. I'm thinking it is the double quotes that are causing the problem, but don't know how to fix. A: Try $element->setAttribs(array( 'onchange' => 'toggleSelect(this.value, ' . htmlspecialchars(json_encode($this->_testData)) . ')')); Using htmlspecialchars you should end up with <select onchange="toggleSelect(1, {&quot;foo&quot; : &quot;bar&quot;})"></select> which should be valid html and still interpret your argument as a valid JSON object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET Roles not working in deployed ASP.NET MVC application I have published and deployed an ASP.NET MVC application that uses the Roles feature of ASP.NET authentication. On my development machine, Roles work fine - but on my server, to which I've transferred the build, the entire database (schema, data, and users), and with full permissions, Roles don't work. Here is the line where my code crashes: var exists = Roles.RoleExists("Administrator"); For some reason, such Roles queries aren't working, but System.Web.Security.Roles.Enabled returns true and System.Web.Security.Roles.Provider is set properly. What gives? A: If I had to take a guess, authentication is set up incorrectly on IIS on the server you have deployed to. Most likely, you used the built in developer server to develop and you have now deployed to a server that has default settings in IIS. A: I found the solution, and it turned out to be unrelated to ASP.NET. The problem, which I found in my SQL logs, was that my SQL user did not have the EXECUTE permission for the database. All it took was a simple query: CREATE ROLE db_executor; GRANT EXECUTE TO db_executor; Thanks to everyone for their help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Problem with foreign keys in sql database I have a school assignment that that is giving me and my friends headaches... So this is my queries that i have executed, one at a time ofc... CREATE DATABASE GamblingSociety; USE GamblingSociety; CREATE TABLE GamblingDen ( Name VARCHAR (20) PRIMARY KEY, Address VARCHAR (50), Phone VARCHAR (10) ); CREATE TABLE Room ( RoomNr INT, GameCapaity INT, GamblingDenName VARCHAR (20), PRIMARY KEY (RoomNr, GamblingDenName), FOREIGN KEY (GamblingDenName) REFERENCES GamblingDen (Name) ); CREATE TABLE Employee ( SSN CHAR (11) PRIMARY KEY, Name VARCHAR (20), Address VARCHAR(50), Salary INT, isBoss BOOL, GamblingDenName VARCHAR (20), FOREIGN KEY (GamblingDenName) REFERENCES GamblingDen (Name) ); CREATE TABLE GameType ( Name VARCHAR (20) PRIMARY KEY, WinningProcentage FLOAT, ResponsibleEmployee CHAR (11), FOREIGN KEY (ResponsibleEmployee) REFERENCES Employee (SSN) ); CREATE TABLE Supplier ( Name VARCHAR (20) PRIMARY KEY, Address VARCHAR (50) ); CREATE TABLE SupplierOfGameType ( SupplierName VARCHAR (20), GameTypeName VARCHAR (20), PRIMARY KEY(SupplierName, GameTypeName), FOREIGN KEY (SupplierName) REFERENCES Supplier (Name), FOREIGN KEY (GameTypeName) REFERENCES GameType (Name) ); CREATE TABLE GamblingTable ( TableNr INT, RoomNr INT, GamblingDenName VARCHAR (20), GameTypeName VARCHAR (20), Comments VARCHAR (128), PRIMARY KEY (RoomNr, TableNr, GamblingDenName, GameTypeName), FOREIGN KEY (RoomNr, GamblingDenName) REFERENCES Room (RoomNr, GamblingDenName), FOREIGN KEY (GameTypeName) REFERENCES GameType (Name) ); CREATE TABLE Shylock ( Phone CHAR (10) PRIMARY KEY, Name VARCHAR (20), Contry CHAR (3) ); CREATE TABLE Customer ( SSN CHAR (11) PRIMARY KEY, Name VARCHAR (20), Phone CHAR (10), Address VARCHAR (50) ); But this last query does not work: USE GamblingSociety; CREATE TABLE GamblingInstance ( StartTime DATETIME, EndingTime DATETIME, GamblingDenName VARCHAR (20), TableNr INT, GameTypeName VARCHAR (20), Customer CHAR (11), Shylock CHAR (10), Debt INT, DebtPayed BOOL, DebtPayedDate DATETIME, PRIMARY KEY (StartTime, GameTypeName, Customer), FOREIGN KEY (GamblingDenName, TableNr, GameTypeName) REFERENCES GamblingTable (GamblingDenName, TableNr, GameTypeName), FOREIGN KEY (Customer) REFERENCES Customer (SSN), FOREIGN KEY (Shylock) REFERENCES Shylock (Phone) ); It gives me this error: "Error Code: 1005. Can't create table 'gamblingsociety.gamblinginstance' (errno: 150)" if I replace this: FOREIGN KEY (GamblingDenName, TableNr, GameTypeName) REFERENCES GamblingTable (GamblingDenName, TableNr, GameTypeName), with this: FOREIGN KEY (GameTypeName) REFERENCES GamblingTable (GameTypeName), It works, so it's something with the GamblingDenName and TableNr. And i have google it and found a lot of tips, but nothing yeat have worked... So anyone with any idea? Thanks in advance! A: There is no key in GamblingTable that can satisfy this REFERENCE: REFERENCES GamblingTable (GamblingDenName, TableNr, GameTypeName), That is, there is no key in GamblingTable for which GamblingDenName, TableNr, GameTypeName are the only columns, or the first three columns. There is a key that satisfies REFERENCES GamblingTable (GameTypeName), which is why that version works. (I have to say that I've never actually seen FOREIGN KEYs being used to parent other FOREIGN KEYs, but I guess it works).
{ "language": "en", "url": "https://stackoverflow.com/questions/7576091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET Tcp Stream fails if idle more than three minutes I have a data collection system that passes data from the collecting computer(server) to the plotting computer (client) over a TCP connection. The code works fine the first time a collection is run. The code continues to work fine on subsequent runs if the system is not left idle for more than three minutes. If the system remains idle for more than three minutes the transfer hangs for the first 12 seconds or so (long enough to cause the collection buffers to overflow). At the start of every collection the client goes into a loop for 30 seconds where it checks every 1 ms to see if _clientStream.DataAvailable = true. That loop looks similar to this (some error checking code removed): public bool WaitForData(int maxWaitInMs) { DateTime start_time = DateTime.Now; while (!_clientStream.DataAvailable ) { Thread.Sleep(DATA_WAIT_DELAY); //1 ms TimeSpan elapsed_time = DateTime.Now - start_time; if (elapsed_time.TotalMilliseconds > maxWaitInMs) { return false; } } return true; } The server side is just doing a simple write of fixed length data _dataTcpServer.SendData(packet_buffer, OFFSET, packet.Size()); When the problem occurs, I can tell from the debugger that the server calls SendData once, returns gets the next packet of data calls the send method again and then hangs up for approx 12 seconds on the SendData call. The client in the meantime never sees DataAvailable go true until the 12 seconds elapse. The Send timeout was left at the default so it should be infinite. The 12 second time does seem to be related somewhat to the amount of data sent. One thing I did differently in this system was instead of creating the TcpClient when the client app starts, I new up a TcpClient when the client needs to Connect. On Disconnect I dispose of the Stream retrieved via the TcpCLient.GetStream and I close the TcpClient. I'm just hoping for some insight into why being idle for three minutes has this effect (both systems are running XP). EDIT - Problem Solved but understanding is proving elusive On the server I was using a separate thread that employed TcpListener.AcceptTcpClient() to allow a client to connect. AcceptTcpClient() returns a TcpClient object. I would periodically check that TcpClient's IsConnected property so I would know if the client disconnected (i.e. the measurement was over) and then I would pend again on AcceptTcpClient() and await the start of the next measurement. The problem was that even though the client's TcpClient disconnected, the server's TcpClient.IsConnected always returned true. I solved the problem by having the client send a message (not over TCP) to the server and then the server forces a disconnect on its end. Now everything works but I'm convinced I'm not using this API properly. While I can see the methods for doing the accept asynchronously I don't see how the server is supposed to find out when the client disconnects and I don't see why the server's TcpClient.IsConnected property would return true when there is no longer a valid connection. Also I was late to notice the ExclusiveAddressUse property so I never set it to true. The system acted like if another client connection was made within a few minutes, the same connection was reused and the server could send data to the client (i.e. it was as if the client had never disconnected). If more than three minutes passed since the disconnect, the new client connection was was accepted (even though as far as I can tell my code never got back to the AcceptTcpClient() line), but it was no longer the same connection the server was sending on. A: Thread.Sleep is EVIL when handling IO. Use socket.BeginReceive instead and come back if it still doesn't work. A: While I still don't understand why my client could connect when my server wasn't pending on AcceptTcpClient I think I do understand why Connected returns true even though the client disconnected. I dug into the underlying Socket docs on MSDN and saw this: The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. Since the client knows to quit because the server stopped sending data the last send prior to the client quitting was sucessful. I think Connected is a terrible name for this property. It should be WasConnected or WasConnectedAtLastSend, while more verbose it would have saved me a lot of heartache (and so would have reading the MSDN docs sooner).
{ "language": "en", "url": "https://stackoverflow.com/questions/7576093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why don't machinist objects save inside nested blocks? This is my spec code that isn't working: require 'spec_helper' describe User do describe "blah" do it "should save itself" do user = User.make! u = User.find user.id user = User.make! u = User.find user.id end end end The spec fails on the 2nd User.find even though that user object has an id. If I remove the 'describe "blah" do' block then the code seems to work fine. I'm using machinist 2.0.0.beta2. If I disable machinist caching in my test.rb config file it also works: Machinist.configure do |config| config.cache_objects = false end Anyone know what I'm doing wrong here? Is it a bad practice to nest multiple describes in a spec? Thanks A: This should also work: u = User.make u.save I run into this bug all the time using Machinist. I don't think it's exclusive to nesting describes, it seems pops up in other situations as well. Really wish they would fix this. It causes seemingly-random errors that are hard to track down.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hiding footer in ListView When my Activity loads, I inflate a layout file that I use for a footer. I attach it to the ListView (addFooterView) and then set its visibility to View.GONE. I maintain a reference to it, and when I want the user to see it, I set the visibility to View.VISIBLE. For the most part, this works great. However, the footer seems to still take up space. If the user uses the scroll wheel/pad, the area the footer is taking up gets highlighted. I'd like to polish this more so the footer is completely gone; ideally without detaching it from the ListView. Is this possible? Or am I going to have to set/unset the foot instead of simply toggling its visibility? A: You can toggle the visibility. To do that, you need to wrap the content of your footer using a linearlayout, then you set the linearlayout visibility to GONE. In the example bellow I set the visibility of LogoLinearLayout to GONE and it worked. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:id="@+id/LogoLinearLayout" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/Logo" android:src="@drawable/Logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="@dimen/spacing3" android:layout_marginBottom="@dimen/spacing3" android:layout_gravity="center" /> </LinearLayout> </LinearLayout> A: You can use listView.removeFooterView(view). The easiest way to do this is to create an instance variable to hold your inflated footer view (so you only inflate it in onCreate() ). Then just call listView.addFooterView(instanceFooter) and listView.removeFooterView(instanceFooter) as needed. Edit: Here's what I'm doing to get this to work: * *inflate footer layout(s) in onCreate *onResume: IF the adapter has not been instantiated, call addFooterView() THEN initialize your adapter (keep an instance reference to it) and call setAdapter(). This will leave the ListView "prepped" *onResume: update the adapter with the data (I have my data in a separate class) and call notifyDatasetChanged() *Call removeFooterView() (it will hide it if it's being displayed and do nothing otherwise) *Call addFooterView() if the footer needs to be displayed A: Try using View.INVISIBLE instead of View.GONE. (I have not tried this,but it might work) A: Set isSelectable parameter to false when You call addFooterView to disable footer selection and highlighting
{ "language": "en", "url": "https://stackoverflow.com/questions/7576099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Double check - does it ever make sense to have internal viewmodel class? I believe we cannot bind to internal viewmodel. Therefore I think all binding related implementations of IValueConverter, IMultiValueConverter, INotifyPropertyChanged, INotifyCollectionChanged should be always public in order to work with XAML. Is that correct? UPDATE: this isn't such an easy question because there are various possible weird cases, like nested viewmodel classes, or explicit interface implementations or something else that I am not aware of which could possibly lead to different answers. As we already can see WPF and SL4.0 treat internal viewmodels differently for some reason. A: Did some checking, based on this code: <UserControl> <UserControl.Resources> <sa1:TestValueConverter x:Key="TestValueConverter" /> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <TextBlock Text="{Binding Data, Converter={StaticResource TestValueConverter}}" /> </Grid> </UserControl> public class TestViewModel : INotifyPropertyChanged { public string Data { get; set; } public event PropertyChangedEventHandler PropertyChanged; } public class TestValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return "-" + value.ToString() + "-"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } Interestingly enough, results are different for WPF and Silverlight. And answers are: In Silverlight: * *"I believe we cannot bind to internal viewmodel" - yes we cannot bind to internal class, nor can we bind to internal or private properties, gives binding error. *"implementations of IValueConverter, IMultiValueConverter" - yes also should be public *"INotifyPropertyChanged, INotifyCollectionChanged" - these interfaces are implemented by classes of ViewModel and some collection that will be bound, so these classes should be public as we already know. And methods and events that implement interfaces cannot be private or internal obviously. In WPF: * *"I believe we cannot bind to internal viewmodel" - we can bind to internal class, but we cannot bind to internal or private properties. *"implementations of IValueConverter, IMultiValueConverter" - can be internal *"INotifyPropertyChanged, INotifyCollectionChanged" - see previous points. A: You cannot bind to internal properties, but it does not matter how accessible the source object (e.g. the DataContext) is as long as the properties are public. If it makes sense to restrict the access is another issue depending on the function of your classes and your assembly. I am not an expert on this but if the assembly is not going to be used by another one then you probably do not need to worry about its outer interface which can be controlled using internal. A: The reason why the two environments (Silverlight and WPF) behave differently is because of the silverlight reflection limitations. In silverlight you can not use reflection on internal or private members. So if the viewmodel is declared as internal, silverlight will not be able to use it for databinding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Error while trying to access Google translate with NSURL If I try this code: NSError *err = nil; NSString *resp = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=abdicate&langpair=en|es"] encoding:NSASCIIStringEncoding error:&err]; Err contains the following message: Error Domain=NSCocoaErrorDomain Code=258 UserInfo=0x1001166d0 "The file name is invalid." Anybody knows what this means? If I try the url on a browser, it works fine. A: (Using NSData) you can just replace the 1.0 with 1%2E0 and the | with %7C. It is possible that with the period is being interpreted as a file with an extension, thus the 258 error (From Foundation Constants Reference): NSError Codes NSError codes in the Cocoa error domain. enum { ... NSFileReadInvalidFileNameError = 258, } NSFileReadInvalidFileNameError: Read error because of an invalid file name Available in Mac OS X v10.4 and later. Declared in FoundationErrors.h. Try this: - (void)viewDidLoad { [super viewDidLoad]; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://ajax.googleapis.com/ajax/services/language/translate?v=1%2E0&q=abdicate&langpair=en%7Ces"]]; if (data) { NSLog([[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]); } } Gives the output: 2011-09-27 15:38:05.691 Project[44290:fb03] {"responseData": {"translatedText":"abdicar"}, "responseDetails": null, "responseStatus": 200} Which is the same as what you get by navigating to the url https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=abdicate&langpair=en|es in a browser. Try using NSData, then converting to a string, like so: NSString *result; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://ajax.googleapis.com/ajax/services/language/translate?%@", [self urlencode:@"v=1.0&q=abdicate&langpair=en|es"]]]]; if (data) { result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; } else { // Do something } This is the urlencode method used above: - (NSString *)urlencode:(NSString *)str { NSMutableString *output = [NSMutableString string]; const unsigned char *source = (const unsigned char *)[str UTF8String]; int sourceLen = strlen((const char *)source); for (int i = 0; i < sourceLen; ++i) { const unsigned char thisChar = source[i]; if (thisChar == ' '){ [output appendString:@"+"]; } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || (thisChar >= 'a' && thisChar <= 'z') || (thisChar >= 'A' && thisChar <= 'Z') || (thisChar >= '0' && thisChar <= '9')) { [output appendFormat:@"%c", thisChar]; } else { [output appendFormat:@"%%%02X", thisChar]; } } return output; } This whole part was unnecessary, just need to replace the 1.0 and | instead of encoding the entire url.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity framework and transaction in asp.net mvc application I have question about managing transaction in asp.net application. For example i have application for planning vacations. Controller has form to approving vacations. One user - click save and approve vacation ---- employee which want vacation has - 1 day second user - clik save and approve vacation and ? //pseudocode public void ApproveVacation(int vacationId) { //pull vacationdata from db var vacation = _dbContext.Vacations.FirstOrDefault(x => x.Id == vacationId); if (vacation != null && vacation.State != approved) // { using (TransactionScope scope = new TransactionScope()) { vacation.state = approved; vacation.Employee.Days = -1; _dbContext.saveChanges(); scope.complete(); } } } And question is simple, is transaction enough for this scenario or I must use one of concurency technique? Thanks EDIT : Context is created one per request. A: You already have an implicit transaction when calling 'SaveChanges' so there's no need for a transaction scope. And also, if you would change several items you would need to start the TransactionScope before you retrieve the data. A: Transaction handles atomicity of the operation so if operation modifies multiple database records it will always result in consistent state where all records are correctly modified (if operation succeeds) or all changes are rolled back (if operation fails). Concurrency handles possible modification of the same record by multiple processes / users because both could load original version of the record but one could save it first so when the second process tries to save a record it can silently override previous changes. So what are you trying to handle in your code?
{ "language": "en", "url": "https://stackoverflow.com/questions/7576106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cyclic dependencies- always wrong? 1.I would like to know if the following structure is incorrect, what is the reason, and what is the solution for that: Assume I have implemented a client for net game The client has 2 main packages: A.GUI - hold all the swing Jpanels etc. B.LogicEngine In Logic engine I have a class called clientThread which main goal is to communicate with the server to get commands to execute on the Gui Panel and also to send information back as a result of the user choices on the Gui Panels.. 2.In order to do so I tend to hold reference of my main Gui panel in clientThread and vise versa, is it so wrong to do cyclic reference between two classes of different projects? 3.Is it wrong in matter of object oriented programming to execute things to be shown on the Gui from within class like client thread which is responsible in some way to manage the flow of the game although it is on logical engine package? 4.Also if the Gui part know and uses the logical part is it a problem? Would like to hear some advices Thank you very much A: Obviously the GUI should depend on the engine, not the other way around (and, god forbid, they should not depend on each other). Your problem is actually pretty common and simple to solve. The engine thread should allow client code to install a listener that will be notified every time something happens. Than GUI implements that listener and installs it. Note that the game logic engine is only aware of the listener interface, not the particular implementation that lies in your GUUI package. This is an implementation of the Observer pattern and it has several advantages: * *notifying code (logic) is not coupled with the "interested" code (the GUI), there is not dependency from engine to GUI *you can plug any implementation of listener/observer, for instance changing Swing application to console/mobile/web application without any change to the engine. *you can have several listeners, e.g. one to update the GUI, second one to run sound, etc. Finally there is nothing wrong with manipulating your GUI from logic thread, hoever you must be aware of event dispatching thread. A: * *I would add a third element in. I would have GUI, LogicEngine, and Communication packages. In this way, you could do testing using files, or a local database, or mock classes. Logic and sockets don't belong together. They are simply inputs and outputs of each other. *I personally would have the logic know nothing about the GUI. The GUI's job would exist only to make calls into the logic. The GUI doesn't know who or what is calling into it, nor would it care. It's the same reason a microwave doesn't care if I am using it or my wife. *I don't quite understand this question. Could you rephrase it? *No, the other way around is the problem. The GUI exists so the user can manipulate the logic. The bad things happen when the logic depends on the GUI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HOWTO: Visual Studio 2010 MVC3 Project on Win7 x64 Using Oracle ODP.NET 11.2 I have a new development machine Windows 7 x64 and am writing an MVC3 application that targets an Oracle database. I have tried everything that I know of to get it running with no success. Previously, I was developing on a Win7 x32 box and could debug fine locally, but was unable to deploy and run it on a Win2008 x64 Server despite having ODP.Net and 11g Client installed. "Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. An attempt was made to load a program with an incorrect format" On my new x64 machine, I can build the project but when i try to run it in via the IDE I get: "The provider is not compatible with the version of Oracle client" I am at a complete loss. Does anyone have a similar setup that could share detailed instructions of what to install where and how to to reference Oracle.DataAccess in such a way that I can debug in the IDE on my x64 box, and also deploy to x64 server? It should not have to be this difficult. A: I do have this running on Windows 7x64 with the Oracle 11g R2 client that comes with the ODAC installation here: http://www.oracle.com/technetwork/topics/dotnet/index-085163.html Make sure you have the x64 version installed locally, and you may have to do the uninstall-reboot-reinstall-reboot tango. I also had weird problems getting it to see TNSNAMES entries and had to go with EZCONNECT strings, but that's not your problem. In fact, I've also gotten it working on x64 using the 32 bit EF beta and it works fine: http://www.oracle.com/technetwork/topics/dotnet/downloads/oracleefbeta-302521.html Although I don't think the EF implementatinon is 100% ready for prime time yet (we ended up using the DevArt driver instead because it had more reliable support for computed fields - we never did get Computed or Identity Timestamps working in ODP.NET EF Beta, although oddly Primary Key NUMBER fields populated by triggers did work.) I didn't have to do anything special, and I didn't have to do anything special on the server side either (with both 10g and 11gR2). A: So I finally figured it out. Here is what I did step-by-step: * *On my Win7 x64 development machine I removed all Oracle products in an attempt to start from scratch (including manually deleting registry keys and files/folders) *I installed "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64) " ON BOTH the dev machine and production IIS server * *I selected the RUNTIME option for the installation *During my first attempt the installation complained of not enough room in the PATH environment variable so I had to cancel the install, remove some path values (which a replaced after the install completed *I installed to C:\oracle was my base path and client_x64 was my HOME so it installed to C:\oracle\product\11.2.0\client_x64 *I then installed "64-bit ODAC 11.2 Release 3 (11.2.0.2.1) for Windows x64" on BOTH the dev and production mahcines. install.bat odp.net4 c:\oracle\odac11.2.x64 odac112x64 * *The above statement creates a new home named odac112x64 *At this point I built a simple console app using the following setup * *Added reference to Oracle.DataAccess.dll located in C:\oracle\odac11.2.x64\odp.net\bin\4 *Set CopyLocal = FALSE for the Oracle.DataAccess reference *Set the application to build for "ANY PROCESSOR" *The app connected to my oracle database and returned records on both machines *I then created a sample MVC website project with the same connection code as the console app. *When I ran it locally in the IDE it threw an error: "Could not load file or assembly 'Oracle.DataAccess, Version=4.112.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. The system cannot find the file specified." * *I believe this is because the IDE is 32bit and could not load a 64bit Oracle.DataAccess *I published that exact code to the production server and it ran successfully * *At this point my only problem is getting it to run locally for development purposes *I installed "ODAC 11.2 Release 3 (11.2.0.2.1) with Xcopy Deployment" which is the x32 version of ODP.NET install.bat odp.net4 c:\oracle\odac11.2.x32 odac112x32 *When I re-ran the MVC website project locally it worked as expected! UPDATED FOLLOW-UP INFORMATION #1: After getting this to work I attempted to apply the same steps to another server and it failed. The problem was that "Allow 32-bit Applications" was set to TRUE in the application pool. DISABLING 32-bit apps (only allowing 64bit) resolved the problem on the new machine. UPDATED FOLLOW-UP INFORMATION #2: The ODAC installation on the new machine failed to place the installation and bin directory in the environment path (I hate Oracle). Once that was added, all was running as desired. A: I have not worked with ODP.NET for quite some time, so I am running from memory of issues I had when I last used it. The ODP.NET bits have to be installed on the server (or at least deployed, although I am not sure how that is accomplished off hand). The actual client in ODP.NET is the same Java libraries used for Oracle access. If installed, then you have some type of configuration error or permissions issue with using the underlying Java libraries. I am not sure what the IDE message is about, however.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get an array of unique values in my controller that is NOT connected to a model? I have a table named Donations which has a column named season. Season contains the actual season the donation was made in... like 2011 or 2010, etc. I also have a controller named ReportController that would like to pass a unique list of seasons from the Donations table. In the ReportController, how do I get an array of those unique values? Is there something like @valid_seasons = Donations.find(:all).unique{|x| x.season} that I use in my reportcontroller? Will I then be able to pass @valid_seasons as an option for select statement in the views/report/foo.html.erb file? A: You can use uniq_by Donations.all.uniq_by{|x| x.season} However this still executes a select * on your table. You might be better off with using raw sql. Something like: Donations.find_by_sql("SELECT * FROM donations GROUP BY season") The first example will retrieve all the records and then filter. The second will only fetch the first row for each unique season. A: You don't mention if this is rails 3 but, if so, this should do the trick: Donations.select(:season).group(:season) This will execute a proper group by: SELECT season FROM "donations" GROUP BY season
{ "language": "en", "url": "https://stackoverflow.com/questions/7576120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Substringing JSON keys I have a form with inputs using this naming convetion: <input class="xxlarge" name="note[url]" id="url" placeholder="URL"> So, I'm using this script (found on StackOverflow) that serializes form data into JSON. $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; and on the output I have this: {"note[url]":"URL","note[title]":"TITLE"} I'd like to know how to transform this script to get output like this: {"url":"URL","title":"TITLE"} I'm handling this from with rather standard, documented code block (using function, described above): $(function() { $('form').submit(function() { $('#result').html(JSON.stringify($('form').serializeObject())); $.post( "/api/create", JSON.stringify($('form').serializeObject()), function(responseText){ $("#result").html(responseText); }, "html" ); return false; }); Thanks in advance! A: Not sure where your 'note' part is coming from. May be something you could fix via the name attributes in your markup. Otherwise you could always do something like: function renameKeys(obj) { var result = {}, key, check, noteReg = /^note\[([^\]]+)\]$/; for(key in obj) { result[(check = key.match(noteReg)) === null ? key : check[1]] = typeof obj[key] == 'object' && toString.call(obj[key]) == '[object Object]' ? renameKeys(obj[key]) : obj[key]; } return result; } which can be used to make a new object with the keys you want. renameKeys({"note[url]":"URL","note[title]":"TITLE"}); // { url: 'URL', title: 'TITLE' } renameKeys({"note[url]":"URL","note[title]":"TITLE", anotherObj: { thingA: 1234, 'note[thingB]': 9492}}); // { url: 'URL', title: 'TITLE', anotherObj: { thingA: 1234, thingB: 9492 } } Beware, though, that if you have something like a key of note[asdf] and a key of asdf then whichever is iterated over last will overwrite the other. A: I would suggest parsing the string into a JS object, changing the keys in a for loop, then stringifying it when you're done. Like so: // turn the string into a JS object var data = JSON.parse('{"note[url]":"URL","note[title]":"TITLE"}'); var newData = {}; // step through each member for(key in data) { // Regular expressions to find the brackets var newKeyStart = key.search(/note\[/) + 5; var newKeyEnd = key.search(/\]/); // pull out the desired part of the key var newKey = key.substr(newKeyStart, newKeyEnd - newKeyStart); // insert into new data object newData[newKey] = data[key]; } // turn back into JSON again var newJSON = JSON.stringify(newData);
{ "language": "en", "url": "https://stackoverflow.com/questions/7576125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Argument invalid with every build in Xcode? No matter what I try, I get an Argument is Invalid error in Xcode when I try to build to my iPhone. It works fine in the simulator. The problem is not specific to one project, it happens with any project, even when I create a new one. When I run the console it displays this I tried deleting and re-adding the provisioning profiles, and I've gone through every setting to look for spaces because I heard these can cause this error. Can anyone help? I don't know what else to try. A: If you have a symbolic link (ln -s) in your project directory, it will work on the simulator, but cause a “The argument is invalid” error if the target is a real iOS device. (Xcode 4.5.2) A: You may check if you have a space somewhere in the settings, such as the product name or so. These cause these kind of errors in many cases.... Also sometimes a symlink in your bundle can be the reason - depending on how you set up your file structures in the app bundle... A: Actually this looks like and xcode error because it cant find those .m files. So here is a post that responded to hopefully it helps. It looks like you are gonna have to do some installation and reinstallation. XCode Update - iOS Link Error A: I am assuming you are working with Git. This often happens due to issues in your local build. Take the latest pull from the develop branch and check if this solves your issue. If this doesn't work, you might want to manually check the build settings for your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rounded rectangle in Silverlight I'm trying to create a rectangle in Silverlight where the corners are rounded. However, I do not explicitly specify the width and the height of the rectangle, which means it adapts to the size of the Grid which contains it (the size of the grid depends on the screen resolution amongst other things, and is not known before hand). I'd like the RadiusX and RadiusY properties to be percentages of the rectangle's width and height respectively. What would be the cleanest way of doing this? Is there a XAML-only way of doing it (without resorting to code-behind)? A: Two files below to download I used for testing this http://dl.dropbox.com/u/8679840/SilverlightApplication1.zip Best way for reuse is to create a Type converter like <Grid x:Name="LayoutRoot" Background="White"> <Rectangle x:Name="rectangle" Width="200" Height="200" RadiusX="{Binding Width, ElementName=rectangle, Converter={StaticResource myConverter}, ConverterParameter=.1}" RadiusY="{Binding Height, ElementName=rectangle, Converter={StaticResource myConverter}, ConverterParameter=.1}" /> </Grid> and the code behind namespace SilverlightApplication1 { public class PercentConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return System.Convert.ToDouble(value) * System.Convert.ToDouble(parameter); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } A: While Justin King's answer works if the Width and Height are known before hand, it doesn't work if they're not set, and the parent control dynamically lays the rectangle out. Unfortunately, in Silverlight, you cannot use Binding with Converters on ActualWidth and ActualHeight, as they are calculated properties. What this means is that when ActualWidth and ActualHeight change, a property changed event is not raised internally, so the binding wouldn't propagate the changes to the source. Essentially, at this point, the only option is to subscribe to the LayoutUpdated event and calculate and set the RadiusX and RadiusY properties in code-behind.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can i use a Java SWT application as an Activex Host? I know this can be a bit of weird question, but let me explain the idea behind it first. I have a win32 app exposed a an Activex host, this gives me the the following useful features: * *Embed and call it from Internet Explorer as a simple to pass/return values from it using javascript. *Embed and call it from any win32 application made in languages like visual basic, c++, delphi etc. Even i can call it from MS office products like excel and word. I have been asked to migrate this app to Java SWT but i don´t know if it can be done without losing the mentioned capabilites, the only way could be to expose the app itself as an Activex host, can this be possible?. Thanks a lot. A: I have no experience with ActiveX, but a lot of examples are in snippets folder at SWT homepage. Try to check them.. A: If you migrate your app to Java SWT then you will lose the desired functionality of using in IE and as well as in other MS product based on COM or ActivX technology. Although one crude way could be to use some bi-directional COM broker like Jacob. If given a choice then I will utilize the SWT's in-built support for COM and will try to embed your activex component in my swt application. For example, you can look at: * *org.eclipse.swt.browser.IE -- Allows access to IE ActiveX component in the form SWT browser control. *org.eclipse.compare.internal.win32.WordComparison this is a part of eclipse's file diff plugin. The class is very nicely written and gives a COM flavored snippet of diffing two MS word files. In this way I can have the activex intact for whatever purposes. There is this article on adding activex support to swt without using any third party COM bridge
{ "language": "en", "url": "https://stackoverflow.com/questions/7576131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How is the * CSS rule more specific than a class or ID style rule? I'm using a * selector to indicate that unless I specify otherwise, the color of the font on a website should be set to a certain value. *{ font-family:"Verdana"; color: #04468e; } So far so good. The problem is that that's the most general of rules, and it should get readily overridden, for example by #profileMessageBoxHeader { background:url('images/profileMessageHeaderGradient.png') repeat-x #208ff6; height:178px; border-radius:10px 10px 0px 0px; color:#fff; } So the following code... <div id="profileMessageBox"> <div id="profileMessageBoxHeader"> < <p>Please fill out the form and click submit. Your entered profile data will be provided to the tutor, to allow them to contact you.</p> </div> </div> Should produce white text. For some reason, however, the extremely general * rule is overriding the more specific ID rule. Why? A: The * is a universal selector and overriding the settings on #profileMessageBoxHeader. It's the same as manually setting BODY, H1, P, TABLE, TR, TD, TH, PRE, UL, LI, ETC. For more information on it and how it can circumvent inheritance, Eric Meyer has a good article. Apply the following and it should work: #profileMessageBoxHeader p { color: #FFF; } Sample: http://jsfiddle.net/x7AnM/ A: Because the * is being applied to the <p>. If you change your CSS to: #profileMessageBoxHeader { background:url('images/profileMessageHeaderGradient.png') repeat-x #208ff6; height:178px; border-radius:10px 10px 0px 0px; } #profileMessageBoxHeader p { color:#fff; } ...then it should work. A: As far as I know an element outweighs an id (search CSS weight for more info) and * specifies (all) elements, so add the element div in your rule, e.g. div#my_id A: Because the "*" matches ANY element. So it's matching the p tag within #profileMessageBoxHeader and overwriting the styles applied to the parent container (#profileMessageBoxHeader). If you changed the style to be #profileMessageBoxHeader p{ color: #fff; } you'd get white text. Or if you changed the markup to remove the p tag, maybe <h3 id = "profileMessageBoxHeader"> Your Text </h3> that would also result in white text. A: There is my little try to illustrate cascade of Your two styles. <div id="profileMessageBox"> Rule of parent Rule * <div id="profileMessageBoxHeader"> Rule of parent Rule * Rule of #profileMessageBoxHeader <p> Rule of parent Rule * </p> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7576136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to remove rows of a matrix by row name, rather than numerical index? I have matrix g: > g[1:5,1:5] rs7510853 rs10154488 rs12159982 rs2844887 rs2844888 NA06985 "CC" "CC" "CC" "CC" "CC" NA06991 "CC" "CC" "CC" "CC" "CC" NA06993 "CC" "CC" "CC" "CC" "CC" NA06994 "CC" "CC" "CC" "CC" "CC" NA07000 "CC" "CC" "CC" "CC" "CC" > rownames(g)[1:2]->remove > remove [1] "NA06985" "NA06991" > g[-remove,] Error in -remove : invalid argument to unary operator Is there a simple way to do what I want to do here (remove the ID's referenced in the vector 'remove' from matrix g? Note: this is just a model for what I actually want to do, please don't say just do g[-(1:2), ], I need to be able to remove a whole bunch of rows that I have ID-d. A: When working with indexing, you cannot use "negative" character vectors. You can convert to logical with %in% g[!rownames(g) %in% remove, ] # ! is logical negation If you really wanted to use negative-indexing this could be done: g[-which(rownames(g) %in% remove), ] #which converts to numeric, so minus sign OK ... however it has a nasty potential erroneous result that arises when there are not any rownames in the target vector. The result may be no values returned. A: You cannot negative index a character vector when indexing. Turn your vector remove into a boolean. I've defined a function `%notin%` <- function(x,y) !(x %in% y) which can then be used as such: g[rownames(g) %notin% remove ,] A: I use "setdiff" as follows: g[setdiff(rownames(g),remove),]
{ "language": "en", "url": "https://stackoverflow.com/questions/7576138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: How to deal with Facebook login as page Facebook has recently allowed pages to be created without any facebook users associated with them. Facebook also lets these unowned pages sign into applications. How should an application detect and handle this situation? * *Sign out of facebook *Create new facebook page *You have a new facebook page, with ID = 249578561746447 *Sign into your facebook App. *Facebook auth callback returns the current user access token *STRANGE - User ID is = 100002923107961 (not 249578561746447??) *ERROR - "/me" connection returns "false" *ERROR - "/100002923107961" returns "false" *Frustrating Facebook Auth Documentation doesn't say this is possible *Frustrating There are no docs about this *Frustrating Reporting this issue to Faceboook gets blocked - See here Has anybody else even made a forray into this area yet? How should I go from a magic user with ID 100002923107961 to page with ID 249578561746447? A: If /me returns false, sign the user out with FB.logout and then show them a message saying they need to log in with a user account and not a page account. Facebook is clear in that logged bug that this is by design.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python simplejson.dumps still returns string Input : {"id": null, "type": null, "order_for": null, "name": "Name"} code : input_map = simplejson.dumps(eval(line)) print type(input_map) returns <type 'str'> what is wrong in here? Thank you A: Perhaps you meant: print(input_map) Also, if you use null in line, eval should have raised a NameError. You could use simplejson.loads instead: import simplejson line='{"id": null, "type": null, "order_for": null, "name": "Name"}' input_map = simplejson.loads(line) print(input_map) # {u'order_for': None, u'type': None, u'id': None, u'name': u'Name'} print(simplejson.dumps(input_map)) # {"order_for": null, "type": null, "id": null, "name": "Name"}
{ "language": "en", "url": "https://stackoverflow.com/questions/7576143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to get the .offset() of an an nth-child selector? For some reason I get a null error when I run $('.art:nth-child(2)').offset(); while $('.art:first').offset() and $('.art:last').offset() give values, no problem. Will offset() only return values for the first and last children? HTML: <div class="row_titles"> <a href="#"><img class="art" src="images/channel_art/netflix-trainspotting.jpg" /></a> <a href="#"><img class="art" src="images/channel_art/netflix-ronin.jpg" /></a> <a href="#"><img class="art" src="images/channel_art/netflix-camelot.jpg" /></a> <a href="#"><img class="art" src="images/channel_art/netflix-the_fighter.jpg" /></a> <a href="#"><img class="art" src="images/channel_art/netflix-johnmalkovich.jpg" /></a> <a href="#"><img class="art" src="images/channel_art/netflix-memento.jpg" /></a> <a href="#"><img class="art" src="images/channel_art/netflix-star_trek.jpg" /></a> <a href="#"><img class="art" src="images/channel_art/netflix-diehard.jpg" /></a> </div> A: The nth-child selector is selecting the children of your .art images - and since they don't have any children, this is null. You could try .row_titles:nth-child(2), or .art:eq(2) - either of those should work. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7576154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: tsql distinct having count I am using SSMS 2008 and am trying to select count of consumers who are part of two different events. Probably this is a simple query, but it is currently not returning expected count. Here is my T-SQL code which better explains what I tried: select [Program Quarter], event_name, consumer from #consumer_initiations where [Program Quarter] = 1 --and consumer = 'Byrd, Victoria Lynn' group by [Program Quarter], event_name, consumer having count (distinct event_name) > 1 So this query above returns 0 records. if I run following query, I get all records: select [Program Quarter], event_name, consumer from #consumer_initiations where [Program Quarter] = 1 So I can see where some of these records are where there is same quarter, same person, but 2 or more events for that person. Now, how can I count number of times that same person is part of 2 or more events? A: NOTE: Quick off the top of my head, so I am sure this can be optimized: Break the problem down. * *Find people who have more than one event for the quarter in question *Get the program quarter, event name and consumer for each consumer found in the above subquery Following this, the subquery is something like SELECT DISTINCT Consumer FROM #consumer_initiations WHERE Count(event_name) > 1 And the full query something like: SELECT [Program Quarter], event_name, consumer FROM #consumer_initiations WHERE consumer IN (SELECT DISTINCT Consumer FROM #consumer_initiations WHERE Count(event_name) > 1) I would then think of how to optimize this down without the subquery. A: I've used your structure to create some data that will generate some example output, copy and paste into SSMS if you want to. declare @consumer_initiations table ([Program Quarter] int null, event_name varchar(100) null, consumer varchar(50) null) insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (1, 'Event 1', 'Byrd') insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (1, 'Event 2', 'Plane') insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (2, 'Event 3', 'Train') insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (3, 'Event 4', 'Stuff') insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (1, 'Event 5', 'Plane') select [Program Quarter], event_name, consumer from @consumer_initiations where [Program Quarter] = 1 --and consumer = 'Byrd, Victoria Lynn' group by [Program Quarter], event_name, consumer having count (distinct event_name) > 1 select [Program Quarter], event_name, consumer from @consumer_initiations where [Program Quarter] = 1 -- Possibly gets more information than needed select consumer, [Program Quarter], count(event_name) as event_count from @consumer_initiations where [Program Quarter] = 1 group by [Program Quarter], consumer having COUNT(event_name) > 1 -- Just displays consumers with more than one event select consumer, event_count from ( select [Program Quarter], count(event_name) as event_count, consumer from @consumer_initiations where [Program Quarter] = 1 group by [Program Quarter], consumer having COUNT(event_name) > 1 ) as subq RESULTS Program Quarter event_name consumer --------------- ---------------------------------------------------------------------------------------------------- -------------------------------------------------- (0 row(s) affected) Program Quarter event_name consumer --------------- ---------------------------------------------------------------------------------------------------- -------------------------------------------------- 1 Event 1 Byrd 1 Event 2 Plane 1 Event 5 Plane (3 row(s) affected) consumer Program Quarter event_count -------------------------------------------------- --------------- ----------- Plane 1 2 (1 row(s) affected) consumer event_count -------------------------------------------------- ----------- Plane 2 (1 row(s) affected)
{ "language": "en", "url": "https://stackoverflow.com/questions/7576160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Left Joins in LINQ with multiple Critieria? How do you do add additional criteria to your left joins? In LINQ you can have only one join clause "x.id equals y.id". On inner joins, this is no problem, just add them to the where clause. When you are doing a left join this creates issues in LINQ. Adding this additional criteria seems to force it to be an inner join. join s in db.tblCustomerPricingSchemes on c.CustomerID equals s.CustomerID into g1 from s in g1.DefaultIfEmpty() join p in db.tblPricingSchemes on l.LangPairs equals p.PSLangPairID into g2 from p in g2.DefaultIfEmpty() where t.JobID == jobID //&& s.PSLangPairID == l.LangPairs //&& p.PSDescID == c.PricingID Any ideas? Thanks, Steve A: from s in db.tblCustomerPricingSchemes .where(x => c.CustomerID == x.CustomerID && x.PSLangPairID == l.LangPairs).DefaultIfEmpty() A: try from c in db.tblCustomer from s in db.tblCustomerPricingSchemes.Where(w => w.CustomerID == c.CustomerID).DefaultIfEmpty() from p in db.tblPricingSchemes.Where(w => w.PSLangPairID == l.LangPairs).DefaultIfEmpty() where t.JobID == jobID select c // etc A: You have two options. Firstly, use the navigational properties. I've asked why people use joins instead of navigational properties a while back and the answers supported my understanding - there's rarely a real reason and it's usually a mistake. As the other answers here suggest, use some where clauses to filter your object graph. db.tblCustomerPricingSchemes.Where(x => condition).Select(scheme => new { scheme, scheme.LangPair, scheme.LangPair.PricingScheme }); However if you need to join, then you try allowing for the outer join in your where clause by doing some null checks. where t.JobID == jobID && (s.PSLangPairID == null || l.LangPairs == null || s.PSLangPairID == l.LangPairs) && (p.PSDescID == null || c.PricingID == null || p.PSDescID == c.PricingID) if it were SQL you use a coalesce operator, but not sure if this would work and again depends on whether you're using LINQ-to-SQL or Entity Framework. && (s.PSLangPairID ?? l.LangPairs) == l.LangPairs && (p.PSDescID ?? c.PricingID) == c.PricingID
{ "language": "en", "url": "https://stackoverflow.com/questions/7576168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS5 Push notifications, Are there any alternatives to the Notification Center? I have 2 related questions regarding the new push notification in iOS5: * *If my application is not running in the background - Can the notification arrive to my application silently? *Can I revert back to the old modal popup UI for push notification? Can I do it programmatically only for my application notification while leaving all the rest using the notification center disappearing notification? A: You can send a silent message by not providing the sound property with the push message. You cannot revert back to the old modal popup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why my panel class gets null public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); _panel = (Panel) findViewById(R.id.panel); _panel.setOnTouchListener(this); } main.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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/Xiaohua_Demo" /> <com.android.demo.Panel android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/panel" /> </LinearLayout> When I start the application, in the Oncreat() i can not get the _panel from the R.id.Panel, is there anything missing?
{ "language": "en", "url": "https://stackoverflow.com/questions/7576172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't access fields of a Javascript Object The following Javascript function returns a JS object: function getCookies() { var result = {}; var cookie = {}; var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { cookie = cookies[i].split('='); result[cookie[0]] = cookie[1]; } return result; } When I tried to access its fields the "easy" way, all I got was "undefined", eg: var c = getCookies(); alert(c.a_cookie_name); alert(c['a_cookie_name']); The only way I could access the keys and values was iterating through the fields, eg: for(cookieName in c){ alert(c[cookieName]); } The question is how to access the fields without iterating? Thank you. P.S. The keys and values do exist, I can see the object fields with console.log(getCookies()) in Chrome. A: You are properly accessing fields the problem is that hte fields you're accessing don't exist. It' looks like the property named a_cookie_name simply doesn't exist on the object. EDIT Given that the Chrome console shows the properties as existing, one possibility to consider is there is white space in the names of the properties. This could explain the difference as the white space would be hard to see in the console. To test that out try the following. It will make the spaces a bit more visible if they are there for (var cookieName in c) { alert('"' + cookieName + '"="' + c[cookieName] + '"'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7576173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ruby on rails tag functions. Why does the case of radio_button_tag.id not match label.for? While registering for openstreetmap, on the terms page, I noticed that clicking the labels didn't check the radio buttons associated with them. Here is the html: <!-- legale is GB --> <form action="/user/terms" method="post"> <p> Please select your country of residence: <input id="legale_fr" name="legale" onchange="Element.update(&quot;contributorTerms&quot;, &quot;&lt;img alt=\&quot;Searching\&quot; src=\&quot;/images/searching.gif?1313181320\&quot; /&gt;&quot;);; new Ajax.Request('/user/terms?legale=FR', {asynchronous:true, evalScripts:true})" type="radio" value="FR" /> <label for="legale_FR">France</label> <input id="legale_it" name="legale" ... type="radio" value="IT" /> <label for="legale_IT">Italy</label> <input checked="checked" id="legale_gb" name="legale" ... type="radio" value="GB" /> <label for="legale_GB">Rest of the world</label> </p> </form> As you can see the checkbox id="legale_gb" doesn't match the label for="legale_GB". Now openstreetmap's website is actually open source so we can read the terms.html.erb: <!-- legale is <%= @legale %> --> <% form_tag :action => 'terms' do %> <p> <%= t 'user.terms.legale_select' %> <% [['france', 'FR'], ['italy', 'IT'], ['rest_of_world', 'GB']].each do |name,legale| %> <%= radio_button_tag 'legale', legale, @legale == legale, :onchange => remote_function( :before => update_page do |page| page.replace_html 'contributorTerms', image_tag('searching.gif') end, :url => {:legale => legale} ) %> <%= label_tag "legale_#{legale}", t('user.terms.legale_names.' + name) %> <% end %> </p> <% end %> I'm a rails newbie, but I can't see anything there that lowercases the id of the radio button tag. What's more, even when I look at the source of radio_button_tag, sanitize_to_id I can't see where this is coming from. Anyone got any idea what's causing this? Edit Swapped out label for radio in my description according to answer from A: 2 things: * *Wrong tag, the offender is radio_button_tag (it's capped as expected in the label). *Seems like you're linking to the wrong Rails. According to this project's environment.rb, it's using Rails 2.3.14. If you look at radio_button_tag for that release, you'll see the culprit. # our pretty tag value is downcased on line 318 pretty_tag_value = value.to_s.gsub(/\s/, "_").gsub(/(?!-)\W/, "").downcase # although the pretty name is not, oddly pretty_name = name.to_s.gsub(/\[/, "_").gsub(/\]/, "") # then the two are combined into the HTML id html_options = { ..., "id" => "#{pretty_name}_#{pretty_tag_value}", ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7576174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: tsql help with concatenting several fields i have address columns that i would like to concatenate even if only one field is not null. for example street,city,state,zip null,null,AL,36609 Currently, my sql statement is like this: select street + ',' + city + ',' + state + ',' + 'zip as address so the sample record above gives me null for address. is there an easy way to show whatever is not nulll? so the example record above would return: AL, 36609 A: Try this: select isnull(street + ',', '') + isnull(city + ',', '') + isnull(state + ',', '') + isnull(zip + ',', '') This relies on the standard NULL behavior where any operation on NULL returns NULL. So street + ',' will return NULL if street is NULL. The ISNULL operator will then choose the empty string instead. For more information about NULL concatenation, see SET CONCAT_NULL_YIELDS_NULL. (This option will always be enabled in a future version.) A: You can use COALESCE: SELECT COALESCE (street, '') + COALESCE (city, '') + state + zip AS address An alternative is to use ISNULL: SELECT ISNULL(street, '') + ISNULL(city, '') + state + zip AS address A: Try this query: SELECT SUBSTRING( ISNULL(','+street,'') +ISNULL(','+city,'') +ISNULL(','+state,'') +ISNULL(','+zip,'') ,2, 500) AS address FROM table A: declare @temp table (street varchar(100) null,city varchar(100) null, state char(2) null, zip varchar(10) null) insert into @temp (street,city,state,zip) values (null,null,'AL','36609') select ISNULL(street + ', ','') + ISNULL(city + ', ','') + ISNULL(state + ', ','') + ISNULL(zip,'') from @temp will return you AL, 36609 EDIT This is not pretty, but seems to work for a variety of null placements: declare @temp table (street varchar(100) null,city varchar(100) null, state char(2) null, zip varchar(10) null) insert into @temp (street,city,state,zip) values (null,null,'AL','36609') insert into @temp (street,city,state,zip) values (null,null,'AL',null) insert into @temp (street,city,state,zip) values ('Acacia Avenue',null,'AL',null) insert into @temp (street,city,state,zip) values ('Acacia Avenue',null,null,null) select case when city is null and state is null and zip is null then ISNULL(street, '') when state is null and zip is null then ISNULL(street + ', ','') + ISNULL(city,'') when zip is null then ISNULL(street + ', ','') + ISNULL(city + ', ','') + ISNULL(state,'') else ISNULL(street + ', ','') + ISNULL(city + ', ','') + ISNULL(state + ', ','') + ISNULL(zip,'') end from @temp RESULTS AL, 36609 AL Acacia Avenue, AL Acacia Avenue (4 row(s) affected) A: I'd write it as below : DECLARE @Address VARCHAR(200) select @Address= isnull(',' + street, '') + isnull(',' + city, '') + isnull(',' + state, '') + isnull(',' + zip, '') from yourtablename where criteria SELECT STUFF(@Address, 1, 1, '') AS Address As already pointed out by other members, when you perform any operation on fields having NULL, resultant expression(value) would always be null.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript: Detect colliding divs How do I detect if two divs are overlapping? Not taking into consideration the width of a div, it is basically a vertical line segment. The (top,left) point is point A while the bottom (top + height) is point B and so forth. I'd then compare each div to each to the other divs in the divs array and then create an array of colliding divs. However, I'm stuck on how to do this programmatically. This is my array of divs: var divs = [ {class:'A', top:0, left:0, height:'60px'}, {class:'B', top:50, left:60, height:'60px'}, {class:'C', top:30, left:10, height:'60px'}, {class:'D', top:100, left:180, height:'60px'}, {class:'E', top:80, left:50, height:'60px'}, {class:'F', top:110, left:200, height:'60px'}, {class:'G', top:55, left:80, height:'60px'} ]; Here's the function I had started: this.collide = function( divs ) { var collidingDivs = [], z = events.length; for(i; i<z; i++) { if ( // Begin pseudocode ( divsB.top >= divsA.top ) && ( (divsB.top + divsB.height) <= (divsA.top + divsA.height) ) ) { collidingDivs.push(divs[i].class); } } console.log(collidingDivs); // Array of divs that overlap (collide) }; I'm just utterly stuck at this point. How do I iterate over each div and check if it collides with any of the other divs? A: You need to loop through each div, and then compare with every other div in a nested loop. Then use logic like what you've written to compare each combination. Here is an example that simply prints out the overlapping divs to the output (note also that I changed the height element to have a numerical value rather than text so that its value could be used in calculations): var divs = [ {class:'A', top:0, left:0, height:60}, {class:'B', top:50, left:60, height:60}, {class:'C', top:30, left:10, height:60}, {class:'D', top:100, left:180, height:60}, {class:'E', top:80, left:50, height:60}, {class:'F', top:110, left:200, height:60}, {class:'G', top:55, left:80, height:60} ]; for (var i=0; i < divs.length - 1; i++) for (var j=i+1; j < divs.length; j++) { var I=divs[i]; var J=divs[j]; if ( (I.top <= J.top && (I.top + I.height) >= J.top) || (J.top <= I.top && (J.top + J.height) >= I.top) ) document.writeln( I.class + " collides with " + J.class + "<br />"); } Output: A collides with B A collides with C A collides with G B collides with C B collides with D B collides with E B collides with F B collides with G C collides with E C collides with G D collides with E D collides with F D collides with G E collides with F E collides with G F collides with G Sample working code: http://jsfiddle.net/QUrWM/
{ "language": "en", "url": "https://stackoverflow.com/questions/7576183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Lag in Java Game I'm writing a game in Java. And, oh wonder, i have performance issues. I benchmarked the paint itself - 1000 cycles in 3 ms tops. The game logic is even below that. So far, so good. But i still encounter an annoying lag: When scrolling, when zooming, when clicking. The problems get worse when i zoom in and more objects are placed. But still - even when I loop the painting a 1000 times the lags stays more or less the same, so that cant be it. I tried putting the loop in a task - still the same. I tried pausing the task in between paints - still the same. Animations run as smooth as silk (since the framerate is stable and high, that makes sense). So how on earth do i organize the inputs in an orderly fashion? Put them all in a seperate thread? Any input would and will be greatly appreciated! A: It sounds like you're using listener callbacks directly on the Swing Event Dispatch Thread, where the UI updates are being done. You should use a command queue, and put events on the queue when a callback is invoked, with the nature of the command, then you use this in the main game update loop that has nothing to do with the EDT.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: call wcf service by form submit I have service [OperationContract] void AddData(str ingdata) implementation void AddData(string data) { NameValueCollection dataToAdd= HttpUtility.ParseQueryString(data); //do seomething with data } and html form <form action='service.com/Service.svc/AddData' method="post" target="_blank"> <label >FirstName</label> <input type="text" size="30" name="FirstName"> <label >LastName</label> <input type="text" size="30" name="LastName"> <input type="submit" value="Submit"> </form> I have big problem to invoke this service. Always after submit I was redirect to service url, but breakpoint on service implementation never fire :/ I want to after submit collect all data from text input and get it in service parameter.. Do I something wrong? A: When call wcf service from html form is the best to use Stream type as parameter in service method [OperationContract] void AddData(Stream data) In stream I have all parameters send from html controls in form and them could me get using that code: NameValueCollection PostParameters = HttpUtility.ParseQueryString(new StreamReader(data).ReadToEnd()); This solve my problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7576186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I use projections with in NHibernate? I'm using <dynamic-component> elements to provide end-users the capacity to extend the functionality of our product by adding fields to the database. A simplified version of our mapping is: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Caselle.Am0.DTO" assembly="Caselle.Am0.DTO" schema="dbo"> <class name="Asset" table="[tblAsset]" lazy="true"> <id name="ID" column="ID" type="Int32"> <generator class="native" /> </id> <property name="AssetNumber" column="[AssetNumber]" type="long" not-null="true" /> <dynamic-component insert="true" update="true" name="UserDefinedFields" /> <many-to-one name="Classification" column="tblClassificationID" class="Lib.DTO.Classification, Lib.DTO" cascade="none" /> </class> <class name="Classification" table="[tblClassification]" lazy="true"> <id name="ID" column="ID" type="Int32"> <generator class="native" /> </id> <property name="Name" column="[Classification]" type="String" not-null="true" length="20" /> <dynamic-component insert="true" update="true" name="UserDefinedFields" /> <set name="Assets" table="tblAsset" lazy="true" cascade="all-delete-orphan" inverse="true"> <key column="tblClassificationID"/> <one-to-many class="Lib.DTO.Asset, Lib.DTO"/> </hibernate-mapping> The classes look something like this: public class Asset { public virtual long AssetNumber{get; set;} public Classification Classification {get; set;} public virtual IDictionary UserDefinedFields {get; set;} } public class Classification { public virtual string Name {get; set;} public virtual ICollection<Asset> Assets {get; private set;} public virtual IDictionary UserDefinedFields {get; set;} } The problem I'm running into is that now users want to use our filtering tools on their custom fields, and I get a QueryException(Could not resolve property 'X') when I run the following query: var query = session.CreateCriteria<Asset>() .Create Alias("c", "Classification") .Add(Restrictions.Eq(Projections.Property("c.X"), "value") .ToList<Asset>(); Is it possible to do this kind of a projection? How else might I write this query (I really like the Criteria API, since I'm generating this query on the fly, but if I have to work some other way...)? A: I don't think you want to use the projection there. Try swapping out .Add(Restrictions.Eq(Projections.Property("c.X"), "value") for .Add(Restrictions.Eq("c.UserDefinedFields.X", "value")
{ "language": "en", "url": "https://stackoverflow.com/questions/7576187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validation in HTML5. :invalid classe after submit I'm building a form and I want to use the :invalid selector to give the "required" input fields a red border if the user presses submit without filling them, but using this makes them appear highlighted right when the page loads. It seems unfriendly to give this kind of warning to the user before even giving him the chance to fill them at least once. Is there a way that these fields appear highlighted only after trying to submit the form, said in another way, is there a way to run the validation only after clicking submit (or at least losing focus on the required input fields?) A: Very simple just use #ID:invalid:focus This only does the validation when focused on and not on page load A: In addition to @Alexander Farkas' post, Dave Rupert has a very workable solution here: Happier HTML5 Form Validation. Essentially, what it does is add a CSS class to form input elements that only displays after a user attempts to submit the form. This is much better UX, in that these elements won't show the invalid styling by default, or when a user tabs through them, which enhances accessibility. Prior to finding this, I tried styling elements with :invalid:focus and other pseudo-elements, but didn't get the desired effect. Although I try to do my styling with pure CSS as much as possible, this looks like a use case where efficient JS is the practical solution. A: No there is nothing out of the box. Mozilla has its own pseudoclass for something very similiar called ':-moz-ui-invalid'. If you want to achieve something like this, you have to use the constraint validation DOM-API: if(document.addEventListener){ document.addEventListener('invalid', function(e){ e.target.className += ' invalid'; }, true); } You can also use webshims lib polyfill, which will not only polyfill incapable browsers, but also adds something similiar like -moz-ui-invalid to all browser (.form-ui-invalid). A: Another way is to add a hide-hints class to the inputs with JavaScript on load. When a user modifies a field you remove the class. In your CSS you then apply styling to input:not(.hide-hints):invalid. This means the error styling will be shown for users without JavaScript as well. A: I used this approach for a project of mine, so the invalid fields would be highlighted only after submit: HTML: <form> <input type="email" required placeholder="Email Address"> <input type="password" required placeholder="Password"> <input type="submit" value="Sign in"> </form> CSS: input.required:invalid { color: red; } JS (jQuery): $('[type="submit"]').on('click', function () { // this adds 'required' class to all the required inputs under the same <form> as the submit button $(this) .closest('form') .find('[required]') .addClass('required'); }); A: Old question, but for people that might might find it useful: I made a little script that adds a class to a form when it's attempted to be submitted, so that you can style forms that have and haven't been attempted to be submitted differently: window.addEventListener('load', function() { /** * Adds a class `_submit-attempted` to a form when it's attempted to be * submitted. * * This allows us to style invalid form fields differently for forms that * have and haven't been attemted to submit. */ function addFormSubmitAttemptedTriggers() { var formEls = document.querySelectorAll('form'); for (var i = 0; i < formEls.length; i++) { function addSubmitAttemptedTrigger(formEl) { var submitButtonEl = formEl.querySelector('input[type=submit]'); if (submitButtonEl) { submitButtonEl.addEventListener('click', function() { formEl.classList.add('_submit-attempted'); }); } } addSubmitAttemptedTrigger(formEls[i]); } } addFormSubmitAttemptedTriggers(); }); Now forms that are attempted to be submitted will get a class _submit-attempted, so you can only give these fields a red box shadow: input { box-shadow: none; } form._submit-attempted input { box-shadow: 0 0 5px #F00; } A: You can achieve this by chaining pseudo-classes: <style> input:required:focus:invalid { ... } </style> that way the input field will just show invalid styles only when that input field required and focused. Here is a helpful article: https://alistapart.com/article/forward-thinking-form-validation/ Another stack overflow thread on this: https://stackoverflow.com/a/7921385/11102617 A: I tried this in my website: <style id="validation"></style> <script> function verify() { document.getElementById("validation").innerHTML = "input:invalid { border: 1px solid red!important;}input:valid { border: 1px solid green;}"; } </script> Then add onclick="verify()" to your submit button, just like this: <input type="submit" onclick="verify()"> A: form.invalid { *:invalid { box-shadow: 0px 0px 2px 1px red; } } let form = document.querySelectorAll('form')[0] form.addEventListener('submit', function() { if (!form.checkValidity()) { form.classList.add('invalid') } }) With the above styles and javascript the form controls will only display the :invalid styles after the submit event and the checkValidity check failing. An invalid check will add the invalid class to the form and activate the styles, otherwise the form will submit as usual. A: Here's another solution that only styles the inputs after a submit attempt. HTML <form id="sign-up-form" method="post" enctype="multipart/form-data" class="login-form sign-in-form"> <input type="text" placeholder="Name" id="full-name" name="full-name" required> ... </form> <script> (() => { const form = document.getElementById('sign-up-form'); form.noValidate = true; form.onsubmit = function(e) { e.preventDefault(); this.reportValidity(); if (this.checkValidity()) return this.submit(); this.classList.add('submit-attempt') } })() </script> CSS .submit-attempt input:invalid, .submit-attempt select:invalid { border: 1px solid red; } A: for 'required' validation way 1 - set 'required' attribute for each element on form submit // submit button event $('#form-submit-btn').click(function(event) { // set required attribute for each element $('#elm1, #elm2').attr('required','true'); // since required attribute were not set (before this event), prevent form submission if(!$('#form')[0].checkValidity()) return; // submit form if form is valid $('#form').submit(); }); way 2 - use 'data' attribute <input type="text" data-required="1"> <script type="text/javascript"> // submit button event $('#form-submit-btn').click(function(event) { // set required attribute based on data attribute $(':input[data-required]').attr('required','true'); // since required attribute were not set (before this event), prevent form submission if(!$('#form')[0].checkValidity()) return; // submit form if form is valid $('#form').submit(); }); </script> A: the problem with waiting for an onSubmit or "submit" event listener is that the form itself is never technically being submitted when the data from the inputs is false. What I did (in react but same principle) is to set a click listener on the submit button and then set a class like "submitted".. then apply the classes accordingly .submitted input:invalid{ outline: 2px solid red; /* oranges! yey */ } A: Expanding on previous answers: Instead of adding a class to the form to indicate whether to show the :invalid styles, you can use a hidden input. The advantage is that when the form is cleared (either by a type=reset button or through javascript), the :invalid styles automatically disappear. You could add another event handler to remove a class on reset, of course; just my preference. Note that to do it this way you have to use an invisible checkbox rather than a hidden element and specifically change the checked property. Changing an input's value or attribute through javascript changes the default value so far as .reset() is concerned. If you don't put a name on the dummy element, it won't be posted with the form, but you can still access it through javascript via id or class. #attemptedSubmit[value=Yes] ~ :invalid, #attemptedSubmit[value=Yes] ~ * :invalid { border: 1px solid red; } <form> <input type="checkbox" style="display:none;" id="attemptedSubmit"> ... rest of the form <input type="text" name="text" required> ... rest of the form <input type="submit" value="Submit" onclick="$('#attemptedSubmit').prop('checked', true)"> <input type="reset" value="Clear"> </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/7576190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Does Usage with Callback Interface with SessionMode is Mandatory? I have a service which calls back the client. the interface has this attribute : [ServiceContract(Namespace = "rf.services", CallbackContract = typeof (ISendBAck), SessionMode = SessionMode.Required)] Does the SessionMode field is mandatory ? why do i need it here ? If i remove it , it still works. but this is a downloaded working example. and i wanted to know why it is there from the first place. A: In a situation where oneway oneway operations and callbacks are used, the processing of messages may be queued. The use of sessions is not mandatory but provides assurance that messages will be processed in the order they are received. This assurances simply has a greater value to the client in scenarios where the call to the service might return before processing is completed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7576194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: perl hash declaration error I am new to perl and can't seem to find why this snippet is giving me a 500 error. #!/usr/bin/perl use strict; use warnings; use CGI::Carp qw( fatalsToBrowser ); my ($distance, $weight, $total_gas, $mph, $buffer, $pair, @pairs, $value, $form, $name); our %FORM = (); read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; $FORM{$name} = $value; } Everything I tried on the %FORM = (); gives me variable declaration errors. A: Are you certain that @pairs contains the values you expect (ie that they are name value pairs split with "="? More than likely $name isn't defined and you can't add an undefined key pair to a hash. Why are you using STDIN to read in values from the query string? Try: my $q = CGI->new; my @keys = $q->param; my %FORM; foreach my $name (@keys) { my $value = $q->param($name); $FORM{$name} = $value; } or my $q = CGI->new; my %FORM = $q->Vars; http://perldoc.perl.org/CGI.html A: I think you're missing HTTP header. Try adding to put following line before any print: print "Content-type: text/html\n\n"; Make sure you have enough permissions for script to run. It'll depend on OS you're using. Also you'd consider using CGI module as mentioned in scrappedcola's answer. This code will work for both POST and GET: use strict; use warnings; use CGI; my $form = CGI->Vars; print "Content-type: text/html\n\n"; print "name=".$form->{name};
{ "language": "en", "url": "https://stackoverflow.com/questions/7576196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }