text
stringlengths
8
267k
meta
dict
Q: Phonegap-plugin-facebook-connect doesn't work I got some problems when I try to integrate the plugin "Phonegap-plugin-facebook-connect" in to my application. I'm new with android developement and phonegap so i think it's some form of newbie mistake :) I have followed the readme that's in the plugin but not getting it to work =/ Errors The method onCancel() of type new Facebook.DialogListener(){} must override a superclass method ConnectPlugin.java /x/src/com/facebook/phonegap line 92 Java Problem The method onComplete(Bundle) of type new Facebook.DialogListener(){} must override a superclass method ConnectPlugin.java /x/src/com/facebook/phonegap line 61 Java Problem The method onError(DialogError) of type new Facebook.DialogListener(){} must override a superclass method ConnectPlugin.java /x/src/com/facebook/phonegap line 86 Java Problem The method onFacebookError(FacebookError) of type new Facebook.DialogListener(){} must override a superclass method ConnectPlugin.java /x//src/com/facebook/phonegap line 80 Java Problem A: In your project properties, select the [Java Compiler] node, and change the [Compiler compliance level] option to 1.6 . That should sort your issue out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Terminal emulator that allows dynamically change of background color I'm currently trying to find a terminal emulator, for a Linux-based system, that allows me to change the background depending on what application I'm running. I'm thinking that this should be pretty easy to do with some OSC escape-sequence, but I can't find any documentation about there being any terminal supporting it. Any suggestions? A: If your terminal emulator supports Background Color Erase (BCE), you could use an "erase display" escape sequence to set the display's background color. For example, this sets the background to red in Bash: tput setab 1; tput clear tput setab 1 sets the "ANSI Background Color" to 1 (Red). put clear clears the screen, usually by emitting the codes to move the cursor to the top/left corner and clear the display. If you don't want to erase the entire display, you can just erase from the current line to the end of the display: tput setab 1; tput ed If your terminal emulator supports BCE, various commands that clear portions of the display will fill the cleared area with the current background color. You can tell if your terminal emulator supports BCE using tput: tput bce && echo Yes || echo No This will display "Yes" if BCE is supported. To make use of this, you can use shell functions (or script files) to wrap the commands you want to set the color for. E.g., in Bash, this will set the display to blue when running ssh: ssh () { trap 'tput sgr0; tput ed' RETURN; tput setab 4; tput ed command ssh $*; } Using trap ensures it resets the background color (and other text attributes) when the function returns. I've used tput ed here, so it only affects the background color of the lines output while running the ssh command. You can use tput clear if you'd rather fill the entire display and you don't mind erasing the current contents at the start (and/or end) of the command. Of course, if anything you do with the remote host changes the background color, it will override your color. A: You can do this with xterm using xtermset: xtermset -bg darkred or xtermcontrol: xtermcontrol --bg=darkred A: I use the Xfce terminal for cmus and change the background based on the cover art. For changing the background, I use sed-sleep-sed to make it realize that the image has changed (I would love to know a better way): sed -i "s:/path/to/old/image:null:g" $HOME/.config/xfce4/terminal/terminalrc ; \ sleep 1; \ sed -i "s:null:/path/to/new/image:g" $HOME/.config/xfce4/terminal/terminalrc
{ "language": "en", "url": "https://stackoverflow.com/questions/7548135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Exiting application iOS When my application loads, using the didFinishLaunchingWithOptionsi parse data from the internet to nsarrays. My question is, when the user exists the application by using the 'home' button, and then loads the application again how can the data be re-loaded? (because if the data does not reload - if there are any updates on websites, the new updates will not be seen). A: Add an applicationWillEnterForeground method to your app delegate. Load the data there, or start a thread to load it if you like. You should probably also periodically check for new data even while the app remains open, because the user could go idle for a long time. A: As an aside, you shouldn't do anything which might block in applicationDidFinishLaunchingWithOptions. If you are using synchronous NSURLConnection APIs there is a danger the OS might kill your app for taking too long to launch. Best to either use the asynchronous/NSURLConnectionDelegate APIs or do the networking on a background thread and call back to the main thread when you need to update UI (UIKit does NOT like being called from background threads, as it is not thread safe. It might appear to work sometimes, but it will come back to bite you sooner or later).
{ "language": "en", "url": "https://stackoverflow.com/questions/7548136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get the days number of the week I would like to get the days of the week compared to the present day. Example : Today it's sunday 25, i would like to have an array with : 19, 20, 21, 22, 23, 24, 25 (monday, tuesday, etc) If we were in the middle of the week, for example Wednesday 21, i should have the same array because it's the same week. Thanks A: Take a look at strtotime(). It accepts relative time strings, for example: strtotime('last Monday'); From there you could determine the week for a loop, start and end dates, etc. Note: Be mindful of your usage though. As noted in the comments this logic is not internationalized. Furthermore, strtotime() is a locale specific function. A: This might do the trick: $days = array(); $inputdate = time(); $dayOfInput = date('j', $inputdate); // 25 $weekdayOfInput = date('N', $inputdate); // monday = 1, tuesday = 2, ... $monday = $dayOfInput - ($weekdayOfInput - 1); for ($i = 0; $i < 7; $i++) { $days[$i] = $monday + $i; } var_dump($days);
{ "language": "en", "url": "https://stackoverflow.com/questions/7548137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SML/NJ while loop I am really new to SML and I can't figure out how to get answer for the same; It goes something like: 3^4 < 32 but 3^5 > 32 so my answer is 4 (power of 3), similarly if I have numbers 4 and 63 then 4^2<63 but 4^3>63 so my answer is 2(power of 4). I have come up with the following code val log (b, n) = let val counter = ref b val value = 0 in while !counter > n do ( counter := !counter*b value := !value + 1) end; So here value is what I need as my answer but I get a lot of errors. I know I am wrong at many places. Any help would be appreciated. I can perhaps do this the normal ML way but I want to learnt impure ML also... fun loghelper(x,n,b) = if x>n then 0 else (1+loghelper((x*b),n,b)); fun log(b,n) = loghelper(b,n,b); ok so finally here is the correct code for the while loop and it works as well; fun log (b, n) = let val counter = ref b val value = ref 0 in while (!counter <= n) do (counter := !counter*b; value := !value + 1); !value end; A: You have several problems in your code: Errors: * *Instead of val log (b, n) = it should be fun log (b, n) =. fun is a convenience syntax that lets you define functions easily. If you wanted to write this with val you would write: val log = fn (b, n) => (it gets more complicated in the cases of recursive functions or functions with multiple curried arguments) *You need a semicolon to separate two imperative statements: ( counter := !counter*b; value := !value + 1) *value needs to be a ref: val value = ref 0 Logic: * *Your function doesn't return anything. A while loop has the unit type, so your function returns () (unit). You probably want to return !value. To do this, you need to add a semicolon after the whole while loop thing, and then write !value *Your while loop condition doesn't really make sense. It seems reversed. You probably want while !counter <= n do *Your base case is not right. Either value should start at 1 (since counter starts at b, and b is b to the first power); or counter should start at 1 (since b to the zeroth power is 1). The same issue exists with your functional version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Postscript: how to convert a integer to string? In postscript , the cvs *operator* is said to convert a number to a string. How should I use it ? I tried : 100 100 moveto 3.14159 cvs show or 100 100 moveto 3.14159 cvs string show but it didn't work. Any help ? A: Try 3.14159 20 string cvs show. string needs a size and leaves the created string on the stack. cvs needs a value and a string to store the converted value. If you're doing lots of string conversions, it may be more efficient to create one string and reuse it in each conversion: /s 20 string def 3.14159 s cvs show A: tldr; A common idiom is to use a literal string as a template. 1.42857 ( ) cvs show more... You can even do formatted output by presenting cvs with various substrings of a larger string. %0123456....... (2/7 = ) dup 6 7 getinterval 2.85714 exch cvs pop show But the Ghostscript Style Guide forbids this. And it's pretty much the only published Postscript Style Guide we have. (A discussion about this in comp.lang.postscript.) So a common recommendation is to allocate a fresh string when you need it and let the garbage collector earn its keep. 4.28571 7 string cvs show Freshly allocating a string can be very important if you're wrapping this action in a procedure. /toString { ( ) cvs } def % vs /toString { 10 string cvs } def If you allocate a fresh string, then the enclosing procedure can be treated as a pure function of its inputs. If you use an embedded literal string as the buffer, then this resulting string is state-dependent and will be invalidated if the generating procedure is run again. too much, don't do this... As a last resort, the truly lazy hacker will hijack =string, the built-in 128-byte buffer used by = and == to output numbers (using, of course, our friend cvs). This is interpreter-specific and not portable according to the standard. 5.71428 =string cvs show And if you like that one, you can combine it with ='s other trick: immediately evaluated names. { 7.14285 //=string cvs show } % embed =string in this procedure This shaves that extra microsecond off, and makes it much harder to interactively inspect the code. Calling == on this procedure will not reveal the fact that you are using =string; it looks just like any other string. Using =string in this manner inherits all the state-dependency problems described in the last section, ramped up a notch because there's only one =string buffer. And it adds a portability issue to boot, since =string is non standard -- albeit available in historical Adobe implementations and Ghostscript -- it is a legacy hack and should be used only in situations where a legacy hack is appropriate. something else, no one (here) asked for... One more trick for the bag, from a post by Helge Blischke in comp.lang.postscript. This is a simple way to get a zero-padded integer. /bindec % <integer> bindec <string_of_length_6> { 1000000 add 7 string cvs 1 6 getinterval }bind def
{ "language": "en", "url": "https://stackoverflow.com/questions/7548142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: ANDROID - creating users/accounts for server/service login privileges Hello everyone on here, I have an application I am working on that requires the user to be able to login to an account in order to gain access to privileges and other services they would otherwise be denied. They will be able to use the basic app itself without login or creating an account but in order to talk to the server and have their data stored they will need to create an account. So far Ive looked for the past couple of days and most threads here or other forums talk mostly about using the google account for doing things which is great for a simple app but the project I am working on is anything but simple :p So.....can the wonderful people of stack overflow direct me to information regarding the process of creating a user account on the app that would correlate to one on a server that can talk to and login to a service that is hosted on that same server. That would be great....thanks A: Step one: write a web app that manages users and accounts using your favorite server side language/framework. Step two: Expose some HTTP interface for Android clients (a simple form will probably do). Step three: Use HttpClient to talk to your webapp. For example, post username, password, user info to the form in step two.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is it that I need not convert int to string in this case? (.Net) private void button2_Click(object sender, EventArgs e) { int i = 5; MessageBox.Show(i); } Fails.. private void button2_Click(object sender, EventArgs e) { int i = 5; MessageBox.Show("hoo" + i); } Works. Why is that?? A: MessageBox.Show() requires a string as its input parameter. The first sample fails because there is no implicit conversion from integer to string. The second sample succeeds because "hoo" + i evaluates to a string. This happens because the C# language defines an addition operator which accepts a string and an object. The object is converted to a string by calling ToString(). This string addition operator is always selected when one of the operands to the addition is a string. A: The second version is converted to a call to String.Concat, which accepts any two objects and returns a string. It is as if you had written this: MessageBox.Show(String.Concat("hoo", i)); A: Your first code snippet doesn't work for obvious reasons. The .Show method expects a string and you are passing it an integer. There's a .ToString() method that you can use: private void button2_Click(object sender, EventArgs e) { int i = 5; MessageBox.Show(i.ToString()); } Now let's consider the following snippet: int i = 5; MessageBox.Show("hoo" + i); that's actually translated by the compiler to: int i = 5; MessageBox.Show(string.Concat("hoo", i)); which is basically the following .Concat overload taking 2 objects as arguments and returning string as result. And because the MessageBox.Show method expects a string it works as that's what the .Concat method I have shown you returns. A: The + operator is overloaded for System.String. If one operand is a string, the other can be any object, and ToString() will be called on that object first. So in the first call, the result is an integer, which cannot be converted implicitly to a string. In the second call, the + operator is called, and the integer is converted to a string, returning in a string. Source: Section 7.7.4 of the C# language specification A: Because in your second example, ("hoo" + i) is interpreted as a string, and your first example passes an int to a string parameter. Execute this code to prove that: Console.WriteLine((5).GetType()); Console.WriteLine(("hoo" + 5).GetType()); A: The MessageBox.Show() method accepts parameter of string type only. In your first case, the parameter is of type int and there's no implicit conversion between int and string. And the code is not compilabel. In the second case, int is converted to string thanks to the + operator defined for string. Here used for concatenation - it works this way when one of the parameteres for + is of type string. So the parameter is automatically converted to string and the code works. And the result is string. A: MessageBox doesn't know what to do with an int as an argument in your first piece of code. But rather it is expecting a string and the string can concat that int to itself via operator+. The MessageBox.Show() can then take that concatenated string and display it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Collision Detection Using AABB or OBB doubts I have readed something about it i wanna to do some implementation using this. But i have a few doubts. The problem with de AABB is that the objects must be axis aligned, otherwise you have to be recalculating the bbox every frame, is that right? Is that recalculation expensive? And what about the precision, can you make a collision tree subdividing the bbox? How it works with AABB? The OBB is oriented to the object rotation, right? You have to build the tree before the game iniatializates. I readed its a lot harder to implement and bit expensive but i gain a lot in precision. But what if the object rotates in the game, does the bbox will recalculate its rotation 'automatically'? Wich one is most used in games and why? Thank you in advance :) A: The choice between AABBs, OBBs, Spheres, Capsules... depends on the kind of simulation you are running and what your constraints (usually real-time applications) are. You need to evaluate pros and cons and do your choice accordingly. For instance, tests with AABBs are very fast, but you need to recompute the AABBs when your object rotates. However, if you are handling very complex objects and deal with BVH, updating an AABB-tree is quite fast since you only need to recompute ("from scratch") the bottom AABBs, the higher ones being constructed from the child AABBs. With OBBs, tests are costlier but you will not need to recompute your OBBs if you are dealing with rigid objects. If you decide to use deformable objects, the AABB tree (or Sphere tree) is definitely a better idea, since your tree will need to be updated anyway. The question is : what will be costlier, the overhead resulting from the updating AABB-tree or from the overlap tests with OBBs? All of this depends on your simulations : objects complexity, average CD tests per sec etc... You can find some benchmarks of different CD libraries based on different methods (BVH, grids...) with different shapes, tested on particular problems. Here is an example that you might find interesting. Concerning the implementation, since all of this has been researched years ago and implemented in many libraries, you should not have any troubles. You could take a look at Real-Time Collision Detection by Christer Ericson, all of those questions are answered and explained very clearly. You can also use a mix between different shapes, e.g. one for the broad phase and another one for the narrow phase (once you reach leaves), but you will probably not need something like this. A: AFAIK, the majority of physics engine uses AABBs + sweep-and-prune algorithm for the broad phase of collision detection. Trees are almost useless for collision detection between dynamic objects. However, the trees can be successfully used for static geometry The problem with de AABB is that the objects must be axis aligned, otherwise you have to be recalculating the bbox every frame, is that right? Yes, AABB must be recalculated on every change of body orientation. But it's a very cheap operation for boxes, capsules, cones, cylinders. For polygonal models is surely more expensive, but AABB computation for low-poly models has a normal performance. All in all, AABB recalculation is better than expensive narrow-phase algorithms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Having Trouble Switching Github accounts on terminal It's been a while since I pushed anything to GitHub. I had initially set up my account on my computer, and everything worked great. Then I changed my account to a client's account (so I could push code to their private repository). It's been a while and now I am changing back to my old account, and I am having trouble. I generated a new rsa_key and pretty much followed the instructions here to a T. However, when I type: ssh -T git@github.com I get: Hi oldincorrectusername! You've successfully authenticated, but GitHub does not provide shell access. I can't push to my repos either, because this old client username isn't authorized. I've doublechecked my ssh keys both on my computer and on my account setting on GitHub. I've also set my global account variables: git config --global user.name "Firstname Lastname" git config --global user.email "your_email@youremail.com" git config --global github.user username git config --global github.token 0123456789yourf0123456789token And still it is giving me the old username. Any suggestions? Thanks, A: The problem is that your local ssh is still offering your “old” SSH key to GitHub. This often comes up when you have one GitHub-recognized key (i.e. your “old” key) loaded in an ssh-agent but want to use a different GitHub-recognized key (i.e. your “new” key). ssh offers keys in this order: * *specified keys that have been loaded into the agent *other keys that have been loaded into the agent *specified keys that have not been loaded into the agent By “specified keys” I mean those keys specified by the -i command line option or the IdentityFile configuration option (which can be given through ~/.ssh/config or the -o command line option). If your “old” key is loaded into the agent, but your “new” key is not, then ssh will always offer your “old” key (from the first or second categories) before your “new” key (only ever in the last category since it is not loaded), even when you specify your “new” key with -i/IdentitiesOnly. You can check which keys are loaded in your ssh-agent with ssh-add -l. If your “old” key is listed, then you can fix the problem by unloading it from your agent (be sure to also unload any other GitHub-recognized keys, except perhaps your “new” key): ssh-add -d ~/.ssh/old_key_file If you are using Mac OS X, the system may be automatically loading your “old” key if you checked “Remember password in my keychain” when prompted for the password at one point; you can disable this automatic loading by deleting the Keychain entry for the key with the command /usr/bin/ssh-add -K -d ~/.ssh/old_key_file. Other systems may do something similar, but the commands to tell them to “stop that” will be different. Instead of unloading the “old” key from your agent, you can set the IdentitiesOnly configuration option to yes, to tell ssh to skip the second category of keys (non-specified agent-loaded keys). Your ~/.ssh/config might include a section like this: Host github.com User git IdentityFile ~/.ssh/id_rsa # wherever your "new" key lives IdentitiesOnly yes This way, it will not matter whether any other GitHub-recognized keys are loaded into your agent; ssh will always offer only your “new” key. If you anticipate needing to access the repositories of both GitHub accounts and you do not want to have to edit the configuration file whenever you want to switch between GitHub accounts, then you might setup your ~/.ssh/config like this: Host clientname.github.com HostName github.com IdentityFile ~/.ssh/client_id_rsa # or wherever your "old" client key lives Host github.com IdentityFile ~/.ssh/id_rsa # or wherever your "new" key lives Host github.com *.github.com User git Hostname github.com IdentitiesOnly yes Then use URLs like github.com:GitHubAccount/repository for your repositories and URLs like clientname.github.com:GitHubAccount/repository for your client’s repositories (you can put the git@ prefix back in if you like, but it is not necessary since the above entries set the User configuration variable).
{ "language": "en", "url": "https://stackoverflow.com/questions/7548158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Anonymous types object creation and passed into MVC# razor view? Q1: What is better shorthand version of the following? Q2: How can I pass anonymous types to my view in mvc3? public ViewResult Index3() { List<T1> ls = new List<T1>(); ls.Add(new T1 { id = 1, title = "t1", val1 = 1, val2 = 2}); ls.Add(new T1 {id=2, title="t2", val1=3, val2=4}); ls.Add(new T1 { id = 3, title = "t3", val1 = 5, val2 = 6}); return View(ls); } (Q1) Something similar to?: List<T1> ls = new List<T1>( List<T1>(new { id = 1, title = "t1", val1 = 1, val2 = 2} new { id = 2, title = "t2", val1 = 3, val2 = 4}) ); (Q2) Something similar to?: public ViewResult Index3() { return View(List(new { id = 1, title = "t1", val1 = 1, val2 = 2 } new { id = 2, title = "t2", val2 = 3, val2 = 4 } ); } Then reference the above in the razor view: @model IEnumerable<Some Anonymous or Dynamic Model> @item.id @item.title @item.val1 ... A: Q1 is a matter of preference. There is no performance difference as the compiler internally creates similar code. Q2 is impossible, you must create a non-anonymous type to be able to access it. A: Could use ViewBag to pass your list to the view. A: * *Collection initializers are written like this: List<T1> ls = new List<T1> { new T1 { id = 1, title = "t1", val1 = 1, val2 = 2 }, new T1 { id = 2, title = "t2", val1 = 3, val2 = 4 }, new T1 { id = 3, title = "t3", val1 = 5, val2 = 6 } }; *Create an implicitly-typed array: return View(new [] { new { id = 1, ... }, ... }); A: Neither option will work as anonymous types are internal and razor views are compiled into a separate assembly. See: Dynamic view of anonymous type missing member issue - MVC3
{ "language": "en", "url": "https://stackoverflow.com/questions/7548167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP program is negating a function? So basically what I have set up here is a very simple and generic log in. I have the entire code copy and pasted because maybe its important somehow. However- $user = mysql_real_escape_string($_POST['User']); $pass = mysql_real_escape_string(md5($_POST['Pass'])); $conn = mysql_connect("localhost", "root") or die(mysql_error()); (mysql_select_db('fireworks', $conn)); $ask = "SELECT * FROM name WHERE (User = '" . $user . "') and (Pass = '" . $pass . "');"; $result = mysql_query($ask); The segment of code below is completely ignored! When I press log in (From the index page) It is suppose to run a series of checks. If the user decides to not put anything inside the user and password text boxes then it is suppose to return the string show below: if (strlen($user) < 1){ if (strlen($pass) < 1){ print "<p class = 'Back'>Epic Fail</p>"; print "<p>You forgot to put in your Username or Password.</p>"; } } (^Up until here) But it doesn't. Instead its just a blank page. But everything else works fine. If I type in a fake user then it returns "YOU FAIL!" If I type a valid user it returns "WELCOME BACK." if (strlen($user) >= 1){ if (mysql_num_rows($result) >= 1) { while ($row = mysql_fetch_array($result)) { print "<p class='Back'>Welcome back</p><p>" . $row['User'] . "</p>"; } }else{ print "YOU FAIL!!!"; } } Any suggestions? EXTRA NOTES: The database is called fireworks the table is called name there are three columns in the name table. nameID, User, and Pass. (Idk how this is useful but sometimes it is.) A: Your code: if (strlen($user) < 1){ if (strlen($pass) < 1){ print "<p>You forgot to put in your Username or Password.</p>"; } } In actual fact, this won't check for $user or $pass being blank; it will only give the error message if both of them are blank. Each test is okay on its own, but the way it's written, the test for $pass will only be run if the $user test has already given a true result. What you need to to is write them together with an or condition, like so: if (strlen($user) < 1 or strlen($pass) < 1){ .... } Hope that helps. A: try this: if (strlen($user) < 1 || strlen($pass) < 1){ .... } A: You're nesting the ifs, so the "Epic Fail" is only displayed when both the user name and password aren't entered. You might want to change it to this: if (strlen($user) < 1 || strlen($pass) < 1) { print "<p class = 'Back'>Notice</p>"; print "<p>You forgot to put in your Username or Password.</p>"; } A: In the documentation of mysql_real_escape_string it says that it will attempt to connect to database for the character set. If you did not connect to database at all before the check it might very well be the case. You can check if error reporting to see if it returned E_WARNING level error. Another thing is that you should avoid database calls when it is not needed. If thats the whole part of the important code, you should call both checks before you try to escape them and continue with database stuff. Also, empty() function might help you as well. if(!empty($_POST['User']) || trim(strlen($_POST['User'])) < 1) { // database stuff }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript not working in Android Webview? I'm trying to make an Android version of a relativly simple iOS app that uses a webview, some buttons and then relies on javascript calls to a CMS. But I'm stuck at a pretty early point of development: The webview doesn't function with javascript.I've read a lot of posts about how to enable JS in an Android webview, but no luck so far. Below is some of my code: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebChromeClient(new WebChromeClient()); mWebView.setWebViewClient(new HelloWebViewClient() { @Override public void onPageFinished(WebView view, String url) { //Calling an init method that tells the website, we're ready mWebView.loadUrl("javascript:m2Init()"); page1(mWebView); } }); mWebView.loadUrl("http://my_url/mobile/iphone//app.php"); } private class HelloWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } public void page11(View view) { mWebView.loadUrl("javascript:m2LoadPage(1)"); } What am I doing wrong here? The URL is working perfectly in my iOS app, and in a browser. But not in my app! Please tell me it's something obvious... A: Loading javascript in webview webView.getSettings().setDomStorageEnabled(true); A: Add the following lines of code in your MainActivity.java It helped me to enable js webSetting.setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient()); webView.setWebViewClient(new WebViewClient()); do not forget about this permission in AndroidManifest file. <uses-permission Android:name="Android.permission.INTERNET" /> A: Did you enable the right internet permission in the manifest? Everything looks fine otherwise. By any chance, have you also tested this code on an actual Android phone? And not just on the emulator? Here is a good tutorial on a slightly different approach. You may want to try that one to see if it works for you. A: In case something with WebView on Android does not work, I always try to make sure I set these crazy flags such as, WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setLoadWithOverviewMode(true); webSettings.setUseWideViewPort(true); webSettings.setBuiltInZoomControls(true); webSettings.setDisplayZoomControls(false); webSettings.setSupportZoom(true); webSettings.setDefaultTextEncodingName("utf-8"); I wonder why these are not set by Default, who would expect webpages without javascript content nowadays, and whats the use having javascript enabled when DOM is unavailable unless specified. Hope someone filed this as a bug or improvement/feature-request already and the monkeys are working on it. and then there is deprecated stuff rotting somewhere, like this: webView.getSettings().setPluginState(PluginState.ON); All this for loading webpages inside app. On iOS, its all so simple - Swift 3.0 private func openURLWithInAppBrowser(urlString:String) { guard let url = URL(string:urlString) else { return } let sfSafari = SFSafariViewController(url:url) present(sfSafari, animated: true, completion: nil) } A: This video (http://youtu.be/uVqp1zcMfbE) gave me the hint to make it work. The key is to save your html and js files in the Android assets/ folder. Then you can easily access them via: webView.loadUrl("file:///android_asset/your_page.html"); A: If you are in Kotlin you can use the following method to get the JavaScript working : webView.apply { loadUrl( "file:///android_asset/frm/my_html_landing_page_here.html" ) settings.javaScriptEnabled = true settings.domStorageEnabled = true } Also make sure that your entire folder is inside the Assets folder (this includes HTML, Javascript and other file needed) A: Xamarin Android also has the same problem that WebView does not execute any Javascript. Follow @computingfreak answer: this.SetContentView(Resource.Layout.activity_main); var webView = this.FindViewById<WebView>(Resource.Id.webView); var webSettings = webView.Settings; webSettings.JavaScriptEnabled = true; webSettings.DomStorageEnabled = true; webSettings.LoadWithOverviewMode = true; webSettings.UseWideViewPort = true; webSettings.BuiltInZoomControls = true; webSettings.DisplayZoomControls = false; webSettings.SetSupportZoom(true); webSettings.DefaultTextEncodingName = "utf-8"; Weirdly enough they changed all setter methods to properties except SetSupportZoom and SupportZoom stays as getter :/ A: FIXED! Spurred on by the error, I found out that I needed to set setDomStorageEnabled(true) for the webview settings. Thanks for your help Stephan :) A: Mainly, these three lines will be enough to make the Javascipt work in webView... webSetting.setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient()); webView.setWebViewClient(new WebViewClient()); If it's not working after that also, then add below line also. webSettings.setDomStorageEnabled(true); Actually, you need both setJavaScriptEnabled() and setWebChromeClient(new WebChromeClient()) to make the JavaScript work. If you will use only webSetting.setJavaScriptEnabled(true); then it won't work. A: Just permit your WebView to run JS, simple like that: WebView web=(WebView)findViewById(R.id.web); web.getSettings().setJavaScriptEnabled(true); A: To enable javascript popups in WebView its necessary to set webChromeClient and override openFileChooser methods. mWebview.setWebChromeClient(new WebChromeClient(){ // For Android 4.1+ @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(acceptType); startActivityForResult(Intent.createChooser(i, "SELECT"), 100); } // For Android 5.0+ @SuppressLint("NewApi") public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (mUploadMessageArr != null) { mUploadMessageArr.onReceiveValue(null); mUploadMessageArr = null; } mUploadMessageArr = filePathCallback; Intent intent = fileChooserParams.createIntent(); try { startActivityForResult(intent, 101); } catch (ActivityNotFoundException e) { mUploadMessageArr = null; Toast.makeText(activity,"Some error occurred.", Toast.LENGTH_LONG).show(); return false; } return true; } }); And handle the onActivityResult as below: @SuppressLint("NewApi") @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 100) { if (mUploadMessage == null) return; Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData(); mUploadMessage.onReceiveValue(result); mUploadMessage = null; } else if (requestCode == 101) { if (mUploadMessageArr == null) return; mUploadMessageArr.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data)); mUploadMessageArr = null; } } A: If nothing above helped try to add delay in WebViewClient.onPageFinished listener override fun onPageFinished(view: WebView?, url: String?) { Handler().postDelayed({ //update your view with js here super.onPageFinished(view, url) }, 1000) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "102" }
Q: Issue with control chars - PHP does not print \t (tab character) i'm sending an XLS file with the header. Everything is working fine. But when i tell it to print the tab to separate the cells in the XLS by print \t. It does not prints the tab. It just prints the '\t' in the file and when i download the XLS file everything that should be in different cell is all in one cell with text like: val1\tval2\tval3\t Those three values should be separate in their separate cells. i have been trying for 2 hours now nothing is working :(. i send headers like this: header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=".$filename.$fileextention); header("Pragma: no-cache"); header("Expires: 0"); and just print the values like echo $val1 . '\t' . $val2 . '\t' . $val3; i have tried using single or double quts. and print and echo both buy still :( A: Try this (see quotes) header('Content-type: application/vnd.ms-excel'); echo "val1\tval2\tval3"; A: I'm quite sure that quotes cause the issue. echo $val1 . "\t" . $val2 . "\t" . $val3; should do the thing. Just look at this: <?php echo 'Test\tTest'; echo "\r\n"; echo "Test\tTest"; echo "\r\n"; which outputs: Test\tTest Test Test Use double quotes when you need control chars. Hopefully this can solve your problem. A: Use double quotes: "\t". Within single quotes only \\ and \' is recognised. A: This should work: echo $val1 . "\t" . $val2 . "\t" . $val3; If it doesn't, it's a bug in PHP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add a % sign and color it I have a datagrid column with numbers in it. How do I: 1. add a '%' sign at the end of each number in the column AND 2. make the color either red or green depending on if the number is less than or greater than 0, respectively. I've been able to do 1 or the other but not both. Here is what I have, which does #2 but not #1: // my datagrid column: <mx:AdvancedDataGridColumn dataField="change" itemRenderer="itemrenderers.ColorRenderer" /> // my item renderer: package itemrenderers { import mx.controls.Label; import mx.controls.dataGridClasses.DataGridListData; public class ColorRenderer extends Label { override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); if (data && data[DataGridListData(listData).dataField] < 0) { setStyle( "color", 0xA41330 ); //red } else { setStyle( "color", 0x59A336 ); //green } } } } A: Try putting this method in your item renderer class. It should fulfill your requirements: override public function set data(value:Object):void { super.data = value; if (value) { var fieldValue:Number = value[DataGridListData(listData).dataField] as Number; text = String(fieldValue) + "%"; if (fieldValue < 0){ setStyle( "color", 0xA41330 ); //red }else{ setStyle( "color", 0x59A336 ); //green } } } Regards. A: If your code is coloring the label correctly, this should work. // my datagrid column: <mx:AdvancedDataGridColumn dataField="change" itemRenderer="itemrenderers.ColorRenderer" /> // my item renderer: package itemrenderers { import mx.controls.Label; import mx.controls.dataGridClasses.DataGridListData; public class ColorRenderer extends Label { override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); if (data && data[DataGridListData(listData).dataField] < 0) { setStyle( "color", 0xA41330 ); //red } else { setStyle( "color", 0x59A336 ); //green } text = (data[DataGridListData(listData).dataField] as String) + "%"; } } } A: Use datagrid column stylefunction and labelfunction. With stylefunction you can toggle color and with labelfunction you can add % character to your data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I break down a view in a flex application? I've written a flex (mobile) application, that ended up bigger than I expected. I'm pretty happy with all my classes and everything on my AS files. However, the view turned out really big, as I'm using MXML to layout my app. I was thinking about creating external components I could call on my view to make it more readable, but am not sure what's the best way to do, or if doing so is the best way at all. As an example, I have in my view a v:Group with the following: <s:VGroup width="100%" height="80%" includeIn="normal" horizontalAlign="center" top="70" id="imageGroup"> <s:Label id="lblFile" visible="false" width="98%" textAlign="center" includeInLayout="true" color="0xFFFFFF"/> <s:BorderContainer id="framingBorder" borderColor="0xFFFFFF" borderWeight="15" cornerRadius="7"> <s:Image id="image" source="{IMAGE_SAMPLE}" horizontalCenter="0"/> </s:BorderContainer> <s:BorderContainer id="shareBorder" borderColor="0xFFFFFF" borderWeight="5" height="30" cornerRadius="7" width="{framingBorder.width}" visible="false" buttonMode="true" click="copyToClipboard(lblURL.text)"> <s:layout> <s:HorizontalLayout verticalAlign="middle" horizontalAlign="left" gap="3"/> </s:layout> <s:Label text="url:" styleName="copyURL" /> <s:BorderContainer borderColor="0xCDCDCD" borderWeight="1" width="{lblURL.width + 5}" height="{lblURL.height + 5}"> <s:layout> <s:HorizontalLayout verticalAlign="middle" horizontalAlign="center"/> </s:layout> <s:Label id="lblURL" text="" styleName="copyURL" /> </s:BorderContainer> <s:Spacer width="100%" /> <s:HGroup> <s:Label color="0xFF0000" text="copy" styleName="copyURL" /> <s:Image source="/assets/icons/page_copy_small.png" horizontalCenter="0" horizontalAlign="right"/> </s:HGroup> </s:BorderContainer> </s:VGroup> Could anyone point me to the right direction as to how I can move this out from the view to make it cleaner, and how to still have access to items inside this block of code (i.e. I would still like to be able to modify lblURL from my view as this is a dynamic value) Thanks in advance, A: You're on the right track, and the link Amy posted has a good example of how to lay it out. You might also be interested in cairngorm and parsely, which are frameworks/tools for a more complete solution. But for now I think just separating parts of your view into components is a good start. You can still modify your label in the main app (e.g.): <views:myBox id="box" /> <s:Button click="{box.myLabel.text = 'changed'}" /> myBox.mxml: <?xml version="1.0" encoding="utf-8"?> <s:BorderContainer xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300"> <s:Label id="myLabel" text="this is my label" /> </s:BorderContainer>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS to keep div to the size of content I have code like this: <div class='outer'> <div class='imgwrapper'><img /></div> <div class='caption'>This is a long caption that should wrap...</div> </div> What I want is for the outer div to be the width of the image so that the caption under it wraps to the width of the image. The images are all different sizes but the size cannot be accessed in code to give absolute pixel sizes. The css has to work for different sizes. I cannot change the structure of the divs. Can this be done? A: Try this: HTML <div class="box"> <img src="http://static.howstuffworks.com/gif/moon-landing-hoax-1.jpg" /> <div class="caption"> Caption </div> </div><br /> <div class="box"> <img src="http://static.howstuffworks.com/gif/moon-landing-hoax-1.jpg" style="width:200px; height:200px;"/> <div class="caption"> Caption </div> </div><br /> <div class="box"> <img src="http://static.howstuffworks.com/gif/moon-landing-hoax-1.jpg" style="width:75px; height:75px;"/> <div class="caption"> Caption </div> </div> CSS .box { overflow:hidden; background-color:#ddd; display:inline-block; } img { padding:10px; } Demo http://jsfiddle.net/andresilich/8Bsgg/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7548188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find current position I have the following situation which I can't figure out. I have a menu as follows: <ul id="top"> <li><a href="" title="">Link 1</a> <ul id="sub1"> <li><a href="" title="">Sub 1.1</a></li> <li><a href="" title="">Sub 1.2</a></li> </ul> </li> <li><a href="" title="">Link 2</a> <ul id="sub2"> <li><a href="" title="">Sub 2.1</a></li> <li><a href="" title="">Sub 2.2</a></li> </ul> </li> [..] </ul> Now I want the according submenu to show when a link is hovered. Herefore I have the following approach (to test it). $("#top li").live("mouseover mouseout", function(event){ if(event.type == "mouseover"){ $(this).closest("ul").show(); }else{ $(this).closest("ul").hide(); } }); But that doesn't work. Apparently the mouseover event is not triggered on the Link 1 hyperlink, because when I change $(this).closest("ul").show(); to alert($(this).attr("title")); (assuming that in my working document there is an actual title description) I get an empty alert window. How do I fix this? Oh, forgot to mention that I use live(), because further on I need to do some stuff with elements that are currently hidden. A: Try find() instead of closest().
{ "language": "en", "url": "https://stackoverflow.com/questions/7548191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Simulating Fiddler requests in buffering mode in C# I am building a web scraping or crawler C# .NET application that keeps sending requests to a server to collect some information. The problem is that for certain web pages for this specific server that web response is always a 404 not found. However surprisingly enough I've discovered that as long as "Fiddler" is working the problem seems to vanish and the request returns with a successful response. I've been searching the web since seeking an answer but found none. On a brighter side, after searching the web and analysing Fiddler's timeline feature I have came to some conclusions. 1.Fiddler loads these web pages using Buffered mode while my application uses Stream mode. 2.It also appears that Fiddler reuses the connection or in other word Keep-Alive is set to be true. And now the question is how can I mimic or simulate the way Fiddler loads the web response in Buffered mode, and whether Fiddler actually does some trick (i.e modifies the response) to get the correct response. I am using HttpWebRequest and HttpWebResponse to request my pages. I need a way to buffer httpwebresponse completely before returning data to client(which is my server). public static String getCookie(String username, String password) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("certain link"); request.UserAgent = "Mozilla/5.0 (Windows NT 6.0; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"; request.Credentials = new NetworkCredential(username, password); HttpWebResponse wr = (HttpWebResponse)request.GetResponse(); String y = wr.Headers["Set-Cookie"].ToString(); return y.Replace("; path=/", ""); } /// <summary> /// Requests the html source of a given web page, using the request credentials given. /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="webPageLink"></param> /// <returns></returns> public static String requestSource(String username,String password,String webPageLink){ String source = ""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webPageLink); if (username != null && password != null) { request.Headers["Cookie"] = getCookie(username, password); request.UserAgent = "Mozilla/5.0 (Windows NT 6.0; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"; request.Credentials = new NetworkCredential(username, password); } StreamReader sr; using (HttpWebResponse wr = (HttpWebResponse)request.GetResponse()) { sr = new StreamReader(wr.GetResponseStream()); source = sr.ReadToEnd(); } return source; } A: Did you try to take a look at the HttpWebRequest's AllowWriteStreamBuffering property? Also you could try to append all the Fiddler's headers to your request to be as close to Fiddler as you can. A: Could it be that your scraper is being detected and shut down and Fiddler slows it enough so it doesn't get detected? http://google-scraper.squabbel.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7548194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why isn't z-index working in IE? I've created a top level menu with dropdowns but the drop down isn't coming to the front in IE. Chrome, FF, and Safari work great. My code looks like this: <li id="search"><a href="#search" class="drop" >Search</a> <div class="drop2columns dropcontent"> <div class="col_2"> <ul> <li id="search_basic"><a href="#test1">Test1</a></li> <li id="search_advanced"><a href="#test2">Test2</a></li> </ul> </div> </div> </li> The css files look like this: #menu .drop2columns {width: 130px;} #menu .col_2 { display:inline; float: left; position: relative; margin-left: 15px; margin-right: 15px; z-index: 9999; } #menu .col_2 {width:130px;} What am I missing? Like I said this only happens with IE (versions 7,8, and 9) A: z-index doesn’t work correctly in Internet Explorer: positioned elements create a new stacking context, starting with a z-index of 0. To get around this you can make the parent element positioned (e.g., position: relative), and set its z-index to a value higher than that of the child. A: z-index and IE was always a nightmare. There's several workarounds about, see http://brenelz.com/blog/squish-the-internet-explorer-z-index-bug/ for one of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I stop authentication of my paypal account using adaptive payments? Using the Adaptive Payments with the Pay method I managed to get a script working where a user can deposit money from my account to theirs through php but I have to enter my password even though it is using my api credentials. How can I stop it from asking me for my password every time? This is my code: <?php require_once '../../../lib/AdaptivePayments.php'; require_once 'web_constants.php'; session_start(); try { $serverName = $_SERVER['SERVER_NAME']; $serverPort = $_SERVER['SERVER_PORT']; $url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']); $returnURL = $url."/PaymentDetails.php"; $cancelURL = $url. "/SetPay.php" ; $currencyCode="USD"; //$_REQUEST['currencyCode']; $email="qwom_1315508825_biz@btinternet.com"; $preapprovalKey = ''; $requested=''; $receiverEmail=''; $amount=''; $count= count($_POST['receiveremail']); //pay details// $payRequest = new PayRequest(); $payRequest->actionType = "PAY"; $payRequest->currencyCode = "USD"; $receiver1 = new receiver(); $receiver1->email = "cam_1315509411_per@btinternet.com"; $receiver1->amount = "5.00"; $payRequest->receiverList = new ReceiverList(); $payRequest->receiverList = array($receiver1); $payRequest->returnUrl = $returnURL; $payRequest->senderEmail = "qwom_1315508825_biz@btinternet.com"; $payRequest->feesPayer = "SENDER"; $payRequest->cancelUrl = $cancelURL; $payRequest->requestEnvelope = new RequestEnvelope(); $payRequest->requestEnvelope->errorLanguage = "en_US"; $payRequest->requestEnvelope->detailLevel = "ReturnAll"; //end pay details// $ap = new AdaptivePayments(); $response=$ap->Pay($payRequest); if(strtoupper($ap->isSuccess) == 'FAILURE') { $_SESSION['FAULTMSG']=$ap->getLastError(); $location = "APIError.php"; header("Location: $location"); } else { $_SESSION['payKey'] = $response->payKey; if($response->paymentExecStatus == "COMPLETED") { $location = "PaymentDetails.php"; header("Location: $location"); } else { /*$token = $response->payKey; $payPalURL = PAYPAL_REDIRECT_URL.'_ap-payment&paykey='.$token; header("Location: ".$payPalURL);*/ echo $response->paymentExecStatus; } } } catch(Exception $ex) { $fault = new FaultMessage(); $errorData = new ErrorData(); $errorData->errorId = $ex->getFile() ; $errorData->message = $ex->getMessage(); $fault->error = $errorData; $_SESSION['FAULTMSG']=$fault; $location = "APIError.php"; header("Location: $location"); } ?> It uses the Adaptive Payments Soap API. The credentials are in the included files. A: That's intended functionality. Since you're using the Pay method, it naturally assumes it's a normal transaction rather than a 'deposit'. You'd want to look at the PayPal MassPay API instead. See https://www.x.com/developers/paypal/products/mass-pay as well as https://www.x.com/developers/paypal/documentation-tools/api/masspay-api-nvp for the NVP API documentation. There's also some sample code up at https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_code (php sample here)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I make my .NET or Crystal Reports editable? Is there any way to print the custom positioned text? I want to make a report, in which I want that user must be able to reposition the labels, text or images with his own choice. I am actually making a cheque maker software in Windows Forms .NET 4, and for different banks there needs different positions but same attributes, because we have to print on cheques of different banks so each one has different position of signature field, name field, money field, etc. So is there any option in any report or Crystal Reports that once we generate a report, we may able to move the labels with drag and drop, and can we adjust the text by drag and drop once the report is shown in the report viewer? A: You would not want to use report generation for check printing. Check printing is "forms" generation, not "report" generation. They're fundamentally different concepts. A: Once the report is generated, the user won't be able to adjust its fields' locations. Keeping this in mind, you have a few options: * *You could, however, group the report by bank, then add a section for each bank's fields and positioning. Use a conditional suppression formula on each section to show the section for the related bank. If you have a lot of clients (50+), this approach might be a bit hard to maintain. *CR does support some limited field positioning based on conditional logic (X and width), but it may not be as flexible as you need. You'd probably want to keep the fields' location in a table so that you could (attempt) to use this to position the fields when the report is generated. *use the report-application server (RAS) SDK--it has finely-grained control of report elements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: JSON format problem when using Factual geo data I'm using Factual api to fetch location data. Their restful service return data in JSON format as follow, but they are not using "usual" JSON format. There's no attribute key, instead, there's a “fields” that explains all the field keys. So the question is how to retrieve the attribute I need? Please give an example if possible. Thanks in advance. { "response": { "total_rows": 2, "data": [ [ "ZPQAB5GAPEHQHDy5vrJKXZZYQ-A", "046b39ea-0951-4add-be40-5d32b7037214", "Hanko Sushi Iso Omena", 60.16216, 24.73907 ], [ "2TptHCm_406h45y0-8_pJJXaEYA", "27dcc2b5-81d1-4a72-b67e-2f28b07b9285", "Masabi Sushi Oy", 60.21707, 24.81192 ] ], "fields": [ "subject_key", "factual_id", "name", "latitude", "longitude" ], "rows": 2, "cache-state": "CACHED", "big-data": true, "subject_columns": [ 1 ] }, "version": "2", "status": "ok" } A: // Field map var _subject_key = 0, _factual_id = 1, _name = 2, _latitude = 3, _longitude = 4; // Example: alert(_json.response.data[0][_factual_id]); Demo: http://jsfiddle.net/AlienWebguy/9TEJJ/ A: If you know the field name, and the data isn't guaranteed to stay in the same order, I would do a transform on the data so I can reference the fields by name: var fieldIndex = {} for (key in x.response.fields) { fieldIndex[x.response.fields[key]] = key; } for (key in x.response.data) { alert(x.response.data[key][fieldIndex.name]); } A: I work at Factual. Just wanted to mention that we've launched the beta of version 3 of our API. Version 3 solves this problem directly, by including the attribute keys inline with the results, as you would hope. (Your question applies to version 2 of our API. If you're able to upgrade to version 3 you'll find some other nice improvements as well. ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Macro with zero arguments - with or without parentheses When defining macro with zero arguments we can define it with parentheses, thus looking more like function or without parentheses. What is preferable (probably there's no right answer) way of doing it? A: If you intend to create a macro that mimics a function, then use the () version. Otherwise don't. A: As a general rule, I would expect MACRO() to generate executable code, which may have side-effects. I use MACRO (sans parentheses) for more structural things that yield declarations, boilerplate, or constants. A: Yes, we can and I don't think that there's really any particular technical reason why one is better than the other. However, conventionally we would omit the () where not required.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Refactoring of many if statements for params[...], inside controller action I have such code, for making chain selects in my form View for index action: <%= form_tag do %> <%= collection_select(*@brands_select_params) %> <%= collection_select(*@car_models_select_params) %> <%= collection_select(*@production_years_select_params) %> <% # Пока еще никто ничего не выбрал %> <%= submit_tag "Send", :id => "submit", :name => "submit" %> And my controller: class SearchController < ApplicationController def index @brands = Brand.all @car_models = CarModel.all if (params[:brand].blank?) @brands_select_params = [:brand, :id, @brands, :id, :name, :prompt => "Выбирай брэнд"] if params[:car_model].blank? @car_models_select_params = [:car_model, :id, @car_models, :id, :name, { :prompt => "Model" }, \ { :disabled => "disabled" }] @production_years_select_params = [:production_year, :id, @car_models, :id, :name, { :prompt => "Year" }, \ { :disabled => "disabled" }] end else @brands_select_params = [:brand, :id, @brands, :id, :name, { :selected => params[:brand][:id] } ] if params[:car_model].blank? @car_models_select_params = [:car_model, :id, Brand.find(params[:brand][:id]).car_models, :id, :name, \ { :prompt => "And model now" } ] @production_years_select_params = [:production_year, :id, @car_models, :id, :name, { :prompt => "Year" }, \ { :disabled => "disabled" } ] else @car_models_select_params = [:car_model, :id, Brand.find(params[:brand][:id]).car_models, :id, :name, \ { :selected => params[:car_model][:id] } ] unless params[:car_model][:id].empty? @production_years_select_params = [:production_year, :id, CarModel.find(params[:car_model][:id]).production_years, :id, :year, \ { :prompt => "And year now" } ] unless params[:car_model][:id].empty? end end end end As you can see, too many ifs in my controller code. And i gonna add more conditions there. After that anyone who read that code will get brain corruption. So i just wanna make it in real Ruby way, but don't know how. Please, help, guys. How should i refactor this bunch of crap? A: I think a big part of the problem is you're doing too much in your controller. Generating markup (and IMO that includes building parameter lists for form helpers) should be done in views and view helpers. So: module SearchHelper def brand_select brands, options={} collection_select :brand, :id, brands, :id, :name, :options end def car_model_select car_models, options={} collection_select :car_model, :id, car_models, :id, :name, options end def production_year_select years, options={} collection_select :production_year, :id, years, :id, :year, options end end Then you can cut your controller down to this: def index @brands = Brand.all @car_models = CarModel.all @selected_brand_id = params[:brand] && params[:brand][:id] @selected_car_model_id = params[:car_model] && params[:car_model][:id] @production_years = @selected_car_model_id ? [] : CarModel.find(@selected_car_model_id).production_years end And in your view: <%= brand_select @brands, :prompt => "Выбирай брэнд", :selected => @selected_brand_id %> <%= car_model_select @car_models, :prompt => "Model", :selected => @selected_car_model_id %> <%= production_year_select @production_years, :prompt => "Year", :selected => @selected_car_id %> I suspect you could simplify this even more using form_for and fields_for and get rid of the helpers entirely, but it depends a bit on how your model associations are set up. A: There is no obvious solution to this kind of problem. Generally, I try to keep the if / else architecture very clear and export all code into separate methods. 2 advantages here: * *readability *easier unit testing For your case, it would be: class SearchController < ApplicationController def index @brands = Brand.all @car_models = CarModel.all if (params[:brand].blank?) @brands_select_params = [:brand, :id, @brands, :id, :name, :prompt => "Выбирай брэнд"] if params[:car_model].blank? @car_models_select_params, @production_years_select_params = get_card_model(@car_models) end else @brands_select_params = [:brand, :id, @brands, :id, :name, { :selected => params[:brand][:id] } ] if params[:car_model].blank? @car_models_select_params, @production_years_select_params = foo_method(@car_models) else @car_models_select_params, @production_years_select_params = bar_method end end end def get_card_model car_models [ [:car_model, :id, car_models, :id, :name, { :prompt => "Model" }, { :disabled => "disabled" }], [:production_year, :id, car_models, :id, :name, { :prompt => "Year" }, { :disabled => "disabled" }] ] end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7548215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to read .arff file with R? Is there any way to do that? Yes, i'm new to R. A: If you only care about the data and not the relations, you can just use: read.csv("data.arff", header=FALSE, comment.char = "@") A: The easiest way to do it is using the "RWeka" library which has read.arff() function that reads .arff files. library(RWeka) test=read.arff("../Test/test.arff") Hope this helps. A: read.arff in package foreign reads data from Weka Attribute-Relation File Format (ARFF) files. Update: there is a new package on CRAN: farff: A Faster 'ARFF' File Reader and Writer A: In general the answer to questions like this can be found via the sos package, which accesses a full-text search of all the packages on CRAN. install.packages("sos") library("sos") findFn("arff") finds functions in the foreign (as noted above) and RWeka packages. Since foreign is a recommended package, it will be installed on your system by default. Hence you would have found the answer with help.search("arff") in the first place, without installing the sos package. sos is still worth having for times when the string you are searching for isn't in the metadata (title, keywords, alias, etc.), which is all that help.search searches, or not in a package you already have installed on your system (ditto). (Looking through the R Data Import/Export Manual, which also comes with your system, is generally useful but would not have found the answer to this question ...) It might be useful to know about the RWeka version on the off chance that the version in foreign (which you should try first) fails for some reason. A: Even though this question is already answered I realize there is another noteworthy solution. Check the RWeka package that enables you to read and write arff files. Plus it gives you a wrapper for Weka functions. So you could use Weka functionality without installing Weka itself (though it installs .jars). See also this doku -> read.arff.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: encoding PHP array to Javascript (JSON) how do I get [{}] in JSON? If I encode array() in PHP, the JSON result is []. What is [{}] in JS anyway? Thanks A: you can use: array(new stdClass) which when json_encoded, should end up to be [{}] To answer your second question of "what is [{}] anyway?", well it is simple: it's an array, whose only element is an object with no members in it. A: [{}] is an array containing an object. JSON is an object and you can have a JSONArray within it and more objects within that. Don't overthink the data structure :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: retrieving URL in iOS app I need to display a homepage in my iPad application. I have been reading the URL Loading information on the Apple Developer site and am confused. In the sample code for SimpleURLConnections, they have a Python server. A colleague mentioned that it should be just a couple lines of code, so clearly I am missing something. There must be an easier way to do this, but I'm at a loss as to what that is. A: It should be easy loading an external browser with cocoa touch. You could use UIWebview with your own browser, but it's easier this way. This is from my own app: - (IBAction)doSupportURL { [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://webpages.charter.net/apollosoftware/support/"]]; } with UIWebView see loadRequest
{ "language": "en", "url": "https://stackoverflow.com/questions/7548222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: openssl error : implicit declaration of MD5Init First of all I am showing the code for my c file .. #include <stdlib.h> #include <sys/types.h> #include <netinet/in.h> #include <memory.h> #include <string.h> #include <ctype.h> #include "sendip_module.h" #include "ipv6ext.h" #include "../ipv6.h" #include "../ipv4.h" #include "ah.h" #include "esp.h" #include "crypto_module.h" #include <openssl/hmac.h> #include <openssl/md5.h> /* code for hmac_md5 here.... void hmac_md5(text, text_len, key, key_len, digest) unsigned char* text; /* pointer to data stream */ int text_len; /* length of data stream */ unsigned char* key; /* pointer to authentication key */ int key_len; /* length of authentication key */ caddr_t digest; /* caller digest to be filled in */ { MD5_CTX context; unsigned char k_ipad[65]; /* inner padding - * key XORd with ipad */ unsigned char k_opad[65]; /* outer padding - * key XORd with opad */ unsigned char tk[16]; int i; /* if key is longer than 64 bytes reset it to key=MD5(key) */ if (key_len > 64) { MD5_CTX tctx; MD5Init(&tctx); MD5Update(&tctx, key, key_len); MD5Final(tk, &tctx); key = tk; key_len = 16; } /* * the HMAC_MD5 transform looks like: * * MD5(K XOR opad, MD5(K XOR ipad, text)) * * where K is an n byte key * ipad is the byte 0x36 repeated 64 times * opad is the byte 0x5c repeated 64 times * and text is the data being protected */ /* start out by storing key in pads */ bzero( k_ipad, sizeof k_ipad); bzero( k_opad, sizeof k_opad); bcopy( key, k_ipad, key_len); bcopy( key, k_opad, key_len); /* XOR key with ipad and opad values */ for (i=0; i<64; i++) { k_ipad[i] ^= 0x36; k_opad[i] ^= 0x5c; } /* * perform inner MD5 */ MD5Init(&context); /* init context for 1st * pass */ MD5Update(&context, k_ipad, 64); /* start with inner pad */ MD5Update(&context, text, text_len); /* then text of datagram */ MD5Final(digest, &context); /* finish up 1st pass */ /* * perform outer MD5 */ MD5Init(&context); /* init context for 2nd * pass */ MD5Update(&context, k_opad, 64); /* start with outer pad */ MD5Update(&context, digest, 16); /* then results of 1st * hash */ MD5Final(digest, &context); /* finish up 2nd pass */ } */ /* rest of the program logic... */ I have already included ...<.path where openssl is installed.....>../openssl/include to C_INCLUDE_PATH and exported it. and now when i try to compile it getting error : $ make gcc -o xorauth.so -I.. -fPIC -fsigned-char -pipe -Wall -Wpointer-arith -Wwrite-strings wstrict-prototypes -Wnested-externs -Winline -Werror -g -Wcast-align - DSENDIP_LIBS=\"/usr/local/lib/sendip\" -shared xorauth.c ../libsendipaux.a ../libsendipaux.a cc1: warnings being treated as errors xorauth.c:34:1: error: function declaration isn’t a prototype xorauth.c: In function ‘hmac_md5’: xorauth.c:56:17: error: implicit declaration of function ‘MD5Init’ xorauth.c:56:17: error: nested extern declaration of ‘MD5Init’ xorauth.c:57:17: error: implicit declaration of function ‘MD5Update’ xorauth.c:57:17: error: nested extern declaration of ‘MD5Update’ xorauth.c:58:17: error: implicit declaration of function ‘MD5Final’ xorauth.c:58:17: error: nested extern declaration of ‘MD5Final’ make: *** [xorauth.so] Error 1 if required I will edit the other implementation details I have skiped them just to make the post small because I think there is something which i need to do regarding include path and header files and i am unaware of it. What is going wrong please help me ??? A: There is no MD5Init function in OpenSSL. (There is in the BSD implementation.) man MD5_Init (note the underscore), or see here. EDIT: Now that you've shown us the offending code, I can also help with the "not a prototype" message. You have (edited a bit): void hmac_md5(text, text_len, key, key_len, digest) unsigned char* text; int text_len; unsigned char* key; int key_len; caddr_t digest; { /* ... */ } That's an old-style, or "K&R", function definition. It's still valid, but only for backward compatibility, and it means that the compiler won't be able to warn you about calls with the wrong number or type(s) of arguments. The modern (since 1989) version is: void hmac_md5(unsigned char *text, int text_len, unsigned char *key, int key_len, caddr_t digest) { /* ... */ } When converting old-style function declarations and definitions to use prototypes, you sometimes have to be careful about parameters with narrow types (float, and integer types narrower than int or unsigned int) due to the promotion rules. That doesn't apply in this particular case. Note that you can leave the definition as it is if you like. Since you got the code from an internet draft, that might even be a good idea (if it ain't broke, don't fix it) -- but as I said you'll get no help from the compiler if you call it with the wrong number or type(s) of arguments.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Firefox calling jquery val throws "NS_ERROR_DOM_SECURITY_ERR" Calling following code in Firebug console in firefox throws 1000 "NS_ERROR_DOM_SECURITY_ERR" exception, dont know why and how. tried putting code in the file in the server to avoid different domain issue, But that also did not work . $("input[type='file']").val('c:\temp\pngs\UA_text_logo.png'); A: For security reasons browsers forbid you from setting the value of an input[type='file'] field. So it's normal that you get this error. You are attempting an unauthorized operation. You can read the filename that has been selected by the user but you cannot set its value. A: You can't set value of file input in any browser. In addition you can't invoke click programatically in firefox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Non alpha-numeric characters in URL If I visit http://†.com in Chrome or Internet Explorer, it will bring me to http://xn--lvg.com. I know it doesn't work in Opera, Safari, and Firefox. Why does † gets translated to xn--lvg? What's the relation between them? Is there a list that maps these weird characters to their translated equivalents in Chrome or Internet Explorer? A: It is the punycode representation. Here is the relevant RFC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Swingworker instances not running concurrently My computer has 4 cores and I am running a Java swing gui program. When I run my application it only uses two cores and about 30% CPU utilization. I have a large number of files to process and want to split them up into two threads to get this task done faster using more cpu. I have a SwingWorker class called PrepareTask, that has a constructor with two ints: class PrepareTask extends SwingWorker<Void, Void> { int start, end; PrepareTask (int start, int end) { ... } ... public Void doInBackground() {... } public void done() { ... } I create two instances of this like: PrepareTask prepareTask = new PrepareTask(0,numberOfFiles/2); prepareTask.execute(); PrepareTask prepareTask2 = new PrepareTask(numberOfFiles/2, numberOfFiles); prepareTask2.execute(); Both are launched (it appears) but when it runs I can see (print stmts) that the first prepare has to finish (print stmts inside) before the second one starts. And the CPU utilization is the same as before, about 30%. They both of course grab data from the same source, a DefaultTableModel. Any ideas on how to do this or what I am doing wrong? thanks. A: This is the result of a change in SwingWorker behaviour from one Java 6 update to another. There's actually a bug report about it in the old SUN bug database for Java 6. What happened was SUN changed the original SwingWorker implementation from using N threads, to using 1 thread with an unbounded queue. Therefore you cannot have two SwingWorkers run concurrently anymore. (This also creates a scenario where deadlock may occur: if one swingworker waits for another which waits for the first, one task might enter a deadlock as a result.) What you can do to get around this is use an ExecutorService and post FutureTasks on it. These will provide 99% of the SwingWorker API (SwingWorker is a FutureTask derivative), all you have to do is set up your Executor properly. A: Maybe Swing is controlling the scheduling of your threads? Or maybe SwingWorker has a thread pool size of 1 (there is no description in SwingWorker javadoc about running multiple SwingWorker threads and I guess multiple threads could cause some difficult concurrency problems in Swing). If all you want to do is run some processing in parallel, can you solve this the simple way by extending the Java Thread class, implementing run, calling SwingUtilities.invokeLater() at the end to update the GUI with any changes: class PrepareTask extends Thread { PrepareTask (int start, int end) { ... } public void run() { ... ; SwingUtilities.invokeLater(new Runnable() { public void run() { do any GUI updates here } )} start the threads with: prepareTask.start(); Or maybe something in your data model is single-threaded and blocking the second thread? In that case, you have to solve that problem with the data model.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Is there a CSS workaround for Firefox' bug: inline-block + first-letter with changed size It's better to see a bug for yourself in Firefox: http://jsfiddle.net/kizu/btdVd/ The picture, showing the bug: And the bug filled in 2007 on bugzilla. The bug appears when you're adding ::first-letter pseudo-element with display: inline-block, and then change the font-size of this first-letter. More letters in a word after the first: more extra space added (or subtracted — if the font-size is lesser than block's). Adding float: left to the first-letter inverts the bug: with bigger font-size the width of inline-block shrinks. So, the question: is there any CSS-only workaround for this bug? It's somewhat killing me. A: I don't think there's a good solution. I have come up with a flaky solution for you though: .test:first-letter { font-size: 2em; letter-spacing: -0.225em; } Add the letter-spacing style to the :first-letter selector in your Fiddle, and you'll find the blocks go back to roughly the right size. Explanation: Basically, the bug is being caused by the whole block taking its size from the font specified in the first-letter. What I'm doing here with the letter-spacing is trying to adjust the size of this font, without affecting it's physical appearance. Adjusting the letter spacing in this way in normal text would result in the letters overlapping each other by .225 of a character width on either side. I was initially hoping that a value of -0.25 would be sufficient -- ie a quarter of a character on each side would reduce the width of each character by half, which would be what we want because the first letter is font-size:2em, so it's twice as big. However, the calculation isn't quite as clean as that, because the first and last characters in the string would only be overlapped on one side each, and because the first letter does in fact want to be double width, even if the rest of the characters don't. All of this means that the exact letter-spacing value required to counter-act the bug will vary depending on how long the text, as well as the font sizes of the original text and the first letter. This is why I had to experiment a bit with the value of the letter spacing to get it working, and also explains why I couldn't get quite a perfect fit on all the text rows in your Fiddle. I would have needed a slightly different value for each block. The value of -0.225 seems to be about the closest I can get to it being right for all your examples, but in practice you'll need to adjust it to suit your site. Don't forget also that this is a Firefox bug, and therefore you'll need to write it in as a browser-specific hack of some sort. And be careful to keep an eye on the Firefox bug report you linked; when it does get fixed, you'll need to work out a way to keep your hack in place for users of old versions, but remove it for users with the fix. [EDIT] The only other working solution I've come up with is simply not to use the features which trigger the bug. ie drop the :first-letter selector, and use a separate <span> for the first letter of your text if you want to style it differently. This is the obvious answer really, and would of course solve the problem (and would also mean that your styled first letter works in older browsers), but it would not be ideal from a semantic perspective, and more importantly doesn't actually answer the question, which is why I didn't offer it as a solution in my original answer. I have been trying to find alternative work around for the bug as well, but the options are limited, and nothing I've tried has given as good results as my initial suggestion. I tried a hack of making the :first-letter invisible, and using :before to display the big leading capital letter. However, this didn't work for me. I didn't linger on it too long so you may be able to get it working, but there is a problem with it in that you'd have to define the leading letter in your CSS, which wouldn't be ideal. Another possible solution is to use the CSS font-stretch: condensed; property on the :first-letter. This would reduce the width of the first letter back to 1em, and thus resolve the width issue of the rest of the text. The down sides of this, however, are that firstly it would make the leading letter look squashed, which is probably not what you want, and secondly this style only works for fonts which support the condensed property. It turns out that this isn't well supported by the standard fonts, so may not be workable for you. In the end, the original letter-spacing solution is still the only way I've found to really work around the bug. A: I've found that triggering reflow on the whole page (or any block with a problem) fixes the problem, so I've found a way to trigger it on every such block with one-time CSS animation: http://jsfiddle.net/kizu/btdVd/23/ Still, while this fix have no downsides in rendering, it have some other ones: * *it would work only for Fx5+ (that supports animations); *it still flashes the original bug for a few ms, so it's maybe somewhat blinky. So, it's not an ideal solution, but would somewhat help when Fx4- would be outdated. Of course, you can trigger such fix onload with JS, but it's not that nice. A: This bug still exists, but some of the fixes don't work anymore. Even after triggering a reflow with an animation, the inline-block returned to the same size for me. I couldn't use the letter-spacing trick because I am already using it on the first letter, that is what is causing the problem for me. I solved the problem by adding this to the CSS for the affected selector: -moz-padding-end: *number of pixels to compensate*; At the moment, moz-padding-end seems to be specific to Firefox, and it can add or remove width to the end of the inline-block. Because this is a Firefox specific bug, that did the trick for me. A: I know this thread is quite old now, but apparently this bug has not been fixed yet. Using animation does work but there is a noticeable FOUT (Flash Of Unstyled Text). I was able to work around the problem by wrapping the first-letter in a span. This does work around both the sizing issue and the FOUT, it does add extra elements to the markup, so it depends on the needs of your site/application if this is the best fit. .test { background: rgba(0,0,0,0.15); /* For visualisation */ display: inline-block; } .test:first-letter { font-size: 2em; } .test2:first-letter { float: left; } .test3:first-letter { font-size: .5em; } <h1>Inline-block with bigger first-letter</h1> <span class="test">Broken</span> <br><br> <span class="test"><span>F</span>ixed</span> <h1>+ floating to first-letter</h1> <span class="test test2">Broken</span> <br><br> <span class="test test2"><span>F</span>ixed</span> <h1>small size for first-letter</h1> <span class="test test3">Broken</span> <br><br> <span class="test test3"><span>F</span>ixed</span> <h1>small size, floating first-letter</h1> <span class="test test2 test3">Broken</span> <br><br> <span class="test test2 test3"><span>F</span>ixed</span> A: As of 2023, this is still happening in Firefox. This is my solution using SASS, but you can see how to make it bare CSS: txt-brand { display:inline-block; } ///Firefox only /// @-moz-document url-prefix() { margin-right: .1em; white-space: nowrap; &::after { content: '\00a0'; } } } .txt-brand::first-letter { letter-spacing: -.11em; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: IE8 moves content on mouseover This is one of the strangest bugs I've ever encountered. Feel free to check it out here. Basically the issue ONLY exists in IE8/Windows (not IE7 or 9 however). The problem happens when you mouse over the What's Hot image, or any image below that on subsequent rows. Upon mousing over, it shifts all the content down. Could this be due to an issue in clearing the floats? That's my best guess but I can't quite seem to narrow down where the problem lies. A: First, you should fix all the validation errors on your page. Invalid markup is the #1 cause of weird browser behavior. http://validator.w3.org/check?uri=http%3A%2F%2Ftroubadourtx.com%2F&charset=%28detect+automatically%29&doctype=Inline&group=0 You have 75 errors, and 17 warnings. Next, you have abotu a zillion stylesheets and selectors.. You might want to prune your css tree and only apply the CSS that's necessary for the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress merge multiple sites into one multi user site I have about 15 standalone instances of Wordpress. Each using a different woo theme that has been customized and some plugins. Is there an easy way to retain all plugin and theme settings when migrating to wordpress multisite? A: Try to follow Migrating multiple blogs Codex page recommendations. But if you have different customized versions of plugins on your sites - it seems you are in trouble then...
{ "language": "en", "url": "https://stackoverflow.com/questions/7548262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the idea behind creating Event Reminder app in android I want to create Event Reminder App, I search and found that I need to use a service and broadcast receiver. But it is not clear for me what is the role of each components ? As I understand-but I am not sure- that the App needs an Activity that when starts, it runs the service ( which check the current time with times are stored persistently , for example in database !). when the two times match , the service create a broadcast, and our broadcast receiver receives it and create Alert. My questions are: * *Does this inception is correct ? *How to make the service running and always check the time ( do we need some infinite loop?!!) thanks in advance, A: Activities and Services can be killed off without notice anytime system decides it's low on resources. There is no guarantee that your Service would run all the time. Also, if phone is in sleep mode, your code stops executing. So: * *The premise is wrong, for the reasons stated above. *You cant guarantee that Service would be running all the time. For your purpose you should be using AlarmManager. It is garanteed to call your code when alarm is triggered. Also important - AlarmManager survives device restarts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fat Model Skinny Controller in CodeIgniter I've been using CodeIgniter for a while, and have a decent knowledge of MVC, PHP etc. However, I'm finding it hard to adhere to the Fat Model Skinny Controller ethos. I've seen a lot about it; including what pseudo code to include in each file, but no actual examples. (Please link to some articles if I've missed any obvious ones!) I'm finding it hard to move the form logic to a model. For instance, I am using a custom library for my auth system, which has it's own model. Should I then make a site user Model to log users in? Or should I just make a site Model to do that? Or a form Model? To help me out, can anyone advise me on how to skinnify this Controller? I realise it's a lot of code, but simple pointers would be great. (Please note, I've only just written this code, so it hasn't been refactored much, but it should give a good example of how some of my methods are getting out of hand.) public function register() { session_start(); if ($this->tf_login->logged_in()) { redirect('profile'); } if ($_GET['oauth'] == 'true') { $type = $_GET['type']; try { $token = $this->tf_login->oauth($type, '', 'email'); } catch (TFLoginCSRFMismatchException $e) { $this->tf_assets->add_data('error_message', $e->getMessage()); } catch (TFLoginOAuthErrorException $e) { $this->tf_assets->add_data('error_message', $e->getMessage()); } if ($token) { $user_details = $this->tf_login->call('https://graph.facebook.com/me?fields=email,first_name,last_name,username&access_token=' . $token); $user_details_decoded = json_decode($user_details); if ($user_details_decoded->email) { try { $id = $this->tf_login->create_user($user_details_decoded->username, md5($user_details_decoded->username . time()), $user_details_decoded->email, '', TRUE, TRUE); } catch (TFLoginUserExistsException $e) { try { if ($this->tf_login->oauth_login($type, $user_details_decoded->email, $token)) { $this->session->set_flashdata('success_message', 'You have successfully logged in.'); redirect('profile'); } else { $this->session->set_flashdata('error_message', 'An account with these details exists, but currently isn\'t synced with ' . $type . '. Please log in to sync the account.'); } } catch (Exception $e) { $this->session->set_flashdata('error_message', $e->getMessage()); } } catch (TFLoginUserNotCreated $e) { $this->tf_assets->add_data('error_message', 'You could not be registered, please try again.'); } if ($id) { $this->tf_login->add_user_meta($id, 'first_name', $user_details_decoded->first_name); $this->tf_login->add_user_meta($id, 'surname', $user_details_decoded->last_name); $this->tf_login->sync_accounts($id, $type, $token); $this->session->set_flashdata('success_message', 'Welcome ' . $this->input->post('first_name', TRUE) . ' ' . $this->input->post('surname', TRUE) . '. Your account has been sucessfully created. You will shortly receive an email with a verification link in.'); redirect('login'); } } else { $this->session->set_flash_data('error_message', 'You could not be logged in, please try again.'); } } // Redirect to clear URL redirect(current_url()); } if ($this->form_validation->run() !== FALSE) { try { $id = $this->tf_login->create_user($_POST['username'], $_POST['password'], $_POST['email'], '', FALSE); } catch (Exception $e) { $this->tf_assets->add_data('error_message', $e->getMessage()); } if ($id) { $this->tf_login->add_user_meta($id, 'first_name', $_POST['first_name']); $this->tf_login->add_user_meta($id, 'surname', $_POST['surname']); if ($this->tf_login->register_verification_email()) { $this->session->set_flashdata('success_message', 'Welcome ' . $this->input->post('first_name', TRUE) . ' ' . $this->input->post('surname', TRUE) . '. Your account has been sucessfully created. You will shortly receive an email with a verification link in.'); redirect('login'); } else { $this->tf_login->login_user($id); $this->session->set_flashdata('success_message','Your account has been sucessfully created.'); redirect('profile'); } } else { $this->tf_assets->add_data('error_message', $this->tf_login->get_errors()); } } if (validation_errors()) { $this->tf_assets->add_data('error_message', validation_errors()); } $this->tf_assets->set_content('public/register'); $this->tf_assets->add_data('page_title', "Register"); $this->tf_assets->render_layout(); } Thanks in advance! A: From what I can tell, most or all of this code belongs in a controller or component, so I don't think your problem is Model/Controller confusion. The code is difficult to read, however, because of the deep nested structures and the failure to break out specific tasks into their own methods. The main refactoring you would benefit from here is creating new private methods to separate out the discrete subtasks that you are performing. This is has the additional important benefit of clarifying the high-level structure of your current method. So you would end up with something that looked like (just to give you a rough example): public function register() { session_start(); if ($this->tf_login->logged_in()) { redirect('profile'); } if ($_GET['oauth'] == 'true') { $this->oauthRegister(); } $this->normalRegister(); } Similarly, the oatuhRegister method and normalRegister methods would be broken down into smaller methods themselves, so that when you were completely finished each method would be adhering to the SRP and would probably be fewer than 10 lines of code. This will drastically improve the readability and maintainability of your code. I'd also recommend checking out Clean Code, which makes a strong argument for keeping your method short.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Tool for creating DBManager classes in Java? Is there a tool for creating DBManager class for simple databases in SQL? I want to use it along with netbeans. I am working on a simple homework datamining project. But I am fed up of writing DBManagers on my own. I am very well aware of Hibernate, but I am not using it here. So I was just curious about whether there are such tools or plugins or anything. I am using netbeans and MySQL. thanks a lot. A: If you need the typical operations related with typical POJOs that are already a link between the database and your business logic, what are you asking about is really near to an ORM. I understand that you have Java objects that matches records in your MySQL database and that is one of the key concepts of an ORM like Hibernate is. Anyway if you are looking for a simple (and limited) library that provides some kind of tools like save, update or delete records from a database, you will find deprecated and abandoned projects like these: * *DB Objects for Java *JStorm - Simple Tool for Object Relational Mapping By other hand if you prefer to test an easy and simple ORM, you can try ActiveObjects who has a simple and functional approach. A: It's hard to say without knowing what your DBManager class actually does! Why don't you just write your DBManager in such a way that you can reuse it in other projects. That way you won't have to keep rewriting it...
{ "language": "en", "url": "https://stackoverflow.com/questions/7548272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: for remembering passwords, sessions or cookies or both? If a user decides to remember their password based on a checkbox when logging in, is it good practice to set both session and cookies? or would it be better to just do cookies? I think I understand to do sessions when user logs in and DOES NOT like to remember the password. Which one is good practice for remembering logging in? Thanks for your time! A: Since a session gets killed by default after 20 minutes, what do you think is the best solution for long-time storage? I hope you're not thinking of actually storing the password in either a cookie or a session, but to store some random ID you also store in your database, which you check on every page view?
{ "language": "en", "url": "https://stackoverflow.com/questions/7548273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'onmousedown' not being called in JavaScript In Javascript, I want to create a handler for a mouse click. Then, I want to be able to "busy-wait" for a few seconds before running the next line of code.* But in the "busy-wait", I want to still be able to process the mouse click events. Why will the following code run the while loop entirely and THEN activate the handler? (as in, why doesn't the mouse click handler event ever get called in the middle of the busy-wait while loop?) <html> <body> <p id="debugMessageElement"> </p> <script type="text/javascript"> canvas=document.createElement("canvas") var ctx = canvas.getContext("2d"); canvas.width = 840; canvas.height = 560; document.body.appendChild(canvas); var mouse_input = function(event){ document.getElementById("debugMessageElement").innerHTML = event.pageX + ", " + event.pageY + "<br />" } canvas.onmousedown = mouse_input; timeallowed = 3 start = Date.now() while(true){ now = Date.now() delta = now - start if(delta >= timeallowed*1000){ document.write("" + timeallowed + " seconds has passed") break; } } </script> </body> </html> *The reason that I'm designing my code like the above is ultimately because I want to do something like this: for(p in person){ for(t in person[p].shirts){ busy_wait_5_seconds() //However, I want to process mouse clicks in these five seconds. //THEN move on to the next shirt... After five seconds... } } P.S. if you're going to test this code, please note that I used the HTML5 canvas, so some browsers might not work? A: JavaScript has only a single thread. If you do a while-true loop, it will essentially freeze the entire page until the code stops running. To wait a certain time before executing some code, you should use setTimeout. The final solution to your problem is a little more complicated than that though - you would need a recursive setTimeout to process the loop. edit: Here's something I quickly whipped up which should solve your nested loop with waiting in the sub loop: http://jsfiddle.net/t4gsR/ - It may go a bit over your head if you're still a beginner though, but press "run" on the top menu and see it work :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ACRA always disabled? Here is the code I use to have ACRA but its not working,. in the LogCat I keep getting "ACRA is disabled": Checkbox xml: <CheckBoxPreference android:key="acra.enable" android:title="@string/pref_disable_acra" android:summaryOn="@string/pref_acra_enabled" android:summaryOff="@string/pref_acra_disabled" android:defaultValue="true"/> Preference class: public class Preferences extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.preferences); } } Here is a picture while enabling/disabling the checkbox: A: Check You have added your Application in Manifest.xml file... Only if you add it, it will be enabled.... Shanmugam
{ "language": "en", "url": "https://stackoverflow.com/questions/7548275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS: Suppressing negative margins of child elements I have a parent element (e.g. a div) which surrounds some dynamic content. I would like the parent div to fully contain the child elements in as many circumstances as possible. One problem is child elements with negative margin settings, which cause the child element to be displayed outside of the parent element (and also cause the parent element not to be of the desired size). So * *Is there any css trick that can be applied to the parent in order to suppress the negative margins in the child elements (e.g. without having to modify the styles on the child). *Failing that, is there anyway to detect via javascript whether a particular element has overflowing content? (and in which direction and to what degree the content is overflowing?) A: Did you try to put a class to the parent like: .parentDiv > * { margin:0 !important; } To have the parent with the desired height, you need to set some css too: .parentDiv{ overflow:hidden; position:relative; background:#DFE; padding:5px; } A: There is a javascript method of handling this, but it's certainly not as clean as @Mic's CSS solution. I haven't completely tested this, and you may need to add some support for various padding/margin adjustments, but it would get somebody started if a JS-solution was the only option. Using prototype.js (jquery would be similar, but plain javascript will be very.. stretchy): function checkOverflow (child) { child = $(child); if (child.descendants().any()) { child.getElementsBySelector("> *").each(function(e) { checkOverflow(e); }); } var parent = child.up(); var child_left = child.cumulativeOffset()['left'], child_top = child.cumulativeOffset()['top']; var child_height = child.getDimensions()['height'], child_width = child.getDimensions()['width']; var parent_left = parent.cumulativeOffset()['left'], parent_top = parent.cumulativeOffset()['top']; var parent_height = parent.getDimensions()['height'], parent_width = parent.getDimensions()['width']; if (child_top < parent_top) { if (child_left < parent_left) { // adjust element style here } else if (child_left > parent_left + parent_width) { // adjust element style here } } else if (child_top > parent_top + parent_height) { if (child_left < parent_left) { // adjust element style here } else if (child_left > parent_left + parent_width) { // adjust element style here } } } My general feeling, though, is that you should only do this if it can't be explicitly done through CSS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hide UIView on device rotation - doesn't work when device is horizontal I'm trying to hide an image in a view controller when the device is rotated. I'm posting a notification in PlayerViewController and am listening for it in the app delegate, which is responsible for the bannerView: - (void)orientationChanged:(NSNotification *)notification { UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; if ((orientation == UIDeviceOrientationLandscapeLeft) || (orientation == UIDeviceOrientationLandscapeRight)) { bannerView.hidden = ([[self.navigationController visibleViewController] isKindOfClass:[PlayerViewController class]]) ? YES : NO; } else { bannerView.hidden = NO; } } The PlayerViewController sends a notification and the app delegate hides the bannerView. However, when the device is laid flat on a table, the image shows. Works fine when the device is held vertically but horizontally the image appears... odd. Here is the code to send the notification: - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) { ... hide other stuff in this view controller } Any ideas why this odd behavior is occurring? Just one tidbit more information. In the simulator the image shows when the device is in upside-down orientation, even though I have: - (BOOL)shouldAutorotateToInterfaceOrientation (UIInterfaceOrientation)interfaceOrientation { if (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIDeviceOrientationPortrait) { return YES; } else { return NO; } } A: Your error might be happening because of when you're posting the notification. willAnimateRotationToInterfaceOrientation is called before the orientation change takes place (hence the "will" in the method name). So if we're going from portrait to landscape, the current orientation may still be reported as portrait (it may not, it depends). Now, the willAnimate... call returns the toInterfaceOrientation - the orientation that is going to happen. You trigger your notification when you receive the willAnimate... call, and inside that notification call [[UIDevice currentDevice]orientation]: which will return portrait. Instead of requesting the orientation in your notification method you should instead pass the orientation provided in the willAnimate call. If that wasn't clear, the one sentence summary: willAnimateRotationToInterfaceOrientation is called before the rotation changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get all defined ClassificationTypeDefinitions? So I just tried creating a new classification type, [Export(typeof(ClassificationTypeDefinition))] [Name("String")] internal static ClassificationTypeDefinition _stringClassType; But then I got a duplicate ClassificationTypeDefinition error telling me that "String" has already been defined. I didn't define it anywhere else. Soon as I renamed it to "String2" it went away. I'm guessing these are already defined by VS... can I get a list of the predefined ones so I know which to avoid (or which ones I can use)? A: Oops.... guess that wasn't too hard to find after all. MSDN: PredefinedClassificationTypeNames Class
{ "language": "en", "url": "https://stackoverflow.com/questions/7548286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't NSWorkspace's openURL open for more than one URL? I have an action for a menu item that is supposed to open a URL base on the value of the 'lyricLink' property. It will work the first time (and all subsequent times where the value of 'lyricLink' is the same). But if the value of 'lyricLink' changes and the action is called again, it won't open the new link. Any ideas? - (void)openLyricLink:(id)sender { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[self lyricLink]]]; } A: I think the first thing to check would be that [self lyricLink] is returning a valid string on the subsequent calls. I would add: NSLog( @"lyricLink: %@", [ self lyricLink ] ); before calling NSWorkspace to see if lyricLink is a valid URL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get all functions of an object in JavaScript For example, Math.mymfunc = function (x) { return x+1; } will be treated as a property and when I write for(var p in Math.__proto__) console.log(p) it will be shown. But the rest of Math functions will not. How can I get all functions of a Math object? A: var functionNames = []; Object.getOwnPropertyNames(obj).forEach(function(property) { if(typeof obj[property] === 'function') { functionNames.push(property); } }); console.log(functionNames); That gives you an array of the names of the properties that are functions. Accepted answer gave you names of all the properties. A: The specification doesn't appear to define with what properties the Math functions are defined with. Most implementations, it seems, apply DontEnum to these functions, which mean they won't show up in the object when iterated through with a for(i in Math) loop. May I ask what you need to do this for? There aren't many functions, so it may be best to simply define them yourself in an array: var methods = ['abs', 'max', 'min', ...etc.]; A: Object.getOwnPropertyNames(Math); is what you are after. This logs all of the properties provided you are dealing with an EcmaScript 5 compliant browser. var objs = Object.getOwnPropertyNames(Math); for(var i in objs ){ console.log(objs[i]); } A: console.log(Math) should work. A: Object.getOwnPropertyNames() is a good solution The following example is if you have written a sample script and want to create a button for each function. <!-- <script src="example.js"></script> --> <script> // example.js function Example_foo() { console.log("foo") } function Example_bar() { console.log("bar") } for (const funcName of Object.getOwnPropertyNames(this)) { if (funcName.startsWith("Example")) { const frag = document.createRange().createContextualFragment(` <button onclick="${funcName}()">${funcName}</button><br> `) document.body.append(frag) } } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Return a query from a function? I am using PostgreSQL 8.4 and I want to create a function that returns a query with many rows. The following function does not work: create function get_names(varchar) returns setof record AS $$ declare tname alias for $1; res setof record; begin select * into res from mytable where name = tname; return res; end; $$ LANGUAGE plpgsql; The type record only allows single row. How to return an entire query? I want to use functions as query templates. A: CREATE OR REPLACE FUNCTION get_names(_tname varchar) RETURNS TABLE (col_a integer, col_b text) AS $func$ BEGIN RETURN QUERY SELECT t.col_a, t.col_b -- must match RETURNS TABLE FROM mytable t WHERE t.name = _tname; END $func$ LANGUAGE plpgsql; Call like this: SELECT * FROM get_names('name') Major points: * *Use RETURNS TABLE, so you don't have to provide a list of column names with every call. *Use RETURN QUERY, much simpler. *Table-qualify column names to avoid naming conflicts with identically named OUT parameters (including columns declared with RETURNS TABLE). *Use a named variable instead of ALIAS. Simpler, doing the same, and it's the preferred way. *A simple function like this could also be written in LANGUAGE sql: CREATE OR REPLACE FUNCTION get_names(_tname varchar) RETURNS TABLE (col_a integer, col_b text) AS $func$ SELECT t.col_a, t.col_b --, more columns - must match RETURNS above FROM mytable t WHERE t.name = $1; $func$ LANGUAGE sql;
{ "language": "en", "url": "https://stackoverflow.com/questions/7548292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Entity framework: How to reduce database hits? So I have this query in my repository (also using Unit of Work pattern) which uses eager loading to make one hit to the database: from g in _context.Games.Include(pg => pg.PreviousGame).Include(go => go.GameObjects) where EntityFunctions.DiffMilliseconds(DateTime.Now, g.EndDate) > 0 && g.GameTypeId == (int)GameTypes.Lottery && g.GameStatusId == (int)GameStatues.Open select new LotteryModel { EndDate = g.EndDate, GameId = g.Id, PreviousGameEndDate = g.PreviousGame.EndDate, PreviousGameId = g.PreviousGameId.HasValue ? g.PreviousGameId.Value : 0, PreviousGameStartDate = g.PreviousGame.StartDate, PreviousWinningObjectCount = g.PreviousGame.GameObjects.Select(go => go.Object.Count).FirstOrDefault(), PreviousWinningObjectExternalVideoId = g.PreviousGame.GameObjects.Select(go => go.Object.Video.ExternalVideoId).FirstOrDefault(), PreviousWinningObjectName = g.PreviousGame.GameObjects.Select(go => go.Object.Video.Name).FirstOrDefault(), StartDate = g.StartDate, WinningObjectCount = g.GameObjects.Select(go => go.Object.Count).FirstOrDefault(), WinningObjectExternalVideoId = g.GameObjects.Select(go => go.Object.Video.ExternalVideoId).FirstOrDefault(), WinningObjectName = g.GameObjects.Select(go => go.Object.Video.Name).FirstOrDefault() }; However I'm reluctant to use this because I now have to create a separate LotteryModel object to return up throughout my other layers. I would like to be able to return an entity of type "Game" which has all of the navigational methods to all of my other data (PreviousGame, GameObjects, etc) and then map the needed properties to my flat view model, but when I do this it seems to only lazy load the objects and then I have the additional hits to the DB. Or do I have this wrong and whenever I need to return heirarchical data I should return it through my LINQ query in the select portion? My basic goal is to reduce the hits to the DB. A: I don't really understand the problem. You return your Games object and you can access the properties and subobjects off it. Your use of the Include() method tells it to load what you need, and not lazy load it. Make sure you return a single object via a .First, .FirstOrDefault, .Single, .SingleOrDefault, or similar methods. A: I ended up with this query (FYI I'm using the System.Data.Objects namespace for the Include extension): (from g in _context.Games.Include(pg => pg.PreviousGame.GameObjects.Select(o => o.Object.Video)) .Include(go => go.GameObjects.Select(o => o.Object.Video)) where EntityFunctions.DiffMilliseconds(DateTime.Now, g.EndDate) > 0 && g.GameTypeId == (int)GameTypes.Lottery && g.GameStatusId == (int)GameStatues.Open select g).FirstOrDefault(); I guess I just needed to include more of the heirarchy and didn't know I could use Select() in the Include() function!
{ "language": "en", "url": "https://stackoverflow.com/questions/7548294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CodeMirror save itself onBlur I want to save all CodeMirrors generated by PHP itself onBlur. Here is what I am talking about: while ($db_field = mysql_fetch_assoc($result)) { ... var editor = CodeMirror.fromTextArea(document.getElementById("id'.$db_field['id'].'"), { lineNumbers: true, matchBrackets: true, mode: "application/x-httpd-php", onBlur: id'.$db_field['id'].'.save() }); ... } But it don´t work ... FireBug says: "id1 is not defined" ... how to do it? A: I found bug in my code: var id'.$db_field['id'].' = CodeMirror.fromTextArea(document.getElementById("id'.$db_field['id'].'"), { lineNumbers: true, matchBrackets: true, mode: "application/x-httpd-php", onBlur: function(){ id'.$db_field['id'].'.save(); }, onChange: function(){ $("#changeimg").show(); } }); This works like a charm
{ "language": "en", "url": "https://stackoverflow.com/questions/7548295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Testing postgres database accessibility from django I am using the django ORM with a postgres database. A small group of users interact with it using import and export scripts. The database is only available on our intranet. If someone tries to use the database when postgres is unavailable the scripts hang. I would like to make the scripts test whether the database is available before attempting to process any data. I can connect to the database using the shell, import a model, and attempt to make a query: from myapp.models import mymodel mymodel.objects.count() this results in a long delay, but then django raises an OperationalError with an informative message ("could not connect to server: Network is unreachable..."). I thought to test database access by making a minimal query to the database, something like: from django.db import connection cursor = connection.cursor() cursor.execute("select 1") but this never progresses beyond the cursor = connection.cursor() line. No error message. * *Why does one of these queries raise an error, but not the other? *What's the best way to test from a script whether the database is available? *How can I ensure that an error will be raised if the connection doesn't succeed within reasonable (perhaps user specified) time? This is not a web application, so a middleware solution à la How do I test a database connection in Django? isn't possible. Edit Following @benjaoming's suggestion, I've made a function to test the connection: import socket def test_connection(): """Test whether the postgres database is available. Usage: if "--offline" in sys.argv: os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings.offline' else: os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings.standard' from myapp.functions.connection import test_connection test_connection() """ try: s = socket.create_connection(("example.net", 5432), 5) s.close() except socket.timeout: msg = """Can't detect the postgres server. If you're outside the intranet, you might need to turn the VPN on.""" raise socket.timeout(msg) This seems to do the trick. A: You can use another method for finding out if the postgres server is reachable: For instance the socket module -- just do a socket.create_connection(("server", port)) and see what exceptions it raises... A: Using multiple database routing, The trick is to check if the database is reachable at django init time, and then route all the ORM queries to your fallback db. I one way of checking if the database exists or not is running an ORM query inside a try..except block and set a variable which is accessible in your routers.py from django.db import connections conn = connections['default'] try: c = conn.cursor() #this will take some time if error except OperationalError: reachable = False else: reachable = True you could put this code in urls.py or the routers.py itself. the custom router will check if the variable is set and route to your fallback db class AppRouter(object): def db_for_read(self, model, **hints): if reachable : return 'actual_db' else: return 'fallback_db' # define db_for_write likewise A: from django.db import connections db_conn = connections['default'] try: c = db_conn.cursor() except Exception as e: connected = False else: connected = True This can be used to check connections with databases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Running a query using ADODB Connection randomly takes a long time to execute I have come across an issue that seems to be somehow connected to a web server configuration, and resulting in queries randomly taking a long time to execute. The application is created using old plain Classic ASP and ADODB Connection is used. The scenario goes as follows: * *there is a single connection opened in a script at the beginning of processing each HTTP request *this connection is used to execute a query against a SQL Server, that resides on a separate box. conn.Execute is used. Connection is NOT closed afterwards *there are usually a few to a few dozens of conn.Execute in a single ASP page All has been working well until recently, when some of the conn.Execute started to take much longer to execute, totally on random. * *the difference is e.g. 15ms normal execution time vs. 2000ms long execution time *on the SQL Server side, Profiler does not show longer query execution times, so there must be something blocking the conn.Execute request When a proper practice of closing a connection after each conn.Execute has been implemented, the issue goes away. However, as I have stated before, all has been working flawlessly until recently. This web app is a fairly large one and rewriting it to close and reopen connections properly will take some time. And I need a short-term solution. My guess is that it could have something to do with the connection pool size, however this is not ADO.NET, therefore I am not sure, whether a connection pool issue should be taken into the consideration at all. On the SQL Server side, there is no limit on the number of concurrent connections to the server. I need some hints. Brainstorming possible ideas. A: Could be related to delays resolving the hostname in the connection string via DNS - have you tried putting an IP address in the connection string instead of the hostname?
{ "language": "en", "url": "https://stackoverflow.com/questions/7548303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Switch Multi UITableViews in a UITableViewController I have a UITableViewController contains two UITableViews appsTableView and gameTableView, first I set : self.tableView = appsTableView; [self.view addSubview:self.tableView]; then when I click switch page button to do page switch: -(void) switchPage:(id) sender{ switch([sender selectedSegmentIndex]){ case 0: gameTableView = self.tableView; self.tableView = appsTableView; // crash here [self.view addSubview:self.tableView]; break; case 1: appsTableView = self.tableView; [self.tableView removeAllSubviews]; self.tableView.removeFromSuperview; self.tableView = gameTableView; //crash here [self.view addSubview:self.tableView]; break; default: sql = nil; } } both appsTableView and gameTableView have been initialed. How can I do the switch? A: How are the two table views created? I would recommend creating instance variables for them, and retain them when necessary. self.gameTableView = ... // gameTableView is a retain property self.appsTableView = ... // appsTableView is a retain property Then for the switch: self.tableView = gameTableView; I don't think you need to remove the original table view from the super views as the self. syntax should do that for you. I'm not 100% sure about this though, I'll experiment and get back to you. Edit: you should be safe with the direct assignment (no need to remove from super view).
{ "language": "en", "url": "https://stackoverflow.com/questions/7548308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to further optimize this MySQL table for a single Query I have a InnoDB MySql Geo ID table that has ~ 1 million rows. The table structure is this: CREATE TABLE `geoid` ( `start_ip` int(11) NOT NULL, `end_ip` int(11) NOT NULL, `city` varchar(64) NOT NULL, `region` char(2) NOT NULL, PRIMARY KEY (`start_ip`,`end_ip`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; There will only be one type query ran against this table: SELECT city, region FROM geoid WHERE 1259650516 BETWEEN start_ip AND end_ip This query takes about ~ .4228 sec, which is not super slow but not incredibly fast ether. My question is: How can I further optimize my table for this single query? I have tried the following things: * *Change the Storage Engine to MyISAM, this made the query take about 1.9 sec. *Use the WHERE statement 'WHERE geoid.start_ip <= 1259650516 AND 1259650516 <= geoid.end_ip'. But that takes about .5 sec to execute instead of .4 ish. I have removed all useless rows from the table to make it smaller. I need all 1 million rows. UPDATE / SOLUTION Thanks to the article below, here is what I did to fix this problem. (just to complete this answer for anyone else interested) I added a new column to the above table: ALTER TABLE `geoid` ADD `geoip` LINESTRING NOT NULL I then filled the new column with the geo data from start_ip and end_ip GeomFromText(CONCAT('LINESTRING(', start_ip, ' -1, ', end_ip, ' 1)')) I then created the SPATIAL INDEX on the new column CREATE SPATIAL INDEX geoip_index ON geoid(geoip); From there, all you have to do is change your query to: SELECT city, region FROM geoid WHERE MBRContains(geoip, GeomFromText(CONCAT('POINT(', 1259650516, ' 0)'))); AND YOUR DONE. This took the query down from .42 sec to .0003 sec!!!!!!! I love this INDEX. Thank you. Hope it helps. A: Try adding an index on end_ip. This should make the query about twice as fast in some cases. For much better perfomance you need to use a SPATIAL index, as explained in this article. A: Try to create index on all fields included in query. on this particular case create one index on two fields (start_ip and end_ip)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Pointer questions regarding linked lists Alright guys, so I've been working on a linked list program and I've run into a problem. I'm trying to place a piece of data into an already sorted linked list in a sorted fashion. Right now, I'm comparing the pointer data the user gives (Data * newData) to the head (LinkNode * current = head) and I know that's where my program is failing. I know I have to compare actual values, not memory addresses, but I'm not sure how I would go about doing it. Anybody have any suggestions at all or ideas? Thanks. void addSorted(Data * newData) { if(head == NULL) { head = new LinkNode(newData); return; } LinkNode * current = head; LinkNode * previous = NULL; while(current != NULL) { if(newData->compareTo(current->data) == -1) { LinkNode * newNode = new LinkNode(newData); newNode->next = current; if(previous == NULL) { current->next = newNode; } else { newNode->next = previous->next; previous->next = newNode; } return; } previous = current; current = current->next; } previous->next = new LinkNode(newData); } A: Simply if(*newData < (*current->data)) assuming that operator< is overloaded for the Data type The minimal idiomatic way to provide std::less<> compliant weak total ordering (I.o.w. implement operator<): struct Data { int id; std::string other; // details omitted bool operator<(const Data& b) const { if (id < rhs.id) return true; if (id > ths.id) return false; return (other < b.other); } }; If you have an large/complicated structure and all the members participating have comparison defined for their types, you can do this neat trick with TR1, Boost or C++11 Tuples: #include <tuple> // ... bool operator<(const Data& b) const { return std::tie(id,other)< std::tie(b.id,b.other); } A: In your while loop you are comparing newData (which is a pointer) with "current->data" which is an integer (I suppose) ? i.e. if(newData < current->data) A: you could use memcmp to compare your data A: if(newData < current->data) should be if(*newData < current->data) I guess. If there is no operator<, implement it or use the slow memcmp. Also if this is a practical code (why not use stl?) consider using skip lists - they will be much faster. PS: operators are a powerful feature, do not hesitate to use them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing output from subprocess.Popen to a if elif statement Im creating a python script to check for suPHP i'm trying to create an if else statement to declare if suPHP is on the server using output from subprocess.Popen I've tested the output of the variable with print before i created this post and it pass's the correct output to the variable suphp. This is what i have so far: # check for suPHP suphp = subprocess.Popen("/usr/local/cpanel/bin/rebuild_phpconf --current", shell=True, stdout=subprocess.PIPE,).communicate()[0] if suphp = "/bin/sh: /usr/local/cpanel/bin/rebuild_phpconf: No such file or directory" print "suPHP is not installed on the server" elif print suphp Please note I am new to coding and python and decided to try to use python to admin some servers. A: You don't appear to be doing anything useful with the shell=True, and so you can probably safely skip it alltogether: try: suphp = subprocess.Popen(["/usr/local/cpanel/bin/rebuild_phpconf", "--current"], stdout=subprocess.PIPE,).communicate()[0] except OSError: print "Couldn't start subprocess, suPHP is not installed on the server" note that you'll have to split the command into each of its separate arguments, since you won't have a shell to do it for you. You should always avoid using the shell for subprocesses unless you absolutely require it (say, because you have to set your environment by sourcing a script) A: Out of my head: the comparison operator is == not = and output is almost always followed by a newline character. so try something like this: if "No such file or directory" in suphp: ... A: In Unix, you sometimes need to consider that subprocesses can output text to two different output streams. When there are no problems, like with echo hello, the text gets sent to the "standard output" stream. On the other hand, it's considered good manners for a process to send all of its error messages to the "standard error" stream; for example stat /this-file-does-not-exist. You can verify this by sending all standard output to /dev/null. When you run this command, you'll get no output on your console: stat . > /dev/null When you run this, an error message will appear on your console (because the text is from the standard error stream): sh /this-program-does-not-exist > /dev/null Getting back to your question, the "standard error" stream is sometimes called "stderr". The text from this stream can be captured using Python's subprocess library using the POpen.stderr property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ContentControl two way binding within DataTemplate not working? I've setup a reusable datatemplate "DataGridCheckBoxEdit" for a datagrid column. Binding to it one way works like a charm through ContentControl. Binding directly works two way correctly. However, binding two way within that DataTemplate, from a ContentControl just won't work. Here are the snippets: <DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <ContentControl Content="{Binding Path=IsMadeAvailable, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ContentTemplate="{StaticResource DataGridCheckBoxEdit}" /> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> and the reusable template: <DataTemplate x:Key="DataGridCheckBoxEdit"> <CheckBox Name="CheckBoxControl" IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}, Path=DataContext.Content, Mode=TwoWay, BindsDirectlyToSource=True, UpdateSourceTrigger=PropertyChanged}" Margin="8,4,2,2" /> <DataTemplate.Triggers> <Trigger SourceName="CheckBoxControl" Property="IsVisible" Value="True"> <Setter TargetName="CheckBoxControl" Property="FocusManager.FocusedElement" Value="{Binding ElementName=CheckBoxControl}"/> </Trigger> </DataTemplate.Triggers> </DataTemplate> As I said, one way binding works like a charm...but getting the data back to the property doesn't. Of course, putting it without being reusable: <DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <CheckBox Name="GasIsAvailableCheckBox" IsChecked="{Binding Path=IsMadeAvailable, UpdateSourceTrigger=PropertyChanged}" Margin="8,4,2,2" /> <DataTemplate.Triggers> <Trigger SourceName="GasIsAvailableCheckBox" Property="IsVisible" Value="True"> <Setter TargetName="GasIsAvailableCheckBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=GasIsAvailableCheckBox}"/> </Trigger> </DataTemplate.Triggers> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> also works great, and works two-way. What am I doing wrong? Thanks! Vladan A: Your binding is just broken (see the output window of Visual Studio for the respective errors), you do not want to bind to DataContext.Content but just Content, the DataContext would be the object in that row instead of the ContentControl itself. Change that in the binding path of the reusable template and it will work. You also set a lot of properties to values they already have by default, this would be the minimal version: {Binding Content, RelativeSource={RelativeSource AncestorType=ContentControl}}
{ "language": "en", "url": "https://stackoverflow.com/questions/7548332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't find logic behind png file sizes I'm saving a large number of small png files for use in a game on a phone, so space is at a premium. I'm trying to figure out the logic behind the file sizes so I can save things most efficiently, but even after using pngcrush the sizes are totally inconsistent. I saved a 1x1 image and it takes 3kb. I have another 23x21 image which takes only 2kb. I have two images which are almost the same size, but one takes 6kb and the other takes 13kb. I doubled the image height and copied one image into the empty space of the other and saved that. The combined image is only 11kb! Why is a 1x1 image larger than a 23x21 image? Why can I combine a 13kb image and a 6kb image and get an 11kb image? Here are the images I'm talking about (there's a 1x1 pixel in between the 1st and second images. It's difficult to see, so I'll just give the URL: http://g42.org/temp/png/1x1.png): example http://g42.org/temp/png/hat.png example http://g42.org/temp/png/1x1.png example http://g42.org/temp/png/helmet1.png example http://g42.org/temp/png/helmet2.png example http://g42.org/temp/png/helmet1_2.png A: It's not a compression thing, the problem with the 1x1 image is that it has metadata (added by Photoshop, it seems), a color profile (iCCP chunk). If you look inside the binary, its' the data between the strings "iCCP" and "IDAT", it could be removed and you get a 69 bytes file. If you reopen and save the file most image viewers (xnview), or use pngcrush, you can strip that chunk. : See it here : http://i.stack.imgur.com/fmOdA.png And regarding the helmet images: besides other informational chunks (imageReady ads some informational text, as you can see), the difference is due to different formats: the two-helmets is a paletted image (8bits per pixel), the single helmet is a RGB with alpha (32bits per pixel) A: PNG compression is based on the same algorithm as zlib and is highly sensitive to the data that is being compressed so you won't see a consistent relationship between image size and file size. In the case of the combined image, it is still bigger than the smaller image and given the similarity of the two halves of the image, the compressor was probably able to reuse a lot of the Huffman tree. I don't know enough about the algorithm to say for certain how it ended up smaller than the other half. As long as you are not seeing oddities like the 1x1 image, which you seem to have figured out in the comments, I don't think this will make a lot of sense without extensive study of image compression. A: There is a great utility called pngcrush http://pmt.sourceforge.net/pngcrush/ Compressing to PNG is a rather difficult task - there are lost of assumptions and strategies to try - do we create a palette, or are we better off without it? PNGcrush essentially bruteforces 100+ different compression strategies, while at the same time trimming useless tags and sections. A: PNG has several sub-formats: 24-bit with or without alpha, 8-bit (includes alpha), grayscale, etc. which use different amount of bytes per pixel and have different "compressibility". Plus PNG supports several compression tricks (filters and gzip settings) which affect how well image data is compressed. On top of that PNG can contain metadata, which sometimes can be pretty large, like some embedded color profiles. * *ImageAlpha converts images to the most space-efficient PNG8+alpha variant. *ImageOptim removes junk metadata and finds best compression parameters. With a combination of those two your images can be reduced by 30-50%.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Snake Game - Collision Error So I am making a snake game, but if I move from one direction to the other really fast then it says I made a collision with the body and ends the game (for example, if I am going left and I hit down and then left again really fast or down and right really fast, etc.) I've tried a few things already. I changed the way that it checked for a collision by making it a .intersects rather than checking if (x == body[i][0] && y = body[i][1]). I also did a few System.out.println()'s to see if maybe something was going wrong there. I noticed that sometimes one of the values repeats (either x or y depending on the direction), but I can't figure out why... I figure that the repeating is why it messes up the collision, but I can't find the spot where it would be making it repeat. x and y are being changed by a thread. Here is the "Drawing" portion of my code. If you need any other snippets of code please let me know. public void paintComponent(Graphics g) { super.paintComponent(g); if (numOfFood == 1) {//Checks wether there is food on the GUI g.setColor(Color.BLUE); g.fillRect(foodX,foodY,12,12); } else { foodX = random.nextInt(103)*12; //Both this and the below line get a random x or y value to put on GUI for food placement foodY = random.nextInt(57)*12; numOfFood = 1; } Rectangle headRect = new Rectangle( x, y, 12, 12 ); //Actual rectangle of the head Rectangle foodRect = new Rectangle(foodX, foodY, 12, 12); //Food rectangle g.setColor(Color.RED); g.fillRect(x,y,12,12); //Draws head of Snake g.setColor(Color.WHITE); g.fillRect(x+2,y+2,8,8); //Draws a white square in the head of the snake for (int i = 0; i < n; ++i) { //Collision Checker Rectangle bodyRect = new Rectangle(body[i][0],body[i][1],12,12); if ( headRect.intersects(bodyRect)) { for (int j = 0; j < n; ++j) { body[j][0] = -1; body[j][1] = -1; } numOfFood = 1; n = 0; x = 624; y = 348; endGame = true; } } g.setColor(Color.RED); if (n > 0) { //Puts the snakes body behind the head for (int i = 0;i < n; ++i) { g.fillRect(body[i][0],body[i][1],12,12); } } for (int i = n-1;i >= 0; --i) { //Inserts the head at the first part of the array so that the body moves if (body[i][0] != -1 && body[i][1] != -1) { body[i+1][0] = body[i][0]; body[i+1][1] = body[i][1]; } if (i == 0) { body[i][0] = x; body[i][1] = y; } } if (headRect.intersects(foodRect)) { //If the food rectangle and the head rectangle intersect then the snake got the food. numOfFood = 0; n++; } } A: When do you call paintComponent? I suspect that you have one method that continuously moves the snake forward in regular intervals, but paintComponent is responsible for making the snake longer. You should move collision and moving the snake into the same method that is responsible for moving the head in the direction the snake is moving. Otherwise, paintComponent might be called many times on one move update, and this is responsible for duplicates of x and y in your array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: An error occurred while signing: SignTool.exe not found While I was trying to Update my Project I was making - I got an error for the first time I've seen: 'An error occurred while signing: SignTool.exe not found.' I've never seen this before, So I looked up that SignTool.exe is what signs my project for ClickOnce Deployment. I also read that is it a part of Windows SDK - but when I looked to find where SignTool.exe is - I saw it right there! C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin I saw no problem, and I've always published my Project all the time - I'm on Version 68. But this is the first time I've seen this - I didn't touch any options that would do this. Any help? A: Click "Project" at the top. Then click " Properties" -> Signing -> Unchecked [Sign the ClickOnce manifests] is now working A: Now try to publish the ClickOnce application. If you still find the same issue, please check if you installed the Microsoft .NET Framework 4.5 Developer Preview on the system. The Microsoft .NET Framework 4.5 Developer Preview is a prerelease version of the .NET Framework, and should not be used in production scenarios. It is an in-place update to the .NET Framework 4. You would need to uninstall this prerelease product from ARP. https://blogs.msdn.microsoft.com/vsnetsetup/2013/11/18/an-error-occurred-while-signing-signtool-exe-not-found/ Lastly you might want to install the customer preview instead of being on the developer preview A: None of the answers above talk about disabling ClickOnce. In my situation, I never used ClickOnce for my applications but after I upgraded to VS 2015 it was suddenly enabled and I got the 'SignTool.exe not found' error when I tried to compile. To disable you go into the properties of your Project (right click) and choose Security | Uncheck Enable ClickOnce security settings. You can leave the manifest checked in the Signing tab because it has nothing to sign if it's been disabled. I've confirmed that unchecking the security resolved the compile error on my projects. A: Please Click Once application --> Properties --> Signing -> Unchecked the Sign the ClickOnce manifests. Problem will be solved. Note: Be aware that this solution removes security from your project. Seek assitance from a more learned colleague before doing so. A: SignTool is moved to another location in the last SDK: C:\Program Files (x86)\Windows Kits\8.1\bin\x86 Need to install ClickOnce Publishing Tools during Visual Studio 2015 setup. You can re-run the Installation from the Programs and Features section; find Visual Studio in the list and click Change. A: I needed Signing hence couldn't un-check as suggested. Then goto Control Panel -> Programs and Features -> Microsoft Visual Studio 2015 Click Change then the installer will load and you need to click Modify to add ClickOnce Publishing Tools feature. A: ClickOnce Publishing Tools are not installed as part of the Typical Installation Options. So you have to install it in advanced mode. This dialog can be found in Windows 7 by going to Control Panel > Uninstall a program, right-clicking on Microsoft Visual Studio Professional 2015 and selecting Change. A Visual Studio dialog will open up. Select Modify from the set of buttons at the bottom and the above dialog will appear. A: You can fix this by clicking on installation application of VS. Then click Modify > Mark ClickOnce App and then upgrade your VS. Also i think @Alex Erygin is right. It is a bad solution to Click Once application --> Properties --> Signing -> Uncheck Sign the ClickOnce manifests. This is not a solution. It only circumambulated the problem. A: This is a simple fix. Open the project you are getting this error on. Click "Project" at the top. Then click " Properties" ( Will be the name of the opened project) then click "Security" then uncheck "Enable ClickOnce security settings." That should fix everything. A: I did have similar problem. For some reason under project properties -> Signing -> Sign ClickOnce manifests was enabled. I unchecked it and the problem went away. A: Reinstalling SDK did not help me but installing SDK+.NET 3.5 did from link below: https://www.microsoft.com/en-us/download/details.aspx?id=3138 A: Windows 10 users can find signtool.exe in C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64 folder (10.0.18362.0 in my case, or other version). But first, make sure you've installed Windows 10 SDK Then, check Windows SDK Signing Tools for Desktop Apps is installed by going to Control Panel > Programs > Programs and Features, choose Windows Software Development Kit - Windows 10.0.18362.1 (in my case, you version may be different), right-click, choose Change, choose options Change then click Next. A: I had the same issue/error message just after upgrading Visual Studio Pro 2019 V16.6.0. Solution was to make sure that the signing certificate is valid as mine had expired by a day. Look in properties and signing to either enter a valid or temporary certificate. To keep the file name the same as before then un-click the security as mentioned above and then delete the key file linked to the programme. Create a new key file and then add back the security. A: * *Solution Explorer *Your app Right Clik *Propatis *Security *Unchek (Enable ClickOnce Security Settings) Thats Solve..... __:) *https://i.stack.imgur.com/62nKZ.png See [enter image description here] A: After upgrading build tools in DevOps build agent to visual studio 2019, we started getting the below error for 64-bit build step of a WPF application. C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3975,5): error MSB3482: An error occurred while signing: SignTool.exe was not found at path I tried all the above answers except the ones to disable signing or signing security and nothing helped. Disabled the default MSBUILD step Added a cmd prompt step The path is "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MsBuild.exe" Note: Removed amd64 from the path above. This is still a workaround. I hope Microsoft will fix it in the following release. A: For VS 2019 or later (Windows 11) Option 1 (Recommended) - ClickOnce Publishing Tools are not installed basic Installation. Therefore you will have to manually check and install. Go to Visual Studio Installer Then Click modify Finally, select Individual components tab, search for ClickOnce Publishing and install Restart the computer. Option 2 (Not recommended) - Click Once application --> Properties --> Signing -> Uncheck Sign the ClickOnce manifests. This is not a solution. A workaround. Option 3 - Install Windows 10 SDK. Check Control Panel > Programs > Programs and Features > Windows Software Development Kit
{ "language": "en", "url": "https://stackoverflow.com/questions/7548342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "105" }
Q: Motif programming and UTF-8 I'm new to Motif programming and I want to use UTF-8 encoding. I've tried XtSetLanguageProc (NULL, NULL, NULL); but when I read a file in Motif (editor text-like in 6A volume motif programming), I've got problems with accented characters. I had to use setlocale()? thanks! A: With Motif, you have to switch to the correct font for the languages that you are using. There is currently no single UTF-8 font that has full support for all languages. If there is more to your problem you might want to ask it on MotifZone http://www.motifzone.com/forum/unicode-support since Motif is not a commonly used toolkit anymore. A: As Michael said, you need a font that supports Unicode. The ones with most broad support are Iso10646 fonts. Assuming Linux with X11, launch xfontsel to find them. Select iso10646 from the rgstry drop-down menu. Then fmly menu will list available fonts with that encoding. Some are very limited, but -*-fixed-medium-*-*-*-18-*-*-*-*-*-iso10646-* is a good choice that comes with the X11 installation. Then, you need either to set that font as a fallback in your Motif program or supply the resource via command-line xmprogram -xrm '*fontList: -*-fixed-medium-*-*-*-18-*-*-*-*-*-iso10646-*' If all worked right, there will be no problems with accented characters anymore. For a font supporting even more glyphs, consider GNU Unifont.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: HTML5 drag and drop question I'm trying to implement HTML5 drag and drop to upload a file. When the file is dropped, I want to call the php file to handle the dropped file. How can I call the php file and access the dragged file in php file. Also, I want to send the success or error message back from php file. I'm unable to figure out how can I post the file to php and get the response from there. My code so far is: function drop(evt) { evt.stopPropagation(); evt.preventDefault(); var files = evt.dataTransfer.files; handleFiles(files); } function handleFiles(files) { var file = files[0]; var reader = new FileReader(); reader.onload = uploadFile; //main function reader.onloadend = uploadComplete; reader.readAsDataURL(file); } function uploadFile(evt) { //call upload.php //get success msg or error msg //alert(success) or alert(error) } Here's example upload.php file: <?php $dropped_file //how to get the file if (filesize($dropped_file) > 1024) { echo "size error" //how to send this error } else { echo "success" //how to send this success msg. } ?> A: This should help - http://www.thebuzzmedia.com/html5-drag-and-drop-and-file-api-tutorial/ A: You can use jQuery, upon the drop callback perform an AJAX call. $("body").droppable({ accept: "img", //Your element type goes here e.g. img drop: function(event, ui){ //Perform an AJAX call here. You can access the current dropped item through //ui.draggable } )} A: Use jQuery UI will give you the ability to drag and drop in the most easy way
{ "language": "en", "url": "https://stackoverflow.com/questions/7548356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery animation glitch for each item of a div container I want to loop through each slider and animate each of them seperate and not all together. With my current code, I'm doing the animation all together, which I don't get it since I used .each and .delay to wait for the next animation. Here is my jquery code: $(document).ready(function(){ var i = $('#slideContainer .slider'); var w = $(window).width(); i.each( function () { var obj = $(this); obj.delay(800).fadeOut('fast', function(){ $(obj, 'div.slider').toggleClass("none"); $('.slideIcon').offset({left: w}); $('.slideText p').offset({left: w}); $( '.slideImage2').offset({left: w}); sliderRight(); sliderLeft(w); }); }); }); function sliderRight(){ $(".slideIcon").animate({left:0}, 4000, 'easeInOutExpo'); $(".slideText p").animate({left:0}, 5000, 'easeInOutExpo'); //$(".slideImage1").animate({opacity:1}, 5000); $(".slideImage2").animate({left:0}, 5000, 'easeInOutExpo'); } function sliderLeft(w){ $(".slideIcon").animate({left:-w}, 4000, 'easeInOutExpo'); $(".slideText p").animate({left:-w}, 2000, 'easeInOutExpo'); //$(".slideImage1").animate({opacity:0}, 5000); $(".slideImage2").animate({left:-w}, 2000, 'easeInOutExpo'); } Here is my HTML code: <div id="slideshow"> <div id="slideContainer"> <div class="slider none"> <div class="slideText"> <img class="slideIcon"src="img/banh-mi-icon.png" alt="" /> <p>Vite fait, vite pr&ecirc;t&ensp;!</p> </div> <div class="static"></div> <div class="slideImage"> <img class="slideImage1" src="img/line1.png" alt="" /> <img class="slideImage2"src="img/line3.png" alt="" /> </div> <div class="clear"></div> </div> <div class="slider none"> <div class="slideText"> <img class="slideIcon"src="img/bubble-tea-icon.png" alt="" /> <p>Avec boules de tapiocas&ensp;!</p> </div> <div class="slideImage"> <img class="slideImage1"src="img/line2.png" alt="" /> <img class="slideImage2"src="img/line3.png" alt="" /> </div> </div> </div><!-- end slidecontainer!--> A: It does not work that way, you will have to encapsule the functions like this $(".slideIcon").animate({left:0}, 4000, 'easeInOutExpo', function(){ $(".slideText p").animate({left:0}, 5000, 'easeInOutExpo', function(){ $(".slideImage2").animate({left:0}, 5000, 'easeInOutExpo'); }); }); What this does is animate each item one after another the function provided as last parameter is the callback, it gets executed when the current animation is completed A: I finally found the solution to my problem. Use an array, find the length of my class slider. Create multiple function for each slider effect, example: left-to-rigth, rigth-to left. For each of this function add the animations desire with a stop animation. Use an automator for preloading the next image by testing if it exist or not and setting a setInterval for the timeout. I haven't wrote the code yet, but the logic is there. Hope it can help someone
{ "language": "en", "url": "https://stackoverflow.com/questions/7548357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: similar tables looking different in opera and IE7 I'm trying to achieve a basic fixed table header effect. For this I'm using two tables with the exact same markup and CSS. The "content" table is in a div with overflow-y set. Everything looks fine except IE7 and Opera where the "header" table has different column widths than the "content" table. Here is a jsfiddle: http://jsfiddle.net/gEtGW/1/ Please let me know if you have an idea about this. Thanks! EDIT: A: In your HTML, you have this... <table class="inner-table"> <colgroup> <col width="83"> <col width="92"> <col width="123"> <col width="120"> <col width="177"> <col width="84"> </colgroup> Where the widths above all add up to 679 total. However, in your CSS, you have this... .inner-table { width: 680px; } I'm not sure what each browser is supposed to do with the extra/missing pixel or how they decide whether the one pixel discrepancy is one extra pixel or missing one pixel. 679 versus 680... which one takes precedence? Though, I'm sure every browser will probably render this differently. A: Ok problem found (The problem is a text-style one): 'Column' text is making the bounds of the column celd change For example change 'column' for 'col' and you see it like this: http://jsfiddle.net/qYnPU/ A: I had this exact same problem and I first tried to solve it in the same way you are doing it. But that led nowhere -- just because of the kinds of cross-browser issues you're seeing. I spent days and days trying to make it right. I finally gave up on the two-table approach. Instead, I made a div with the table header material, calculating the width of each header element from the first row of the content table. It has worked flawlessly in all browsers. I posed a question like yours over here on SO. You might want to give it a look. Here is the table using the new scheme. HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/7548361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dropdownlist event I have been searching all around for a guide on event handling in flash builder 4.5. I have a dropdownlist that I'd like to activate preferably a action script function. similar to asp.net/js. cheers! A: right out of as3 docs with some comments... import fl.controls.ComboBox; import fl.controls.Label; var myComboBox:ComboBox = new ComboBox(); myComboBox.prompt = "Please select an item..."; myComboBox.addItem({label:"Item 1"}); myComboBox.addItem({label:"Item 2"}); myComboBox.addItem({label:"Item 3"}); myComboBox.addItem({label:"Item 4"}); myComboBox.width = 150; myComboBox.move(10, 10); myComboBox.addEventListener(Event.CHANGE, changeHandler); // <- ASSIGN EVENT LISTENER addChild(myComboBox); var myLabel:Label = new Label(); myLabel.autoSize = TextFieldAutoSize.LEFT; myLabel.text = "selectedIndex:" + myComboBox.selectedIndex; myLabel.move(myComboBox.x + myComboBox.width + 10, myComboBox.y); addChild(myLabel); function changeHandler(event:Event):void { // <- ASSIGN FUNCTION myLabel.text = "selectedIndex:" + myComboBox.selectedIndex; } Also from the docs, these are the events... change Dispatched when the user changes the selection in the ComboBox component or, if the ComboBox component is editable, each time the user enters a keystroke in the text field. ComboBox close Dispatched when the drop-down list is dismissed for any reason. ComboBox enter Dispatched if the editable property is set to true and the user presses the Enter key while typing in the editable text field. ComboBox itemRollOut Defines the value of the type property of an itemRollOut event object. ComboBox itemRollOver Defines the value of the type property of an itemRollOver event object. ComboBox open Dispatched when the user clicks the drop-down button to display the drop-down list. ComboBox scroll Dispatched when the user scrolls the drop-down list of the ComboBox component. ComboBox
{ "language": "en", "url": "https://stackoverflow.com/questions/7548366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CUDA Maximum Reduction Algorithm Not Working A previous question asked how to find to find the maximum value of an array in CUDA efficiently: Finding max value in CUDA, the top response provided a link to a NVIDIA presentation on optimizing reduction kernels. If you are using Visual Studio, simply remove the header reference, and everything between CPU EXECUTION. I setup a variant which found the max, but it doesn't match what the CPU is finding: // Returns the maximum value of // an array of size n float GetMax(float *maxes, int n) { int i = 0; float max = -100000; for(i = 0; i < n; i++) { if(maxes[i] > max) max = maxes[i]; } return max; } // Too obvious... __device__ float MaxOf2(float a, float b) { if(a > b) return a; else return b; } __global__ void MaxReduction(int n, float *g_idata, float *g_odata) { extern __shared__ float sdata[]; unsigned int tid = threadIdx.x; unsigned int i = blockIdx.x*(BLOCKSIZE*2) + tid; unsigned int gridSize = BLOCKSIZE*2*gridDim.x; sdata[tid] = 0; //MMX(index,i) //MMX(index,i+blockSize) // Final Optimized Kernel while (i < n) { sdata[tid] = MaxOf2(g_idata[i], g_idata[i+BLOCKSIZE]); i += gridSize; } __syncthreads(); if (BLOCKSIZE >= 512) { if (tid < 256) { sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 256]); } __syncthreads(); } if (BLOCKSIZE >= 256) { if (tid < 128) { sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 128]); } __syncthreads(); } if (BLOCKSIZE >= 128) { if (tid < 64) { sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 64]); } __syncthreads(); } if (tid < 32) { if (BLOCKSIZE >= 64) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 32]); if (BLOCKSIZE >= 32) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 16]); if (BLOCKSIZE >= 16 ) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 8]); if (BLOCKSIZE >= 8) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 4]); if (BLOCKSIZE >= 4) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 2]); if (BLOCKSIZE >= 2) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 1]); } if (tid == 0) g_odata[blockIdx.x] = sdata[0]; } I have a giant setup to test this algorithm: #include <cstdio> #include <cstdlib> #include <ctime> #include <iostream> #include <sys/time.h> #include <cuda.h> #include <cuda_runtime.h> #include <device_launch_parameters.h> #include "book.h" #define ARRAYSIZE 16384 #define GRIDSIZE 60 #define BLOCKSIZE 32 #define SIZEFLOAT 4 using namespace std; // Function definitions float GetMax(float *maxes, int n); __device__ float MaxOf2(float a, float b); __global__ void MaxReduction(int n, float *g_idata, float *g_odata); // Returns random floating point number float RandomReal(float low, float high) { float d; d = (float) rand() / ((float) RAND_MAX + 1); return (low + d * (high - low)); } int main() { /*****************VARIABLE SETUP*****************/ // Pointer to CPU numbers float *numbers; // Pointer to GPU numbers float *dev_numbers; // Counter int i = 0; // Randomize srand(time(0)); // Timers // Kernel timers cudaEvent_t start_kernel, stop_kernel; float elapsedTime_kernel; HANDLE_ERROR(cudaEventCreate(&start_kernel)); HANDLE_ERROR(cudaEventCreate(&stop_kernel)); // cudaMalloc timers cudaEvent_t start_malloc, stop_malloc; float elapsedTime_malloc; HANDLE_ERROR(cudaEventCreate(&start_malloc)); HANDLE_ERROR(cudaEventCreate(&stop_malloc)); // CPU timers struct timeval start, stop; float elapsedTime = 0; /*****************VARIABLE SETUP*****************/ /*****************CPU ARRAY SETUP*****************/ // Setup CPU array HANDLE_ERROR(cudaHostAlloc((void**)&numbers, ARRAYSIZE * sizeof(float), cudaHostAllocDefault)); for(i = 0; i < ARRAYSIZE; i++) numbers[i] = RandomReal(0, 50000.0); /*****************CPU ARRAY SETUP*****************/ /*****************GPU ARRAY SETUP*****************/ // Start recording cuda malloc time HANDLE_ERROR(cudaEventRecord(start_malloc,0)); // Allocate memory to GPU HANDLE_ERROR(cudaMalloc((void**)&dev_numbers, ARRAYSIZE * sizeof(float))); // Transfer CPU array to GPU HANDLE_ERROR(cudaMemcpy(dev_numbers, numbers, ARRAYSIZE*sizeof(float), cudaMemcpyHostToDevice)); // An array to temporarily store maximum values on the GPU float *dev_max; HANDLE_ERROR(cudaMalloc((void**)&dev_max, GRIDSIZE * sizeof(float))); // An array to hold grab the GPU max float maxes[GRIDSIZE]; /*****************GPU ARRAY SETUP*****************/ /*****************KERNEL EXECUTION*****************/ // Start recording kernel execution time HANDLE_ERROR(cudaEventRecord(start_kernel,0)); // Run kernel MaxReduction<<<GRIDSIZE, BLOCKSIZE, SIZEFLOAT*BLOCKSIZE>>> (ARRAYSIZE, dev_numbers, dev_max); // Transfer maxes over HANDLE_ERROR(cudaMemcpy(maxes, dev_max, GRIDSIZE * sizeof(float), cudaMemcpyDeviceToHost)); // Print out the max cout << GetMax(maxes, GRIDSIZE) << endl; // Stop recording kernel execution time HANDLE_ERROR(cudaEventRecord(stop_kernel,0)); HANDLE_ERROR(cudaEventSynchronize(stop_kernel)); // Retrieve recording data HANDLE_ERROR(cudaEventElapsedTime(&elapsedTime_kernel, start_kernel, stop_kernel)); // Stop recording cuda malloc time HANDLE_ERROR(cudaEventRecord(stop_malloc,0)); HANDLE_ERROR(cudaEventSynchronize(stop_malloc)); // Retrieve recording data HANDLE_ERROR(cudaEventElapsedTime(&elapsedTime_malloc, start_malloc, stop_malloc)); // Print results printf("%5.3f\t%5.3f\n", elapsedTime_kernel, elapsedTime_malloc); /*****************KERNEL EXECUTION*****************/ /*****************CPU EXECUTION*****************/ // Capture the start time gettimeofday(&start, NULL); // Call generic P7Viterbi function cout << GetMax(numbers, ARRAYSIZE) << endl; // Capture the stop time gettimeofday(&stop, NULL); // Retrieve time elapsed in milliseconds long int elapsed_sec = stop.tv_sec - start.tv_sec; long int elapsed_usec = stop.tv_usec - start.tv_usec; elapsedTime = (float)(1000.0f * elapsed_sec) + (float)(0.001f * elapsed_usec); // Print results printf("%5.3f\n", elapsedTime); /*****************CPU EXECUTION*****************/ // Free memory cudaFreeHost(numbers); cudaFree(dev_numbers); cudaFree(dev_max); cudaEventDestroy(start_kernel); cudaEventDestroy(stop_kernel); cudaEventDestroy(start_malloc); cudaEventDestroy(stop_malloc); // Exit program return 0; } I ran cuda-memcheck on this test program, with -g & -G switches on, and it reports 0 problems. Can anyone spot the issue? NOTE: Be sure to have book.h from the CUDA by Example book in your current directory when you compile the program. Source link here: http://developer.nvidia.com/cuda-example-introduction-general-purpose-gpu-programming Download the source code, and book.h will be under the common directory/folder. A: Your kernel looks broken to me. The thread local search (before the shared memory reduction), should look something like this: sdata[tid] = g_idata[i]; i += gridSize; while (i < n) { sdata[tid] = MaxOf2(sdata[tid], g_idata[i]); i += gridSize; } shouldn't it? Also note that if you run this on Fermi, the shared memory buffer should be declared volatile, and you will get a noticeable improvement in performance if the thread local search is done with a register variable, rather than in shared memory. There is about an 8 times difference in effective bandwidth between the two. EDIT: Here is a simplified, working version of your reduction kernel. You should note a number of differences compared to your original: __global__ void MaxReduction(int n, float *g_idata, float *g_odata) { extern __shared__ volatile float sdata[]; unsigned int tid = threadIdx.x; unsigned int i = blockIdx.x*(BLOCKSIZE) + tid; unsigned int gridSize = BLOCKSIZE*gridDim.x; float val = g_idata[i]; i += gridSize; while (i < n) { val = MaxOf2(g_idata[i],val); i += gridSize; } sdata[tid] = val; __syncthreads(); // This versions uses a single warp for the shared memory // reduction # pragma unroll for(int i=(tid+32); ((tid<32)&&(i<BLOCKSIZE)); i+=32) sdata[tid] = MaxOf2(sdata[tid], sdata[i]); if (tid < 16) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 16]); if (tid < 8) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 8]); if (tid < 4) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 4]); if (tid < 2) sdata[tid] = MaxOf2(sdata[tid], sdata[tid + 2]); if (tid == 0) g_odata[blockIdx.x] = MaxOf2(sdata[tid], sdata[tid + 1]); } This code should also be safe on Fermi. You should also familiarise yourself with the CUDA math library, because there is a fmax(x,y) intrinsic which you should use in place of your MaxOf2 function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unicode SQL Query W/ Parameter instead N Prefix I have an insert query to execute from within a C# against a SQL Server database. The column I am inserting to is of type nvarchar. the data I am inserting to that column is non-english. Is it sufficient for me to use AddWithValue in order to pass the non-english data to the server? like this example: string dogName = "עברית"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand("INSERT INTO Dogs1(Name) VALUES @Name", connection)) { command.Parameters.AddWithValue("Name", dogName); command.ExecuteNonQuery(); } } Or must I use the N prefix to declare it unicode? like it says so here. A: If I am understanding the question correctly, you can explicitly set the SqlCommand parameter to be a specific data type. You will be able to set it to be nvarchar as shown by the following link: http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx This below code snippet is taken directly from MSDN: SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@CategoryName"; parameter.SqlDbType = SqlDbType.NVarChar; parameter.Direction = ParameterDirection.Input; parameter.Value = categoryName; This uses an explicitly created SqlParameter instance, but it is the same idea by indexing the SqlParameterCollection of the SqlCommand instance. A: I believe the link at the bottom is only really talking about values within SQL itself. As far as I'm aware, the code you've got should be absolutely fine - otherwise there'd be no way of specifying Unicode text. Of course, it's probably worth validating this - but I'd be very surprised if it didn't work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Performing data error correction on Byte level, to video stream Does anyone has an idea for efficient error correction algorithm? Suppose all the operations and manipulation on the stream is on the Byte level. A: Maybe Reed-Solomon error correction? A: Depends on what are requirements. Have a look at Raptor wiki. RFC is here. Qualcomm has nice video demonstration that might be of interest to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: Simple Arrays I'm making this array where the first number in the array should be 15 and the third as well. Then I need to print the array on the screen but I get an error when I do this, I've read that I got to write a loop when printing an array. How's that possible? This is my current code. int[] i = {15,0,15,0,0}; System.out.println(i); And what's the difference in using this method or using int [] i = new int [5]; Thanks in advance, Michael. A: To print an array use Arrays.toString(); import java.util.Arrays; System.out.println(Arrays.toString(i)); // or print it in the loop for(int e : i) { System.out.print(e); } About differences between two methods: int [] i = new int [5]; // five evements are allocated // the number of elements are determined by the initialization block int[] i = {15,0,15,0,0}; A: You could write a loop like this: for(int j=0; j < i.length; j++) { System.out.println("Value at index " + j + ": " + i[j]"); } A: That code executes just fine, although it's probably not the string you expect as the default value for toString() (which is what gets executed) is defined as: getClass().getName() + '@' + Integer.toHexString(hashCode()) To print the actual contents of the string you should employ the method suggested by e.g., @Oleg. The statement int[] i = {15,0,15,0,0}; is just shorthand for the more verbose int [] i = new int [5]; i[0] = 15; i[1] = 0; i[2] = 15; i[3] = 0; i[4] = 0; A: It's considered a "mistake" in java that there's no implementation for toString() - you get java.lang.Object implementation. Instead, you must use the static method Arrays.toString(array). Writing this int [] i = new int [5]; allocates memory for 5 elements, but they are all intitialized to zero (0). You would have to write more code to assign values to the elements. A: Either you could print like this: for (int index=0; index<i.length; index++) System.out.println("Array's value at index " + index + "is: " + i[index] ); Or you can use toString() function. A: The difference between the two is that int[] i = {15,0,15,0,0}; System.out.println(i); the elements are determined by a initialization block , while int [] i = new int [5]; five elements are allocated in the int i.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I add a variable to $(this)? I have two functions: function animateOpen(){ var originalPosition = $(this).css("left"); var distance = $(this).getHorzontalDistanceToCenter(); $(this).animate("left", "+="+distance); $('#button').click( function (){ $(this).animate("left", originalPosition+"px"); }); } function animateClose(){ $('#button').click(); } I want to convert this code to the bottom form (to remove the dependency on button): function animateClose(){ $(this).animate("left", originalPosition+"px"); } function animateOpen(){ var originalPosition = $(this).css("left"); var distance = $(this).getHorzontalDistanceToCenter(); $(this).animate("left", "+="+distance); } The problem is, how does animateClose get the originalPosition? Can I somehow put it in $(this)? A: You can save the original position using $(this).data('original_left', my_value) And afterwards, get the saved value with $(this).data('original_left') A: Wrap it in a closure and share originalPosition: (function(){ var originalPosition; function animateClose(){ $(this).animate("left", originalPosition+"px"); } function animateOpen(){ originalPosition = $(this).css("left"); var distance = $(this).getHorzontalDistanceToCenter(); $(this).animate("left", "+="+distance); } window.animateClose = animateClose; window.animateOpen = animateOpen; }()); A: Call $(this).data('some name', value). You can get the value later by calling $(this).data('some name').
{ "language": "en", "url": "https://stackoverflow.com/questions/7548382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get "close friends" list of a Facebook user, using the Graph API? The graph Api gives me the user's friends. But I want to know who its close friends are (SmartLists). How can I do that using the Graph API? A: You can call /me/friendlists to get the friends list. One of them should be close friends. Then go to /closeFriendsListId/members to see who is on that list. You will need read_friendlists extended permissions. A: I recently saw a simpler way. /me/friendlists/close_friends?fields=members will give you the list of all members at one shot. Just wanted to put it out here in case if somebody needs help. Similarly, call to /me/friendlists/family?fields=members will give family members. P.S: "close_friends" and "family" are keywords and no need for a ID. A: This is no longer possible. Facebook removed the ability to see the members of a friend list somewhere before version 2.5 of their API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: what is the semantically correct way to create an accordion widget? taking into account the semantic web and HTML5, what is the semantically correct way to create an accordion widget? example: jQueryUI proposes the following example: <div id="accordion"> <h3><a href="#">First header</a></h3> <div>First content</div> <h3><a href="#">Second header</a></h3> <div>Second content</div> </div> now if it is clear that we need a list that has a title and content, now that is what we would need then: a list of definitions? <dl> <dt> Title </dt> <dd> Content </dd> </dl> A: Semantics are based on the content. not the style, not the interaction. Because of this, there isn't going to be just one way to markup an accordion widget semantically. As an accordion widget is an interaction. dl's should be used for name-value groups, so it would be semantic to use a dl with an accordion widget if you've got "terms and definitions, metadata topics and values, questions and answers, or any other groups of name-value data.": <dl id="definitions"> <dt>...</dt> <dd>...</dd> <dt>...</dt> <dd>...</dd> ... </dl> If you've got a bunch of articles in an archive, it could be semantic to use: <h1>Archive</h1> <div id="articles"> <h2>...</h2> <article>...</article> <h2>...</h2> <article>...</article> ... </div> Before worrying about what the content should do, figure out what your content is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why is COM interface name replaced by coclass name in VB6? I am developing a C++ COM library to use it from a VB6 application. The .IDL file defines a few interfaces and a class library with some component classes that implement these interfaces: [ local, object, uuid(....), version(1.0) ] interface ICOMCvPixelBuffer : IUnknown { .... }; [ local, object, uuid(....), version(1.0) ] interface ICOMCvBitmap : IUnknown { .... HRESULT GetPixelBuffer([retval][out] ICOMCvPixelBuffer** pBuffer); HRESULT SetPixelBuffer([in] ICOMCvPixelBuffer* pBuffer); .... }; [ uuid(....), version(1.0) ] library COMCvLibrary { importlib("stdole32.tlb"); interface ICOMCvBitmap; interface ICOMCvPixelBuffer; [ uuid(....), version(1.0) ] coclass CCOMCvPixelBuffer { [default] interface ICOMCvPixelBuffer; }; [ uuid(....), version(1.0) ] coclass CCOMCvBitmap { [default] interface ICOMCvBitmap; }; }; The Object Browser in VB6 shows the definition of the SetPixelBuffer method of the CCOMCvBitmap class as Sub SetPixelBuffer(pBuffer As CCOMCvPixelBuffer). Why it is not Sub SetPixelBuffer(pBuffer As ICOMCvPixelBuffer) as declared in .IDL? A: Finally I found out an answer to my question. As I understood from the book ".NET and COM: The Complete Interoperability Guide", if the coclass's default interface is defined in the same class library as the coclass, the VB6's type library importer replaces any parameters and the fields of the default interface type with the coclass type. Also, a helpful information on the mechanics that stands behind the VB6 can be found here: Visual Basic uses the class module name as an alias for the default interface; that is, the Visual Basic compiler maps the class name to the default interface reference silently for you. One of the working solution is to supply IUnknown as the default interface of the CCOMCvPixelBuffer coclass: [ uuid(....), version(1.0) ] coclass CCOMCvPixelBuffer { [default] interface IUnknown; interface ICOMCvPixelBuffer; }; A: As far as I remember, VB6 does not like the idea that COM object implements 2+ automation interfaces. Along with this, if it implements one, then it quite assumable that the interface is implemented by coclass which is declared as implementing this interface: coclass CCOMCvBitmap { [default] interface ICOMCvBitmap; This way VB6 might be making it simpler for VB6 developer undestanding, trying to explain the working using objects rather than interfaces. If you are curios for an experiment, try to comment the line "[default] interface ICOMCvBitmap;" above and see if VB6 will show the type as interface. This should not break interoperation, as your ATL implementation object will still implement IProvideClassInfo and advertise implemented interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Entity Framework 4.1 Fluent mapping Foreign Key and the Foreign object with a string key I am moving from an EDMX mapping to the EF 4.1 DbContext and Fluent mapping and I am wanting to map both a string foreign key and the foreign object using the fluent API. I have an Employee with an Optional Office. I would like both the OfficeId and the Office Object in the Employee class (This is all read only, and I do not need to be able to save these objects). Objects with int keys work fine, but I have tried several with string keys and get the same result - the OfficeId field populates, but the Office object comes back as null. Chekcking in SQL profiler the data is being queried, but the office object is not being populated. public partial class Employee { public int Id { get; set; } // snip irrelevant properties public Office Office { get; set; } // this is (incorrectly) always null public string OfficeId { get; set; } public WorkGroup WorkGroup { get; set; } // this one with the int key is fine public int? WorkGroupId { get; set; } // snip more properties } public partial class Office { public string Id { get; set; } public string Description { get; set; } } public partial class WorkGroup { public int Id { get; set; } public string Code { get; set; } } After feedback from Ladislav below, I map it like this in the OnModelCreating modelBuilder.Entity<Employee>().HasKey(d => d.Id).ToTable("Employee", "ExpertQuery"); modelBuilder.Entity<Office>().HasKey(d => d.Id).ToTable("Office", "ExpertQuery"); modelBuilder.Entity<WorkGroup>().HasKey(d => d.Id).ToTable("WorkGroup", "ExpertQuery"); modelBuilder.Entity<Employee>() .HasOptional(a => a.Office) .WithMany() .Map(x => x.MapKey("OfficeId")); // this one does not work modelBuilder.Entity<Employee>() .HasOptional(e => e.WorkGroup) .WithMany() .HasForeignKey(e => e.WorkGroupId); // this one works fine I assume there is some subtlety with string keys that I am missing ? I am querying it as follows : var employees = expertEntities.Employees.Include("Office").Include("WorkGroup").Take(10).ToList(); If I omit the OfficeId field from Employee, and set up the mapping like this : modelBuilder.Entity<Employee>() .HasOptional(e => e.BusinessEntity) .WithMany() .Map(x => x.MapKey("OfficeId")); Then the office object is populated, but I need the OfficeId field in the Employee object. A: Well, I found the issue - it's a data issue - the primary key string values were space padded and the foreign key values were not (!). Although SQL joins the tables correctly (ignoring the padding) and fetches the correct data, it appears that EF will not correlate it back into the the correct objects as .NET is fussier than SQL about trailing blanks. A: Your customized mapping just conflicts because of the fact that you have already introduced a OfficeId property of string type. See what happens if you remove the OfficeId property from your Employee definition, or change it to int type. A: That is not correct mapping. If you have FK property you cannot use Map and MapKey. That is for scenarios where you don't have that property. Try this: modelBuilder.Entity<Employee>() .HasOptional(a => a.Office) .WithMany() .HasForeignKey(a => a.OfficeId); Also first part of your mapping with mapping entities to table is most probably incorrect. Map is used for inheritance and entity splitting scenarios. You are looking for ToTable: modelBuilder.Entity<Employee>().HasKey(d => d.Id).ToTable("ExpertQuery.Employee"); Also if your ExpertQuery is database schema and not part of table name it should look like: modelBuilder.Entity<Employee>().HasKey(d => d.Id).ToTable("Employee", "ExpertQuery");
{ "language": "en", "url": "https://stackoverflow.com/questions/7548391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving user images - reaching maximum folder limit I'm using ext3 and according to Wikipedia, the maximum sub directories allowed is around 32000. Currently, each user is given their own directory to upload images on the filesystem. This makes it simple to retrieve images and ease of access. the folder structure is like this: ../images/<user id>/<image> ../images/<another user id>/<image> I don't want to commit to a design that is doomed to fail with scalability, specifically when 32k users have upload images. While this may never be achieved, I still think it is bad practice. Does anyone have an idea to avoid this problem? I would prefer not to use the database if possible for reasons of unnecessary queries and speed. A: You could have a multi-level hierarchy, where each level is guaranteed to never exceed the maximum. For example, if your user ids are defined with the regular expression [A-Za-z0-9_]+, you have 64 possible choices for any given character (I'm adding a space to account for spaces at the end when ids are shorter). Taking two characters together you have 64*64 = 4096 total possibilities. You cannot do three characters as that takes you over your limit. Then with this info you can create the directories by splitting the ids in groups of two letters. Example: user ids "miguel" and "miguel12345" would go to: /images/mi/gu/el/<image> /images/mi/gu/el/12/34/5/<image> Note how the last component can be one char long if the length of the id is odd. This is fine, since the space is accounted as a possible char, you will still be within the max sub-directory limit. Good luck! A: Create a subdirectory for when the previous one gets full /images/<a>/<user id 1>/<image> /images/<a>/<user id 2>/<image> ... /images/<a>/<user id 32000>/<image> /image/<b>/<user id 32001>/<image> ... A: If i'm getting this right and this ir some sort of web app You could use some abstract layer to imitate that folder structure and save the files in one directory. save file real name in database, and save uploaded file with some unique name. then list users files from database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In eclipse, is it possible to change what the default package is without changing the source folder? I'm working with some people on a java project. Problem is, I'm the only one using eclipse. The source files are located in svn in trunk/src/*.java. However, if I import that as a project directory, the default package is "" instead of what the actual project package name is. Is there a way to change that without changing the source location and the package name? Thanks! A: If you mean that you want code in package foo.bar without having a matching directory folder of foo/bar under some source root - no, I don't think Eclipse supports that. While the convention of source locations having to match package structure isn't enforced by the language specification, it's mentioned there and so widely respected that I think it would be a bad idea to do anything else. A: Eclipse requires a directory structure that matches the package structure. There is no option to have some package prefix that isn't reflected in directories. IntelliJ can work with this, and it's what most people expect to see most of the time anway. A: I think you are checking out the incorrect root folder. If you are trying to work with a collection of source files located under trunk/src/ you may be don't need to check out this folder, because you will loose your reference to the main package (for example foo.bar) because it will be the base package. You may need to check out the trunk/ folder, because Eclipse expects to find the source files under the default /src folder. Once you have your main root folder (with a lot of files like .project, .classpath inside), it is likely possible that Eclipse will recognize your folder structure and configuration and your project will compile without problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting omnicppcomplete and ctags to work in VIM Here's my .vimrc syntax on set number set nowrap set autoindent " configure tags - add additional tags here or comment out not-used ones set tags+=~/.vim/tags/cpp_files set tags+=~/.vim/tags/cpp_src/ set tags+=~/.vim/tags/qt " build tags of your own project with Ctrl-F12 map C-F12 :!ctags -R --sort=yes --c++-kinds=+p --fields=+iaS --extra=+q .CR " OmniCppComplete let OmniCpp_NamespaceSearch = 1 let OmniCpp_GlobalScopeSearch = 1 let OmniCpp_ShowAccess = 1 let OmniCpp_ShowPrototypeInAbbr = 1 " show function parameters let OmniCpp_MayCompleteDot = 1 " autocomplete after . let OmniCpp_MayCompleteArrow = 1 " autocomplete after -> let OmniCpp_MayCompleteScope = 1 " autocomplete after :: let OmniCpp_DefaultNamespaces = ["std", "_GLIBCXX_STD"] " automatically open and close the popup menu / preview window au CursorMovedI,InsertLeave * if pumvisible() == 0|silent! pclose|endif set completeopt=menuone,menu,longest,preview autocmd FileType python set omnifunc=pythoncomplete#Complete autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS autocmd FileType html set omnifunc=htmlcomplete#CompleteTags autocmd FileType css set omnifunc=csscomplete#CompleteCSS autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags autocmd FileType php set omnifunc=phpcomplete#CompletePHP autocmd FileType c set omnifunc=ccomplete#Complete au BufNewFile,BufRead,BufEnter *.cpp,*.hpp set omnifunc=omni#cpp#complete#Main autocmd FileType cpp set omnifunc=cppcomplete#CompleteCPP I've followed this guide for getting it to work, but nothing really happens. As you can see I've tried a variation of autocmd and au type commands for this to work, but nothing actually happens. Am I doing something wrong? The paths in the set tags* lines are correct... A: This line should be the one that causes the problem: autocmd FileType cpp set omnifunc=cppcomplete#CompleteCPP You see, you have the following commands: au BufNewFile,BufRead,BufEnter *.cpp,*.hpp set omnifunc=omni#cpp#complete#Main autocmd FileType cpp set omnifunc=cppcomplete#CompleteCPP The thing is, the first autocommand is executed when entering a buffer with the extension "cpp" or "hpp". The second is executed when the filetype is set to cpp, which always happens after opening the buffer. It doesn't even matter how you order them, the second one will always be executed after the first one, so the omnifunc will always be set to cppcomplete#completeCPP, and you don't want that. You should replace both of these lines with this one line: autocmd FileType cpp set omnifunc=omni#cpp#complete#Main Just in case, if it still doesn't work, try only this instead: au BufNewFile,BufRead,BufEnter *.cpp,*.hpp set omnifunc=omni#cpp#complete#Main For future debugging issues, a small tip: you can check the value of omnifunc by executing set omnifunc. That way, you can check if the completion function really is the one you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: problems with char array = char array I have: char message1[100]; char message2[100]; When I try to do message1 = message2, I get error: incompatible types when assigning to type ‘char[100]’ from type ‘char *’ I have functions like if(send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize){ DieWithError("send() failed") } inbetween. Could these mess things up somehow? :( I have a feeling maybe you can't do = on char arrays or something, but I looked around and couldn't find anything. A: Your suspicions are correct. C (I'm assuming this is C) treats an array variable as a pointer. You need to read the C FAQ about arrays and pointers: http://c-faq.com/aryptr/index.html A: You can't assign anything to an array variable in C. It's not a 'modifiable lvalue'. From the spec, §6.3.2.1 Lvalues, arrays, and function designators: An lvalue is an expression with an object type or an incomplete type other than void; if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object. A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type. The error message you're getting is a bit confusing because the array on the right hand side of the expression decays into a pointer before the assignment. What you have is semantically equivalent to: message1 = &message2[0]; Which gives the right side type char *, but since you still can't assign anything to message1 (it's an array, type char[100]), you're getting the compiler error that you see. You can solve your problem by using memcpy(3): memcpy(message1, message2, sizeof message2); If you really have your heart set on using = for some reason, you could use use arrays inside structures... that's not really a recommended way to go, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Magento: Get simple product color from custom table I'm really struggling with this in Magento 1.10 Enterprise. I have a array of simple products color ids and I want to use this id to query the atb_color table. Raw query: SELECT description FROM atb_colors WHERE option_id = 'my_color_id' Here is a method I was trying to build: public function getColorData($product){ $ids = $product->getTypeInstance()->getUsedProductIds(); foreach($ids as $id){ $simpleproduct = Mage::getModel('catalog/product')->load($id); -->Query using my_color_id } } I can use this to get name and quantity. If I put this in the foreach loop: echo $simpleproduct->getName()." - ".(int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty() . '<br />'; How would I run this query. Forgive me I am very new to Magento. It's somewhat difficult to grasp some of it. But I'm on a deadline to finish this one section of displaying color and size. Any help? Please, please!! Thanks in advance A: This is the weirdest hack, but if you are really in big hurry public function getProductCustomColor($product) { $ids = $product->getTypeInstance()->getUsedProductIds(); foreach($ids as $id){ $simpleProduct = Mage::getModel('catalog/product')->load($id); $select = $product->getResource()->getReadConnection()->select() ->from('atb_colors', array('description')) ->where('option_id = :my_color_id'); $colorDescription = $product->getResource()->getReadConnection() ->fetchOne($select, array('option_id' => $simpleProduct->getYourColorId())); // ... } } To everyone: never write code for magento in this way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does this menu navigation not centre align? I have a website with a drop down navigation bar at the top, I would like to centre the navigation bar, but I can't get it to work, it seems to be stuck to the left side. You can view the website here and I've pasted the code below. I've been trying to get this to work all day, but I can't see where the problem is. I don't know what more to write, any help would be greatly appreciated. My style.css: #menu{ position: absolute; z-index: 1; padding:0; margin: auto; } #menu ul{ padding:0; margin:0; margin: auto; text-align: center; display: inherit; } #menu li{ position: relative; float: left; list-style: none; margin: 0; padding:0; } #menu li a{ width:100px; height: 30px; display: block; text-decoration:none; text-align: center; line-height: 30px; background-color: white; color: #7B99FF; font-size: 16px; } #menu li a:hover{ color: #000; } #menu li .subnav a { color: #7B99FF; font-size: 13px; } #menu li .subnav a:hover{ color: #000; font-size: 13px; } #menu ul ul{ position: absolute; top: 30px; visibility: hidden; } #menu ul li:hover ul{ visibility:visible; } .subnav { font-size: 13px; } My index.php: <div id="menu"> <ul> <li><a href="#nogo">About me</a> </li> <li><a href="#nogo">Categories</a> <ul class="subnav"> <li><a href="#nogo">Link 2-1</a></li> <li><a href="#nogo">Link 2-2</a></li> <li><a href="#nogo">Link 2-3</a></li> </ul> </li> <li><a href="#nogo">Archive</a> <ul class="subnav"> <li><a href="#nogo">Link 3-1</a></li> <li><a href="#nogo">Link 3-2</a></li> <li><a href="#nogo">Link 3-3</a></li> </ul> </li> <li><a href="#nogo">Contact</a> </li> </ul> </div> A: Remove the 'absolute' position of #menu and give it some width: #menu{ width:400px; z-index: 1; padding:0; margin: auto;} If you don't want to set width manually you can wrap your root in a div with style: text-align:center
{ "language": "en", "url": "https://stackoverflow.com/questions/7548417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to grab all words that start with capital letters? I want to create a Java regular expression to grab all words that start with a capital letter then capital or small letters, but those letters may contain accents. Examples : Where Àdónde Rápido Àste Can you please help me with that ? A: Regex: \b\p{Lu}\p{L}*\b Java string: "(?U)\\b\\p{Lu}\\p{L}*\\b" Explanation: \b # Match at a word boundary (start of word) \p{Lu} # Match an uppercase letter \p{L}* # Match any number of letters (any case) \b # Match at a word boundary (end of word) Caveat: This only works correctly in very recent Java versions (JDK7); for others you may need to substitute a longer sub-regex for \b. As you can see here, you may need to use (kudos to @tchrist) (?:(?<=[\pL\pM\p{Nd}\p{Nl}\p{Pc}[\p{InEnclosedAlphanumerics}&&\p{So}]])(?![\pL\pM\p{Nd}\p{Nl}\p{Pc}[\p{InEnclosedAlphanumerics}&&\p{So}]])|(?<![\pL\pM\p{Nd}\p{Nl}\p{Pc}[\p{InEnclosedAlphanumerics}&&\p{So}]])(?=[\pL\pM\p{Nd}\p{Nl}\p{Pc}[\p{InEnclosedAlphanumerics}&&\p{So}]])) for \b, so the Java string would look like this: "(?:(?<=[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}\\[\\p{InEnclosedAlphanumerics}&&\\p{So}]\\])(?![\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}\\[\\p{InEnclosedAlphanumerics}&&\\p{So}]\\])|(?<![\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}\\[\\p{InEnclosedAlphanumerics}&&\\p{So}]\\])(?=[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}\\[\\p{InEnclosedAlphanumerics}&&\\p{So}]\\]))\\p{Lu}\\p{L}*(?:(?<=[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}\\[\\p{InEnclosedAlphanumerics}&&\\p{So}]\\])(?![\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}\\[\\p{InEnclosedAlphanumerics}&&\\p{So}]\\])|(?<![\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}\\[\\p{InEnclosedAlphanumerics}&&\\p{So}]\\])(?=[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}\\[\\p{InEnclosedAlphanumerics}&&\\p{So}]\\]))" A: Code for to detect the Capital Letters in a given para. in this case input given as Console Input. import java.io.*; import java.util.regex.*; import java.util.Scanner; public class problem9 { public static void main(String[] args) { String line1; Scanner in = new Scanner(System.in); String pattern = "(?U)\\b\\p{Lu}\\p{L}*\\b"; line1 = in.nextLine(); String delimiter = "\\s"; String[] words1 = line1.split(delimiter); for(int i=0; i<words1.length;i++){ if(words1[i].matches(pattern)){ System.out.println(words1[i]); } } } } If you give the Input something like Input:This is my First Program output: This First Program A: You can do it without regular expression. Verify the first letter in each word by transforming it to lower case and then check equality: String firstLetter = String.valueOf(seq[i].charAt(0)); String lowerCase = firstLetter.toLowerCase(); if (!firstLetter.equals(lowerCase)) System.out.println(seq[i]); It will work with any accent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: International Phone Number Regex for Scraping Possible Duplicate: A comprehensive regex for phone number validation I've spent about two days searching for a regex that will find international phone numbers (using in scraping script), but I've run into a few problems.. * *I don't know the format(s), if they are similar lengths, etc.. *I suck at complex regex I had something that I thought worked, but then I saw a phone number from the UK that had a (0) before the 'area' code, which I've been told is not super common, but is used for within/outside numbers.. So what I need is a regex to be used in my Ruby script that will detect as many International phone numbers as possible, which accounts for this '(0)', and the possibility of a '+' in front of country code... Because this is for scraping, and I can assume people enter phone numbers in a formatted way, I can expect a space, a ., or a - in between the area code and last 4 digits.. EDIT - This is what I tried, and wasn't getting results with which led me here.. /((\+\d{1,3})[- .]?(\d{2})[- .]?)(\d{3,4})[- .]?(\d{4})/
{ "language": "en", "url": "https://stackoverflow.com/questions/7548425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple threads with locks vs single threads? I am designing a client and server socket program. I have a file to be transferred to the server from the client using UDP, I repeat I am using UDP..... I am sending through UDP so, the sending rate is too fast then the receiver, so I have created 3 threads listening on the same socket, so that when one thread is doing some work(I mean writing to a file using fwrite) with the received data the other thread can recv from the client. My 1st question is when I am using a fwrite with multiple threads I have to use locks as the file pointer is shared between the threads. I am right in thinking??? My 2nd question is "Will there be any improvement in the performance if I use multiple threads to fwrite using locks over using a single thread to do the fwrite work with no locks...??? " ... Please guide me... A: Cache the data before writing it. Let the writing happen in another thread. Doing it the way you do will require locking the socket. Q1: yes you do need to lock it (very slow!). Why not use a separate file descriptor in each thread? the problem comes mostly with the current file position managed by that descriptor. Q2: Neither. If data needs ordering (yes, UDP!) you should still buffer it. RAM is much faster then disk IO. Feed a stream to buffer it and handle the data in that stream in a separate thread. A: I would use one thread. Saves the complications. You can buffer the data and use asynchronous writes http://www.gnu.org/s/hello/manual/libc/Asynchronous-Reads_002fWrites.html A: My 1st question is when I am using a fwrite with multiple threads I have to use locks as the file pointer is shared between the threads Yes, you always have to use locks when multiple threads are writing to a single object (file, memory, etc). My 2nd question is "Will there be any improvement in the performance if I use multiple threads to fwrite using locks over using a single thread to do the fwrite work with no locks...??? " I would use two threads. The first thread does nothing but read from the socket and store the data in memory. The second thread reads data from memory and writes it to the file. Treat the memory buffer as a FIFO queue and use a mutex to protect the queue pointers. You'll gain nothing from a third thread. In fact, it would probably harm performance and it definitely makes the problem far more complicated. A: Similar to Ed's answer, I'd suggest using asynchronous I/O and a single thread for your server. Though I find using Boost.Asio easier than posix AIO. A: First, try to avoid using UDP for bulk transfers. If you use UDP you have to reinvent your own flow control protocol, as well as logic for retransmission and reordering. From the sounds of it, your problems boil down to missing flow control - so why not just use TCP? Anyway, don't put your file writing in another thread. Modern OSes will internally buffer disk writes in any case - you'll only start blocking if you're writing data much faster than the disk can keep up, in which case buffering inside your process will only buy you another few seconds at most. Switch to TCP, or implement a proper flow control mechanism.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Chargify vs Amazon's, Google's and PayPal's payment service? I wanna build a web store for selling people's second hand products. * *A customer adds the products into a shopping cart. *He/she pays (credit card, bank account) for it and I get the money. *The seller sends the bought products to the customer. *I get send the money to the seller (and have taken a fee for it). People tend to mention Amazon's, Google's and PayPal's payment service but recently I came across services like Chargify and Recurly. My questions: * *How do these two differ from the other three? *Which one would support the above mentioned transaction process? *How should I set up the above transaction process? *The "big 3" require an account. How do I charge with just a credit card or bank account only? Thanks! A: Thanks for thinking of Chargify. We're not the right thing for your need... we focus on helping a business manage many things involved in recurring billing of customers. For what you want to do, I think one of the "Big 3" is the way to go. You've got the extra "wrinkle" of this, however: you're essentially collecting money on behalf of each Seller, and each Seller may be selling very different things and will have different levels of honesty, etc. All of my experience is with merchants that have a traditional merchant account and payment gateway, which together allow them to charge credit cards. But the banks that issue merchant accounts want to know what each merchant (each Seller) is about. I'm 99% sure the banks dislike a single merchant account being used to sell / collect credit card payments for more than one merchant. Anyway, to the degree that it's useful, I wrote a blog post last year about merchant accounts and payment gateways. It may be helpful to you as you explore options: https://lancewalley.wordpress.com/2010/06/22/merchant-accounts-payment-gateways/ A: See my answer in Online payments for a middleman. PayPal Adaptive Payments allows you to accept guest payments, without requiring buyers to have a PayPal account. Another thing to think about is regional availability; Amazon / Google may sound interesting, but are not very useful if you don't live in the US or UK. Whereas PayPal Adaptive Payments is available pretty much globally (with the exception of a few countries where PayPal hasn't launched yet).
{ "language": "en", "url": "https://stackoverflow.com/questions/7548428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JIT / AOT problems when running montouch app I have been developing a monotouch opengl iphone game for some weeks now. As recently as yesterday, it was building and running properly on my test hardware (an iPhone 4). But when I loaded the project yesterday, it gave me the compiler error: Framework 'Mono for iPhone' not Installed. I can't think of any reason for this, I had not changed my system or source code. Luckily Monodevelop was already harassing me with a download link for the latest api download. I installed and the error went away. But instead, I now get a runtime error when the app starts http://screencast.com/t/EXyNqqhNoEsu : System.ExecutionEngineException has been thrown. Attempting to JIT compile method ... FirstOrDefault ... while running with --aot-only. This occurs while trying to create a new DataContractSerializer to load some XML settings: http://screencast.com/t/4SDzU5ygg This compelled me for the first time to change the Linker behavior setting under the app's project options. It was set to 'Don't link', as it has been. When I switch to 'Link SDK assemblies only', it runs without the above exception. This would be great, problem solved, except that it takes almost half an hour (!) to compile and deploy to the phone in this mode. The build output sits on 'Linking SDK only for assembly...'. Is this normal? I don't think I can keep my sanity with build times that long. Even 'Don't Link' takes about five minutes which is a grueling pace when you're trying to troubleshoot. To reiterate, this is code that was working every day for weeks, and to my knowledge has not been changed from its working state. Does anyone know why this error is occurring now, and what a resolution might be to continue using the 'Don't Link' option? A: Framework 'Mono for iPhone' not Installed. For some reason MonoDevelop could not find your MonoTouch installation. I can't say why, but restarting MonoDevelop and checking the MD preferences for SDK Locations (and fix the path if MonoTouch was not found) would have been the best options to try. System.ExecutionEngineException has been thrown. Attempting to JIT compile method ... FirstOrDefault ... while running with --aot-only. MonoTouch 4.2[.1] can sometime throw a ExecutionEngineException when the "Don't link" linker option is selected. This bug was fixed and will be part of future releases of MonoTouch. FWIW Link SDK assemblies is the default and should always be used for device builds. The linker will produce much smaller applications and it also allows faster builds in most circumstances (because the linker can save 100kb faster than the AOT compiler can process that 100kb). If you hit a case where the linker takes a very long time then something is wrong (or at least weird) in your project. Please take the time to fill a bug report at http://bugzilla.xamarin.com so we can investigate why this takes so long.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: solr: multivalued dateranges (representing opening hours) Consider a bar which might have multiple openinghours, depending on the day of week (+ some special days when it might be closed) I want to be able to lookup all bars that are currently open and that will be open for the next, say, 3 hours. (or be able to ask: 'open on 18-10-2011 from 7 until (at least) 10 ) The best thing I believe would be to have a 'open,close'-tuple for each date (other suggestions welcome) Without, as far as I know ?, a fieldtype that combines open/close hours in 1 field, I can naively (but wrongly) define this structure using 2 fields: 'open' and 'closed', which need to be multivalued. Now index them like: open: 2011-11-08:1800 - close: 2011-11-09:0300 open: 2011-11-09:1700 - close: 2011-11-10:0500 open: 2011-11-10:1700 - close: 2011-11-11:0300 And queries would be of the form: open < now && close > now+3h But since there is no way to indicate that 'open' and 'close' are pairwise related I will get a lot of false positives, e.g the above document would be returned for: open < 2011-11-09:0100 && close > 2011-11-09:0600 because SOME opendate is before 2011-11-09:0100 (i.e: 2011-11-08:1800) and SOME closedate is after 2011-11-09:0600 (for example: 2011-11-11:0300) but these open and close-dates are not pairwise related. I have been thinking about a totally different approach using Solr dynamic fields, in which each and every opening and closing-date gets it's own dynamic field, e.g: * *_date_2011-11-09_open: 1800 *_date_2011-11-09_close: 0300 *_date_2011-11-09_open: 1700 *_date_2011-11-10_close: 0500 *_date_2011-11-10_open: 1700 *_date_2011-11-11_close: 0300 Then, the client should know the date to query, and thus the correct fields to query. This would solve the problem, since startdate/ enddate are nor pairwise -related, but I fear this can be a big issue from a performance standpoint (especially memory consumption of the Lucene fieldcache) Thusfar, I haven't found a satisfactory solution. Any help highly appreciated. A: While keeping granularity on Bars like I want (instead of BarsxDate) it's possible to use the expirimental Lucene Spatial Playground implementation. The use-case + general solution is here: https://issues.apache.org/jira/browse/SOLR-2155?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=comment-13115244#comment-13115244 A: First a question - do you really have open times for dates? not days of the week? but leaving that aside (it doesn't change the answer in any important way), what you should do is create a document for every bar/date combination. In each of these documents you will need all the fields you are planning to search on; maybe that includes location, bar name, etc. So those fields will be denormalized (duplicated across many related documents). That way you can do the query you describe and get precise results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to remove subversion repository for a specified project from netbeans? I imported a project into subversion from netbeans now I simply want to undo that action and want the file stored in repository for that specified project alone be removed. How do I have to proceed? A: * *Delete all .svn folders inside your project. Eclipse has a Team / Disconnect function for this. Maybe Netbeans also support it. If not, you can do it by hand or with a simple shell script. *With a repository browser delete the project's folder from SVN. I don't know that Netbeans supports it or not. If not, you can use the command line svn client (svn delete <url>) or TortoiseSVN for example. A: Under TEAM menu. Choose DISCONNECT option to disconnect code from SVN
{ "language": "en", "url": "https://stackoverflow.com/questions/7548443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VS08-WIN7-What account does ASP.NET web server run as? VS08-WIN7-What account does VS08's ASP.NET development web server run as? I am trying to write to a log file. protected void Page_Load(object sender, EventArgs e) { System.Diagnostics.Trace.WriteLineIf(lifecycleSwitch.TraceInfo, string.Format("{0:yyyy-MM-dd HH:mm:ss.ffff}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}", DateTime.Now, "Page", this.GetType().Name, "Page_Load", "Start", User.Identity.Name, Thread.CurrentThread.ManagedThreadId, Request.Url.PathAndQuery, Session.SessionID)); Response.Write(Environment.UserName); System.Diagnostics.Trace.WriteLineIf(lifecycleSwitch.TraceInfo, string.Format("{0:yyyy-MM-dd HH:mm:ss.ffff}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}", DateTime.Now, "Page", this.GetType().Name, "Page_Load", "Start", User.Identity.Name, Thread.CurrentThread.ManagedThreadId, Request.Url.PathAndQuery, Session.SessionID)); } But, the log file keeps displaying empty. Is it a permissions issue on the folder where the logfile lives? Here is the corresponding web.config section. <system.diagnostics> <switches> <add name="Lifecycle" value="4"/> </switches> <trace autoflush="false" indentsize="0"> <listeners> <add name="LifecycleLog" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\Logs\lifecycle.log"/> </listeners> </trace> A: the web server runs with your identity
{ "language": "en", "url": "https://stackoverflow.com/questions/7548445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show alert after postback I have a button which calls stored procedure and binds gridview. I found a code on stackoverflow for top alert bar like this: function topBar(message) { var alert = $('<div id="alert">' + message + '</div>'); $(document.body).append(alert); var $alert = $('#alert'); if ($alert.length) { var alerttimer = window.setTimeout(function () { $alert.trigger('click'); }, 10000); $alert.animate({ height: $alert.css('line-height') || '50px' }, 500).click(function () { window.clearTimeout(alerttimer); $alert.animate({ height: '0' }, 200); }); } } Then in my button I try to call this function like this: Dim script As String = String.Format("topBar({0});", Server.HtmlEncode("Successfully Inserted")) Response.Write(script) 'Or even like this ClientScript.RegisterStartupScript(Page.GetType(), "topBar", script, True) But it simply does not work. Can you guide me in right direction? A: I always sort this type of problems with supplying a Boolean Property whether javascript should fire a piece of script or not. For example : public bool IsDone { get; set; } Sorry that the code is in C# This is a property on code behind file. When I need to fire the javascript method, I simply make this true. What I do on the aspx page is as follows : <script> if(<%= IsDone.ToString().ToLower() %>) { alert("Done!"); } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7548448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checking if the UNIX timestamp stored in MySQL DB is this weeks or this months? I have a MySQL DB, and in one of the tables I have stored the time in which the content was submitted its in the form of a UNIX timestamp, the column is called content_time. Below are two pseudo examples of queries to demonstrate what I'm trying to accomplish, just not sure how to go by doing this (although I understand I will need do some some comparisons between the current and stored timestamps within the WHERE clause): SELECT * FROM content WHERE content_time = THIS WEEKS (the content was posted at any time/day within the current week) SELECT * FROM content WHERE content_time = THIS MONTHS (the month and year from content_time match with the current) Appreciate all help. A: See MySQL's Date and Time Functions, specifically FROM_UNIXTIME(), WEEK() and MONTH(). Keep in mind that when checking is it the same week or month you probably also want to check is it the same year. Another option is to generate start and end timestamps for the time range youre intrested in (ie timestamp for the beginning of the week and for the end of the week) and then use WHERE(content_time BETWEEN start AND end)
{ "language": "en", "url": "https://stackoverflow.com/questions/7548455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to cache only the content page I've got a master page with a content page loaded on to it, the content page is cached <%@ OutputCache Duration="360" VaryByParam="none" %> in the master page iv'e got a login control above the content , now if i attempt to use the control nothing happens since the content and the master binned to it are cached so the Response is redirect . * *How could i cache only the content ? *Or alternately how can i make it so the login event refreshes the cached content page? OK : Adding my attempts to resolve the situation (1) iv'e declared an OutputCache directive in the User Control itself the problem now is that it wasn't recognized (it's null) when i redirect to other pages so i added the shared attribute to its directive <%@ OutputCache Duration="360" VaryByParam="none" Shared="true" %> but it's still null when redirecting to different pages. A: Well, a wild idea which comes to my mind first is to put that dynamic content in a separate page and then reference it as <iframe> on your master page. It will cache all of the things but won't cache the content of the iframe. Also have a look at below document : Caching Portions of an ASP.NET Page http://msdn.microsoft.com/en-us/library/h30h475z.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7548456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql query optimisation - 50k+ Rows I'm querying 50k+ rows with this query and it is taking 1.2759 seconds. What do you think is the best way to optimise it. The data updates every second or so but I could cache it for say 20 seconds. I've been looking into memcached for this, but is there a way to optimize this query? There is already indexes on most of the columns. SELECT `p`.`id` as performance_id, `p`.`performers`, `t`.`name` as track_name, `p`.`location`, `p`.`es_id` FROM (`performances` p) JOIN `users` u ON `p`.`user_id` = `u`.`id` JOIN `tracks` t ON `p`.`track` = `t`.`id` WHERE (p.status = 1 OR (p.status != 2 && p.flagged < 3)) AND `p`.`prop` IN ('1', '2', '3', '4', '5', '6', '8', '11', '13') AND `p`.`track` IN ('5', '15', '2', '3', '8', '6', '12', '4', '1') AND `p`.`type` IN ('1', '0', '2') ORDER BY `p`.`created` desc LIMIT 12 Update: So here is the output from my EXPLAIN plan. +----+-------------+-------+--------+----------------------------------------+---------+---------+----------------------------------+-------+-----------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+----------------------------------------+---------+---------+----------------------------------+-------+-----------------------------+ | 1 | SIMPLE | p | range | user_id,track,prop,flagged,status,type | status | 2 | NULL | 27440 | Using where; Using filesort | | 1 | SIMPLE | u | eq_ref | PRIMARY,id | PRIMARY | 3 | staging.p.user_id | 1 | Using index | | 1 | SIMPLE | t | eq_ref | PRIMARY | PRIMARY | 4 | staging.p.track | 1 | Using where | +----+-------------+-------+--------+----------------------------------------+---------+---------+----------------------------------+-------+-----------------------------+ 3 rows in set (0.00 sec) A: Do what duffymo said, explain, and create indexes. This will do 99% of the stuff you need If you want to make it even faster you can also do this: * *Enable query cache query_cache_size = 268435456 query_cache_type=1 query_cache_limit=1048576 *You may also increase the table cache size A: MySQL can only use a single index at each stage of the query. You have many single-column indexes, but only one of them will be used for your query. To better make use of indexes, try adding a multi-column index. As an example, you could try this 4-column index: (status, type, prop, track) Both the columns you include in your index and the order of them will affect the speed of the query. It's hard to tell the best order without knowing the distribution of your data, so feel free to experiment a bit. You can add more than one index, run the query to see which index was actually used, then remove the other unused indexes. A: Run EXPLAIN PLAN on your query and look for table scans. If you find one, think about adding indexes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Statistical method for grading a set of exponential data I have a PHP application that allows the user to specify a list of countries and a list of products. It tells them which retailer is the closest match. It does this using a formula similar to this: ( (number of countries matched / number of countries selected) * (importance of country match) + (number of products matched / number of products selected) * (importance of product match) ) * (significance of both country and solution matching * (coinciding matches / number of possible coinciding matches)) Where [importance of country match] is 30%, [importance of product match] is 10% and [significance of both country and solution matching] is 2.5 So to simplify it: (country match + product match) * multiplier. Think of it as [do they operate in that country? + do they sell that product?] * [do they sell that product in that country?] This gives us a match percentage for each retailer which I use to rank the search results. My data table looks something like this: id | country | retailer_id | product_id ======================================== 1 | FR | 1 | 1 2 | FR | 2 | 1 3 | FR | 3 | 1 4 | FR | 4 | 1 5 | FR | 5 | 1 Until now it's been fairly simple as it has been a binary decision. The retailer either operates in that country or sells that product or they don't. However, I've now been asked to add some complexity to the system. I've been given the revenue data, showing how much of that product each retailer sells in each country. The data table now looks something like this: id | country | retailer_id | product_id | revenue =================================================== 1 | FR | 1 | 1 | 1000 2 | FR | 2 | 1 | 5000 3 | FR | 3 | 1 | 10000 4 | FR | 4 | 1 | 400000 5 | FR | 5 | 1 | 9000000 My problem is that I don't want retailer 3 selling ten times as much as retailer 1 to make them ten times better as a search result. Similarly, retailer 5 shouldn't be nine thousand times better as a match than retailer 1. I've looked into using the mean, the mode and median. I've tried using the deviation from the mean. I'm stumped as to how to make the big jumps less significant. My lack of ignorance of the field of statistics is showing. Help! A: Consider using the log10() function. This reduces the direct scaling of results, like you were describing. If you log10() of the revenue, then someone with a revenue 1000 times larger receives a score only 3x larger. A: A classic in "dampening" huge increases in value are the logarithms. If you look at that Wikipedia article, you see that the function value initially grows fairly quickly but then much less so. As mentioned in another answer, a logarithm with base 10 means that each time you multiply the input value by ten, the output value increases by one. Similarly, a logarithm with base two will grow by one each time you multiply the input value by two. If you want to weaken the effect of the logarithm, you could look into combining it with, say, a linear function, e.g. f(x) = log2 x + 0.0001 x... but that multiplier there would need to be tuned very carefully so that the linear part doesn't quickly overshadow the logarithmic part. Coming up with this kind of weighting is inherently tricky, especially if you don't know exactly what the function is supposed to look like. However, there are programs that do curve fitting, i.e. you can give it pairs of function input/output and a template function, and the program will find good parameters for the template function to approximate the desired curve. So, in theory you could draw your curve and then make a program figure out a good formula. That can be a bit tricky, too, but I thought you might be interested. One such program is the open source tool QtiPlot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problem Binding array of Processes to WPF ListBox Ok, so I am trying to implement a fairly straightforward feature in my app. I want to have a list of processes running (listed by their process name, ID, whatever) and when I click on a process in the list, update a few labels with information on that process (again, process name, ID, stuff like that). After having a look at MSDN docs for DataBinding with Collections, I created my own custom class ProcessList that inherits from ObservableCollection. The class is completely bare now, I had previously been messing around with it trying to get things to work so I guess I may as well just be working straight with an ObservableCollection, but anyway. Here is what I have at the moment: public partial class MainWindow : Window { private Dictionary<int, Injector> injectors; public Process[] processes; public ProcessList procList; public MainWindow() { procList = new ProcessList(); foreach (var p in Process.GetProcesses()) { procList.Add(p); } InitializeComponent(); processGrid.DataContext = procList; } private void button_refresh_processes_Click(object sender, RoutedEventArgs e) { processes = Process.GetProcesses(); } } } And the pertinent XAML: <Grid Name="processGrid" Margin="0,21,0,0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="348*" /> <ColumnDefinition Width="145*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="147*" /> <RowDefinition Height="42*" /> </Grid.RowDefinitions> <Button Content="Inject" Grid.Row="1" Height="23" HorizontalAlignment="Center" Margin="0,0,0,0" Name="button_inject" VerticalAlignment="Center" Width="75" /> <ListBox Height="147" HorizontalAlignment="Left" Name="process_list" VerticalAlignment="Top" Width="348" ItemsSource="{Binding Path=ProcessName}" /> <Grid Grid.Column="1" Height="147" HorizontalAlignment="Left" Name="grid2" VerticalAlignment="Top" Width="145"> <Grid.RowDefinitions> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*" /> <ColumnDefinition Width="1*" /> </Grid.ColumnDefinitions> <Label Content="Process ID:" Grid.RowSpan="1" Height="28" HorizontalAlignment="Left" Margin="0" Name="label_pid" VerticalAlignment="Center" /> <Label Content="PID" Grid.Column="1" Grid.RowSpan="1" Height="28" HorizontalAlignment="Right" Margin="0" Name="label_pid_value" VerticalAlignment="Center" /> </Grid> <Button Content="Refresh" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="6,9,0,0" Name="button_refresh_processes" VerticalAlignment="Top" Width="75" Click="button_refresh_processes_Click" /> </Grid> The problem I am currently having is that instead of displaying a list of all currently running processes by their ProcessName, it instead lists what appears to be each character from the first process's name as seperate entries in the list, and nothing more. Screenshot I have no idea what is going on, though I'm sure I'm doing something extremely stupid as I am very new to WPF development and Data Binding. A: I am wondering why you are getting an output at all. ItemsSource="{Binding Path=ProcessName}" Means the source of items is the ProcessName. The name is a string and a string is an IEnumerable<Char>. So the listbox displays each char as one entry. You have to set the ItemsSource to the list itself. In your case it would be ItemsSource="{Binding}" Because the ProcessList is already the data context of your grid, which gets inherited to the listbox. If you are not using a view model class (which is best practice when working with the MVVM pattern) you can do a DataContext = this; in your windows constructor to set the data context of the window to its own code-behind. If you do this the binding of your list would change to ItemsSource="{Binding procList}" However you should introduce a property and implement INotifyPropertyChanged so your UI is notified and updated when the datasource changes. TL;DR version: taking a look at guides to XAML/Bindings and the MVVM Pattern is required if you want to take use full use of WPF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery filter toggler function to show/hide images I'm trying to create a "filter toggler" with jQuery, to use for showing/hiding images on a page that has different categories applied to them (using a rel attribute). The filter is outside the list of images, so I need to address them by comparison (I think?) of values. I can't seem to find a way of applying the "On" switch for fading out all images that are not of the current category. See code below: $('#filter a').toggle(function() { // On $('.nodes a').removeClass('inactive'); $('.nodes a').animate({opacity: 1}, 250); $('.nodes a').animate({opacity: 1}, 1); $('filter a').animate({opacity: 0.5}, 1); $(this).animate({opacity: 1}, 1); var filter = $(this).attr('rel'); $('.nodes span').not('.' + filter).parent().addClass('inactive'); $('.nodes a.inactive').animate({opacity: 0.5}, 250); $('#filter a').not(this).animate({opacity: 0.5}, 250); }, function() { // Off (Reset) $('.nodes a').removeClass('inactive'); $('.nodes a').animate({opacity: 1}, 250); $('#filter a').animate({opacity: 1}, 250); }); The HTML structure is as this - <ul class="nodes"> <li> <a> <span> <img> </span> </a> </li> </ul> <div id="filter"> <ul> <li> <a href="#" rel="category">Category</a> </li> <ul> </div> Edit: Found a solution, see updated code. Could probably use more tweaking but it will do for now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Converting adjectives and adverbs to their noun forms I am experimenting with word sense disambiguation using wordnet for my project. As a part of the project, I would like to convert a derived adjective or an adverb form to it's root noun form. For example beautiful ==> beauty wonderful ==> wonder * *How can I achieve this? Is there any other dict other than wordnet that provides this kind of transformation? *It would be an added bonus for me if I can map the exact sense of the adjective word to its noun form with exact sense. Is that possible? Thank you A: Search google or SO for terms like 'stemming' and 'lemmatization', these terms might help you get what you are looking for. For example, go to http://qaa.ath.cx/porter_js_demo.html and enter the words 'beautiful' and 'beauty', and you will see they both stem to the same token. Porter stemmer essentially removes common suffixes found in the english language, so is by no means definitive, but is a pretty good place to start. You can consider words that map to the same stem to be in some sense synonymous. If you can procure part of speech tags for all these words as well, you will be able to infer that beauty is the noun form of the adjective beautiful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I create a packaged_task with parameters? Following this excellent tutorial for futures, promises and packaged tasks I got to the the point where I wanted to prepare my own task #include <iostream> #include <future> using namespace std; int ackermann(int m, int n) { // might take a while if(m==0) return n+1; if(n==0) return ackermann(m-1,1); return ackermann(m-1, ackermann(m, n-1)); } int main () { packaged_task<int(int,int)> task1 { &ackermann, 3, 11 }; // <- error auto f1 = task1.get_future(); thread th1 { move(task1) }; // call cout << " ack(3,11):" << f1.get() << endl; th1.join(); } As far as I can decipher the gcc-4.7.0 error message it expects the arguments differently? But how? I try to shorten the error message: error: no matching function for call to 'std::packaged_task<int(int, int)>::packaged_task(<brace-enclosed initializer list>)' note: candidates are: std::packaged_task<_Res(_ArgTypes ...)>::---<_Res(_ArgTypes ...)>&&) --- note: candidate expects 1 argument, 3 provided ... note: cannot convert 'ackermann' (type 'int (*)(int, int)') to type 'std::allocator_arg_t' Is my variant how I provide the parameters for ackermann wrong? Or is it the wrong template parameter? I do not give the parameters 3,11 to the creation of thread, right? Update other unsuccessful variants: packaged_task<int()> task1 ( []{return ackermann(3,11);} ); thread th1 { move(task1) }; packaged_task<int()> task1 ( bind(&ackermann,3,11) ); thread th1 { move(task1) }; packaged_task<int(int,int)> task1 ( &ackermann ); thread th1 { move(task1), 3,11 }; hmm... is it me, or is it the beta-gcc? A: Since you're starting the thread with no arguments, you expect the task to be started with no arguments, as if task1() were used. Hence the signature that you want to support is not int(int, int) but int(). In turn, this means that you must pass a functor that is compatible with this signature to the constructor of std::packaged_task<int()>. Try: packaged_task<int()> task1 { std::bind(&ackermann, 3, 11) }; Another possibility is: packaged_task<int(int,int)> task1 { &ackermann }; auto f1 = task1.get_future(); thread th1 { move(task1), 3, 11 }; because the constructor of std::thread can accept arguments. Here, the functor you pass to it will be used as if task1(3, 11) were used. A: Firstly, if you declare std::packaged_task to take arguments, then you must pass them to operator(), not the constructor. In a single thread you can thus do: std::packaged_task<int(int,int)> task(&ackermann); auto f=task.get_future(); task(3,11); std::cout<<f.get()<<std::endl; To do the same with a thread, you must move the task into the thread, and pass the arguments too: std::packaged_task<int(int,int)> task(&ackermann); auto f=task.get_future(); std::thread t(std::move(task),3,11); t.join(); std::cout<<f.get()<<std::endl; Alternatively, you can bind the arguments directly before you construct the task, in which case the task itself now has a signature that takes no arguments: std::packaged_task<int()> task(std::bind(&ackermann,3,11)); auto f=task.get_future(); task(); std::cout<<f.get()<<std::endl; Again, you can do this and pass it to a thread: std::packaged_task<int()> task(std::bind(&ackermann,3,11)); auto f=task.get_future(); std::thread t(std::move(task)); t.join(); std::cout<<f.get()<<std::endl; All of these examples should work (and do, with both g++ 4.6 and MSVC2010 and my just::thread implementation of the thread library). If any do not then there is a bug in the compiler or library you are using. For example, the library shipped with g++ 4.6 cannot handle passing move-only objects such as a std::packaged_task to std::thread (and thus fails to handle the 2nd and 4th examples), since it uses std::bind as an implementation detail, and that implementation of std::bind incorrectly requires that the arguments are copyable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Injecting properties into a QuartzJobObject Am I right in thinking that my QuartzJobObject can't have any DAO's or other Spring-managed objects injected into it? Was hoping I could do something like this (orderService is what I want to inject): <object name="checkPendingOrdersJob" type="Spring.Scheduling.Quartz.JobDetailObject, Spring.Scheduling.Quartz"> <property name="JobType" value="Munch.ScheduledTasks.CheckPendingOrdersJob" /> <!-- We can inject values through JobDataMap --> <property name="JobDataAsMap"> <dictionary> <!--entry key="UserName" value="Alexandre" /--> </dictionary> </property> <property name="orderService" ref="orderService"/> </object> ...which I know doesn't make sense because of the type it is. But, I could do with being able to inject some DAO's, Services etc somehow. I can't figure it out though. How can I do this? A: This is what I've ended up with and it works perfectly (hopefully useful to someone else) Job factory that is aware of Spring's context /// <summary> /// A custom job factory that is aware of the spring context /// </summary> public class ContextAwareJobFactory : AdaptableJobFactory, IApplicationContextAware { /// <summary> /// The spring app context /// </summary> private IApplicationContext m_Context; /// <summary> /// Set the context /// </summary> public IApplicationContext ApplicationContext { set { m_Context = value; } } /// <summary> /// Overrides the default version and sets the context /// </summary> /// <param name="bundle"></param> /// <returns></returns> protected override object CreateJobInstance(TriggerFiredBundle bundle) { return m_Context.GetObject(bundle.JobDetail.JobType.Name, bundle.JobDetail.JobType); } } The job itself (checks the DB for records and if there are at least HomeManyMenuItemsIsOK of them, everything is good). Note: menuService is an injected spring-managed object that itself has several DAO's in it). HowManyMenuItemsIsOK is a static property that's passed in through the job data map. public class CheckMenuIsHealthyJob : QuartzJobObject { private static readonly ILog log = LogManager.GetLogger(typeof(CheckMenuIsHealthyJob)); public IMenuService menuService { get; set; } public int HowManyMenuItemsIsOK { get; set; } /// <summary> /// Check how healthy the menu is by seeing how many menu items are stored in the database. If there /// are more than 'HowManyMenuItemsIsOK' then we're ok. /// </summary> /// <param name="context"></param> protected override void ExecuteInternal(JobExecutionContext context) { IList<MenuItem> items = menuService.GetAllMenuItems(); if (items != null && items.Count >= HowManyMenuItemsIsOK) { log.Debug("There are " + items.Count + " menu items. Menu is healthy!"); } else { log.Warn("Menu needs some menu items adding!"); } } } And finally the Spring config <!-- Scheduled Services using Quartz --> <!-- This section contains Quartz config that can be reused by all our Scheduled Tasks ----> <!-- The Quartz scheduler factory --> <object id="quartzSchedulerFactory" type="Spring.Scheduling.Quartz.SchedulerFactoryObject, Spring.Scheduling.Quartz"> <!-- Tell Quartz to use our custom (context-aware) job factory --> <property name="JobFactory" ref="contextAwareJobFactory"/> <!-- Register the triggers --> <property name="triggers"> <list> <ref object="frequentTrigger" /> </list> </property> </object> <!-- Funky new context-aware job factory --> <object name="contextAwareJobFactory" type="Munch.Service.ScheduledTasks.ContextAwareJobFactory" /> <!-- A trigger that fires every 10 seconds (can be reused by any jobs that want to fire every 10 seconds) --> <object id="frequentTrigger" type="Spring.Scheduling.Quartz.CronTriggerObject, Spring.Scheduling.Quartz" lazy-init="true"> <property name="jobDetail" ref="checkMenuIsHealthyJobDetail" /> <property name="cronExpressionString" value="0/10 * * * * ?" /> </object> <!-- Now the job-specific stuff (two object definitions per job; 1) the job and 2) the job detail) --> <!-- Configuration for the 'check menu is healthy job' --> <!-- 1) The job --> <object name="checkMenuIsHealthyJob" type="Munch.Service.ScheduledTasks.CheckMenuIsHealthyJob" singleton="false"> <property name="menuService" ref="menuService"/> </object> <!-- 2) The job detail --> <object name="checkMenuIsHealthyJobDetail" type="Spring.Scheduling.Quartz.JobDetailObject, Spring.Scheduling.Quartz"> <property name="JobType" value="Munch.Service.ScheduledTasks.CheckMenuIsHealthyJob"/> <property name="JobDataAsMap"> <dictionary> <entry key="HowManyMenuItemsIsOK" value="20" /> </dictionary> </property> </object> A: You can do property/constructor injection into your job by overiding CreateJobInstance of AdaptableJobFactory and register your new JobFactory instead of the default one. The passed in TriggerFiredBundle provides you with enough infos to ask the context for a matching job (based on conventions). bundle.JobDetail.JobType.Name and bundle.JobDetail.JobType fitted my need, so back in 2008 I ended up with sth. like this (the class is derived form AdaptableJobFactory and implements IApplicationContextAware to get the context injected): public class ContextAwareJobFactory : AdaptableJobFactory, IApplicationContextAware { private IApplicationContext m_Context; public IApplicationContext ApplicationContext { set { m_Context = value; } } protected override object CreateJobInstance( TriggerFiredBundle bundle ) { return m_Context.GetObject( bundle.JobDetail.JobType.Name, bundle.JobDetail.JobType ); } } You need to register the ContextAwareJobFactory using the following config: <objects xmlns="http://www.springframework.net"> <!-- Some simple dependency --> <object name="SomeDependency" type="Namespace.SomeDependency, Assembly" /> <!-- The scheduled job, gets the dependency. --> <object name="ExampleJob" type="Namespace.ExampleJob, Assembly" singleton="false"> <constructor-arg name="dependency" ref="SomeDependency"/> </object> <!-- The JobDetail is configured as usual. --> <object name="ExampleJobDetail" type="Spring.Scheduling.Quartz.JobDetailObject, Spring.Scheduling.Quartz"> <property name="JobType" value="Namespace.ExampleJob, Assembly"/> </object> <!-- The new JobFactory. --> <object name="ContextAwareJobFactory" type="Namespace.ContextAwareJobFactory, Assembly" /> <!-- Set the new JobFactory onto the scheduler factory. --> <object id="quartzSchedulerFactory" type="Spring.Scheduling.Quartz.SchedulerFactoryObject, Spring.Scheduling.Quartz"> <property name="JobFactory" ref="ContextAwareJobFactory"/> </object> </objects> I don't know if there is sth. ootb since this was developed in 2008 and I did not followed the integration progress made for quartz.net.
{ "language": "en", "url": "https://stackoverflow.com/questions/7548481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting 404 error page content with Http WebRequest? I use Http WebRequest with Vb.Net to download content. Everything is working fine, but now I have a problem: I want to download this website which is an example for a 404 Error page with content: http://www.boris-koch.de/404seiteyeah But then I get this Error: "Webexception - 404". And I can't read the content of the page because the response is nothing. So do you know a way how to handle it and to get the content of the 404 error page? Thanks a lot. :) A: You can access the WebResponse within the WebException via the Response property. That will have the response data in. For example, in C# (the VB code would be very similar): using System; using System.IO; using System.Net; class Program { static void Main(string[] args) { string url = "http://www.boris-koch.de/404seiteyeah"; WebRequest req = WebRequest.Create(url); try { using (WebResponse response = req.GetResponse()) { Console.WriteLine("Didn't expect to get here!"); } } catch (WebException e) { WebResponse response = e.Response; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string text = reader.ReadToEnd(); Console.WriteLine(text); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7548483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: cyanogenmod lockscreen music controls I am looking for the png's of the music controls that appear on the lockscreen of CyanogenMOD roms, can anybody help me? I was also looking for the source code of those controls, but couldn't find it. Thanks in advance A: All the Cyanogen source code can be found at their github repo. You should be able to find what you're looking for (if I understood your question) at: https://github.com/CyanogenMod/android_packages_apps_Music
{ "language": "en", "url": "https://stackoverflow.com/questions/7548484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modifying httpd.conf to serve over the internet in EasyPHP I'm running EasyPHP on Windows. The default install just opens port 80 on the loopback interface, 127.0.0.1. I want my sites to be accessible over the local network too. There are no simple EasyPHP settings for enabling my other interface, like the one that's connected to the internet (let's say 192.168.1.3). What do I add/modify in Apache httpd.conf? A: Use this code in your httpd.conf ServerName localdomain # env SetEnv TMP "/tmp" ServerAdmin admin@devserver DocumentRoot "/var/www" #NameVirtualHost *:80 #Listen 80 ################################################################## # default <VirtualHost *:80> DocumentRoot "/var/www" ServerName localhost </VirtualHost> <VirtualHost *:80> DocumentRoot "/var/www" ServerName www.localdomain.com </VirtualHost> ** I just realize EasyPHP is for windows. You might use c:/path/to/www instead of /var/www A: I just need to add this line Listen <your machine IP>:<your port> e.g. Listen 192.168.1.3:8080 and restart Apache
{ "language": "en", "url": "https://stackoverflow.com/questions/7548487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }