text
stringlengths
8
267k
meta
dict
Q: How to get progress values from SeekBar created in ListAdapter? I'm curently working on my first Android app, which is my first pice of java code at all, i think I got pretty far already but now I'm stuck on the following topic: I have a ListActivity which shows rowViews from a custom ListAdapter generated from json objects. Generaly there are 3 types of objects: Rooms, which neither have a button nor a slider. Those are handled like this in my ListActivity: @Override protected void onListItemClick (ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Log.d(TAG,"Area" + l.getItemAtPosition(position).toString() + "clicked"); handleControlItemActions((JSONObject)l.getItemAtPosition(position)); } Switchable devices, which have a toggle button to be switched on and off are handled like this (onObjectSwitch is defined in xml as onClick action for the button): public void onObjectSwitch (final View view) { Log.d(TAG,"Object" + view.getId()+ " clicked"); handleControlItemActions((JSONObject)l.getItemAtPosition(position)); } Dimmable devices, which have a SeekBar, and here is my problem: I know the "onSeekBarChangeListener", but I have no clue how I can set it to the SeekBars which are inside the rowViews from my Activity class. The bars are created by the Listadapter like this: case 1: textView.setText((String)controlItem.get("name") + " " +(String)controlItem.getString("actual")+"°C"); slider.setVisibility(View.VISIBLE); slider.setId(position); slider.setProgress(controlItem.getInt("setPoint")); slider.setMax(controlItem.getInt("max")); break; Can anyone tell me how to handle those sliders? Or am I not even on the right track to manage those widgets? Thanks in advance to everyone (and sorry for my spelling ;) )! A: Okay got it: just define the listadapter as a subclass inside of the listactivity, now you're able to reffere to the methods without flagging them "static".
{ "language": "en", "url": "https://stackoverflow.com/questions/7611160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to CameraCaptureTask and PhotoChooserTask on the same screen? In my phone there is an app called PhotoFunia and it has a option to take picture. Whenever I take picture it shows me a page like given in below image: I'm wondering which is this control which is giving Gallery and Camera on the same screen? I have used CameraCaptureTask and PhotoChooserTask separately but the this app is using both control on the same page. So please can anyone tell me whether it is a custom control or default. Is it a hidden application bar and showing when a PhotoChooserTask is launched? I want to implement the similar concept in my application so then whenever a user want to take a picture in application then he can take it from the single screen rather then launching the PhotoChooserTask or CameraCaptureTask separately. A: Is is the PhotoChooserTask with the ShowCamera property set to true, which enables the user to select an existing photo or take a new one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Editing websites locally I think I read somewhere that you can edit the stylesheet of other websites locally on your computer. For example I'd like to edit the stylesheet of Facebook just for my own view. How can I do that? Is there anyway I can edit the original stylesheet CSS and tell my browser to read one locally instead of the original one? A: I use the Stylebot extension for Chrome to apply custom CSS rules to specific websites. It has a great UI you can use to alter bits of the page without actually having to write CSS. You can write raw CSS if you want to though. For example, I use it to hide the <div> containing comments on YouTube, so I never have to see pointless arguments between morons. A: You can use the Firebug plugin for Firefox. That allows you to edit the styles as you see them. Such a valuable development tool, I couldn't recommend it highly enough. I use it every day and no doubt other developers do too. Google Chrome/Safari also has a great web development tool which offers similar features. A: Either you do something browser specific (e.g. for Opera) or you use a proxy server that lets you rewrite requests that match a specific pattern (e.g. Charles). A: Firebug will do that nicely for you. Here is a link for you to download to firefox. http://getfirebug.com/ A: Some browsers allow you to write your own stylesheet but they are browser specific and I don't know if FF is included in them. However I do know that you can setup preferences in firefox. Below is a link on how to use your own stylesheet for Opera and IE http://blackwidows.co.uk/clients/imp-guide/accessify/local-style.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7611163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to catch the exception caused by an absence of an object in Java? I have a very simple method: public int getScore() { return game.gameWindow.userBestScore; } The problem is that it can happens that game object or gameWindow do not exist. I do not want to get the Null Pointer Exception. How can catch it in a correct way? Can I do it in this way: public int getScore() { try{ return game.gameWindow.userBestScore; } catch(NullPointerException e){ return -1; } } A: You can do that. You can also check to see if game and gameWindow are null before trying to access userBestScore. if(game != null && game.gameWindow != null) return game.gameWindow.userBestScore A: Check whether the variables are null as shown below: public int getScore() { if(game == null || game.gameWindow == null){ return -1; } return game.gameWindow.userBestScore; } A: public int getScore() { return ((game == null || game.gameWindow == null) ? -1 : game.gameWindow.userBestScore); } A: Do not catch a NullPointerException. A NullPointerException is a sign that your code is not adhering to some contract. If it is possible that game can be null, then you need to make an explicit test: if(game != null) { ... } else { ... } If game should not be null, then you can ensure the correctness of your code by using assert. assert game != null; ... What is more worrying is that game seems to be a private member of your class. In this case game should probably not be null (although there are cases where this can happen). Are you initializing it properly in your constructor? I'd say that the first thing you should is to make sure that game is being initialized properly. Otherwise your code will end up being littered with un-necessary null-checks. For example, what if gameWindow in the Game class wasn't initialized properly? You would need to have another null-check for that: if(game !== null && game.gameWindow != null) { ... } else { ... } So you should first make sure that your object's private members are being initialized properly. If they are, and it turns out that there is a valid use-case for game being null, then you would need an explicit null-check. It's always better to test for null than catching a NullPointerException. Other than the fact that exceptions should not be used to control the flow of your business logic, what if a valid NullPointerException (due to a programming error) was generated somewhere up the chain? Now your catch will catch it and you won't know about it; this can lead to some really nasty and hard-to-find bugs. A: You can do that. OR you can check for null before you dereference those objects and take appropriate action without throwing an exception. That'll be more efficient. The real question you should be asking is: Why on earth would an object have null references for private data members? You aren't constructing your objects properly. An object should be properly initialized and 100% ready to go after you create it. Otherwise, you end up having to be unnecessarily defensive in your code. A: Avoid exception throwing as much as possible. Handling the known issues is the better way than throwing exceptions. In some where you have to do a null check. Probably before calling the getScore() method, because that doesn't make a sense of calling that method if the game or gameWindow is null. if (game != null && gameWindow != null) { int score = getScore(); } OR public int getScore() { if (game != null && gameWindow != null) { return game.gameWindow.userBestScore; } else { return -1; } } Don't do duplicate null checkings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I determine if a compiler uses early or late binding on a virtual function? I have the following code: class Pet { public: virtual string speak() const { return ""; } }; class Dog : public Pet { public: string speak() const { return "Bark!"; } }; int main() { Dog ralph; Pet* p1 = &ralph; Pet& p2 = ralph; Pet p3; // Late binding for both: cout << "p1->speak() = " << p1->speak() <<endl; cout << "p2.speak() = " << p2.speak() << endl; // Early binding (probably): cout << "p3.speak() = " << p3.speak() << endl; } I have been asked to determine whether the compiler uses early or late binding for the final function call. I have searched online but have found nothing to help me. Can someone tell me how I would carry out this task? A: You can look at the disassembly, to see whether it appears to be redirecting through a vtable. The clue is whether it calls directly to the address of the function (early binding) or calls a computed address (late binding). The other possibility is that the function is inlined, which you can consider to be early binding. Of course the standard doesn't dictate the implementation details, there may be other possibilities, but that covers "normal" implementations. A: You can always use hack :D //... Pet p3; memset(&p3, 0, sizeof(p3)); //... If compiler does use vtbl pointer, guess what will gonna happen :> p3.speak() // here A: Look at the generated code. E.g. in Visual Studio you can set a breakpoint, then right-click and select "Go To Disassembly". A: It uses early binding. You have an object of type P3. While it is a base class with a virtual function definition, the type is concrete and known at compile time, so it doesn't have to consider the virtual function mapping to derived classes. This is much the same as if you called speak() in the Pet constructor - even when making derived objects, when the base class constructor is executing the type of the object is that of the base so the function would not use the v-table, it would call the base type's version. Basically, early binding is compile time binding and late binding is run-time binding. Run time binding is only used in instances where the compiler doesn't have enough type information at compile time to resolve the call. A: In fact the compiler has no obligation to use either one particularly, just to make sure that the right function is called. In this case, your object is of the concrete type Pet, so as long as Pet::speak is called the compiler is "doing the right thing". Now, given that the compiler can statically see the type of the object, I suspect that most compilers will optimize away the virtual call but there is no requirement that they do so. If you want to know what your particular compiler is doing the only way is to consult its documentation, source code, or the generated disassembly. A: I just thought of a way to tell at runtime, without guesswork. You can simply override the vptr of your polymorphic classes with 0 and see if the method is called or if you get a segmentation fault. This is what I get for my example: Concrete: Base Concrete: Derived Pointer: Base Pointer: Derived DELETING VPTR! Concrete: Base Concrete: Derived Segmentation fault Where Concrete: T means that calling the virtual member function of T through a concrete type was successful. Analogously, Pointer: T says that calling the member function of T through a Base pointer was successful. For reference, this is my test program: #include <iostream> #include <string.h> struct Base { unsigned x; Base() : x(0xEFBEADDEu) { } virtual void foo() const { std::cout << "Base" << std::endl; } }; struct Derived : Base { unsigned y; Derived() : Base(), y(0xEFCDAB89u) { } void foo() const { std::cout << "Derived" << std::endl; } }; template <typename T> void dump(T* p) { for (unsigned i = 0; i < sizeof(T); i++) { std::cout << std::hex << (unsigned)(reinterpret_cast<unsigned char*>(p)[i]); } std::cout << std::endl; } void callfoo(Base* b) { b->foo(); } int main() { Base b; Derived d; dump(&b); dump(&d); std::cout << "Concrete: "; b.foo(); std::cout << "Concrete: "; d.foo(); std::cout << "Pointer: "; callfoo(&b); std::cout << "Pointer: "; callfoo(&d); std::cout << "DELETING VPTR!" << std::endl; memset(&b,0,6); memset(&d,0,6); std::cout << "Concrete: "; b.foo(); std::cout << "Concrete: "; d.foo(); std::cout << "Pointer: "; callfoo(&b); std::cout << "Pointer: "; callfoo(&d); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Intelligent point label placement in R * *Is there an R library/function that would implement INTELLIGENT label placement in R plot? I tried some but they are all problematic - many labels are overlapping either each other or other points (or other objects in the plot, but I see that this is much harder to handle). *If not, is there any way how to COMFORTABLY help the algorithm with the label placement for particular problematic points? Most comfortable and efficient solution wanted. You can play and test other possibilities with my reproducible example and see if you are able to achieve better results than I have: # data x = c(0.8846, 1.1554, 0.9317, 0.9703, 0.9053, 0.9454, 1.0146, 0.9012, 0.9055, 1.3307) y = c(0.9828, 1.0329, 0.931, 1.3794, 0.9273, 0.9605, 1.0259, 0.9542, 0.9717, 0.9357) ShortSci = c("MotAlb", "PruMod", "EriRub", "LusMeg", "PhoOch", "PhoPho", "SaxRub", "TurMer", "TurPil", "TurPhi") # basic plot plot(x, y, asp=1) abline(h = 1, col = "green") abline(v = 1, col = "green") For labelling, I then tried these possibilities, no one is really good: * *this one is terrible: text(x, y, labels = ShortSci, cex= 0.7, offset = 10) *this one is good if you don't want to place labels for all points, but just for the outliers, but still, the labels are often placed wrong: identify(x, y, labels = ShortSci, cex = 0.7) *this one looked promissing but there is the problem of labels being too close to the points; I had to pad them with spaces but this doesn't help much: require(maptools) pointLabel(x, y, labels = paste(" ", ShortSci, " ", sep=""), cex=0.7) *require(plotrix) thigmophobe.labels(x, y, labels = ShortSci, cex=0.7, offset=0.5) * require(calibrate) textxy(x, y, labs=ShortSci, cx=0.7) Thank you in advance! EDIT: todo: try labcurve {Hmisc}. A: I found some solution! It's not ultimate and ideal unfortunatelly, but it's the one that works the best for me now. It's half algoritmic, half manual, so it saves time compared to pure manual solution sketched by joran. I overlooked very important part of the ?identify help! The algorithm used for placing labels is the same as used by text if pos is specified there, the difference being that the position of the pointer relative the identified point determines pos in identify. So if you use the identify() solution as I wrote in my question, then you can affect the position of the label by not clicking directly on that point, but by clicking next to that point relatively in the desired direction!!! Works just great! The downside is that there are only 4 positions (top, left, bottom, right), but I'd more appreciate the other 4 (top-left, top-right, bottom-left, bottom-right)... So I use this to labels points where it doesn't bother me and the rest of the points I label directly in my Powerpoint presentation, as joran proposed :-) P.S.: I haven't tried the directlabels lattice/ggplot solution yet, I still prefer to use the basic plot library. A: First, here's the results of my solution to this problem: I did this by hand in Preview (very basic PDF/image viewer on OS X) in just a few minutes. (Edit: The workflow was exactly what you'd expect: I saved the plot as a PDF from R, opened it in Preview and created textboxes with the desired labels (9pt Helvetica) and then just dragged them around with my mouse until they looked good. Then I exported to a PNG for uploading to SO.) Looking for algorithmic solutions is totally fine, and (IMHO) really interesting. But, to me, point labeling situations fall into roughly three categories: * *You have a small number of points, none which are terribly close together. In this case, one of the solutions you listed in the question is likely to work with fairly minimal tweaking. *You have a small number of points, some of which are too closely packed for the typical algorithmic solutions to give good results. In this case, since you only have a small number of points, labeling them by hand (either with an image editor or fine-tuning your call to text) isn't that much effort. *You have a fairly large number of points. In this case, you really shouldn't be labeling them anyway, since it's hard to process large numbers of labels visually. :climbing onto soapbox: Since folks like us love automation, I think we often fall into the trap of thinking that nearly every aspect of producing a good statistical graphic ought to be automated. I respectfully (humbly!) disagree. There is no perfectly general statistical plotting environment that automagically creates the picture you have in your head. Things like R, ggplot2, lattice etc. do most of the work; but that extra little bit of tweaking, adding a line here, adjusting a margin there, is probably better suited to a different tool. :climbing down from soapbox: I would also note that I think we could all come up with scatterplots with <10-15 points that will be nearly impossible to cleanly label, even by hand, and these will likely break any automatic solution someone comes up with. Finally, I want to reiterate that I know this isn't the answer you're looking for. And I'm not saying that algorithmic attempts are useless or dumb. The reason I posted this answer is that I think this question ought to be the canonical "point labeling in R" question for future duplicates, and I think solutions involving hand-labeling deserve a seat at the table, that's all. A: ggrepel looks promising when applied to ggplot2 scatterplots. # data x = c(0.8846, 1.1554, 0.9317, 0.9703, 0.9053, 0.9454, 1.0146, 0.9012, 0.9055, 1.3307) y = c(0.9828, 1.0329, 0.931, 1.3794, 0.9273, 0.9605, 1.0259, 0.9542, 0.9717, 0.9357) ShortSci = c("MotAlb", "PruMod", "EriRub", "LusMeg", "PhoOch", "PhoPho", "SaxRub", "TurMer", "TurPil", "TurPhi") df <- data.frame(x = x, y = y, z = ShortSci) library(ggplot2) library(ggrepel) ggplot(data = df, aes(x = x, y = y)) + theme_bw() + geom_text_repel(aes(label = z), box.padding = unit(0.45, "lines")) + geom_point(colour = "green", size = 3) A: I'd suggest you take a look at the wordcloud package. I know this package focuses not exactly on the points but on the labels themselves, and also the style seems to be rather fixed. But still, the results I got from using it were pretty stunning. Also note that the package version in question was released about the time you asked the question, so it's still very new. http://blog.fellstat.com/?cat=11 A: I've written an R function called addTextLabels() within a package basicPlotteR. The package can be directly installed into your R library using the following code: install.packages("devtools") library("devtools") install_github("JosephCrispell/basicPlotteR") For the example provided, I used the following code to generate the example figure linked below. # Load the basicPlotteR library library(basicPlotteR) # Create vectors storing the X and Y coordinates x = c(0.8846, 1.1554, 0.9317, 0.9703, 0.9053, 0.9454, 1.0146, 0.9012, 0.9055, 1.3307) y = c(0.9828, 1.0329, 0.931, 1.3794, 0.9273, 0.9605, 1.0259, 0.9542, 0.9717, 0.9357) # Store the labels to be plotted in a vector ShortSci = c("MotAlb", "PruMod", "EriRub", "LusMeg", "PhoOch", "PhoPho", "SaxRub", "TurMer", "TurPil", "TurPhi") # Plot the X and Y coordinates without labels plot(x, y, asp=1) abline(h = 1, col = "green") abline(v = 1, col = "green") # Add non-overlapping text labels addTextLabels(x, y, ShortSci, cex=0.9, col.background=rgb(0,0,0, 0.75), col.label="white") It works by automatically selecting an alternative location from a fine grid of points. The closest points on the grid are visited first and selected if they don't overlap with any plotted points or labels. Take a look at the source code, if you're interested. A: Not an answer, but too long for a comment. A very simple approach that can work on simple cases, somewhere between joran's post-processing and the more sophisticated algorithms that have been presented is to make in-place simple transformations to the dataframe. I illustrate this with ggplot2 because I'm more familiar with that syntax than base R plots. df <- data.frame(x = x, y = y, z = ShortSci) library("ggplot2") ggplot(data = df, aes(x = x, y = y, label = z)) + theme_bw() + geom_point(shape = 1, colour = "green", size = 5) + geom_text(data = within(df, c(y <- y+.01, x <- x-.01)), hjust = 0, vjust = 0) As you can see, in this instance the result is not ideal, but it may be good enough for some purposes. And it is quite effortless, typically something like this is enough within(df, y <- y+.01) A: Have you tried the directlabels package? And, BTW, the pos and offset arguments can take vectors to allow you to get them in the right positions when there are a reasonable number of points in just a few runs of plot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "103" }
Q: Is there a way to convert word colors ("red", "blue", "green") into #123456 values? I've been stuck on this for a while. I keep trying to compare colors for elements but even if the colors are the same, the values representing them are not. One is #000 and the other is "black". How do I take "black" and turn it into #000. With that said, how do I take any word color and turn it into a number? A: I've seen this question asked in the past and i think you can find a good script here. The script is from a great programmer in javasscript and, well, actually he does a word look up, there is no other way to do it i think. A: If you set a CSS color property to your color string and then get the property back, most (at least some) modern browsers will give you a "normalized" color string. Firefox seems to like the "rgb(n, n, n)" notation. edit — @Andy E notes that this doesn't work in too many browsers. A: Since you are using javascript you can use a "javaScript associative array" and have the assosiation "colorName <-> colorCode" you need. You can find all the official color names here: http://www.w3schools.com/cssref/css_colornames.asp here is some code: var colors= new Array(); colors["black"] = "#000"; colors["AliceBlue"] = "#F0F8FF"; colors["AntiqueWhite"] = "#FAEBD7"; var mycolor = 'black' alert('the code of '+mycolor +' is:'+colors[mycolor]); A: I'm not sure it is possible x-browser without a predefined list of colours. It's simple enough in browsers supporting window.getComputedStyle(): function getColorFromName(name) { var rgb, tmp = document.body.appendChild(document.createElement("div")); tmp.style.backgroundColor = name; rgb = window.getComputedStyle(div, null); //-> returns format "rgb(r, g, b)", which can be parsed and converted to hex } For browsers not supporting this, the only option you have is to use an object map and define the values yourself: var colours = { aliceblue: "#F0F8FF", antiquewhite: "#FAEBD7", aqua: "#00FFFF" //...etc } // and lookup alert(colours[document.getElementById("div").style.backgroundColor.toLowerCase()]); A full list of colours supported in CSS3 is available from http://www.w3.org/TR/css3-color/#svg-color. Of course, the downside to the list method is that lists need to be maintained if the specification changes, so you might want to incorporate both methods - ie if getComputedStyle() is available, use it else fall back to the list. This ensures compatibility for both older browsers and newer browsers without ever needing to update the list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PIL - are there a any PIL solutions that will allow you to take a screenshot of a specified web page? Is there a way to take a screenshot using PIL of an specified HTML/Javascript page that resides on my server? I want to write a script that will change some parameters on that HTML page and then have PIL take screenshots of it. Any ideas? Examples would be truly appreciated. A: Do you absolutely have to use PIL? If not you might be able to get what you want using PyQT which has a built-in Webkit control. See http://notes.alexdong.com/xhtml-to-pdf-using-pyqt4-webkit-and-headless for an example which converts html+css into a PDF without using a separate browser. The code is pretty short so I've copied it below. import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * app = QApplication(sys.argv) web = QWebView() web.load(QUrl("http://www.google.com")) #web.show() printer = QPrinter() printer.setPageSize(QPrinter.A4) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName("file.pdf") def convertIt(): web.print_(printer) print "Pdf generated" QApplication.exit() QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt) sys.exit(app.exec_())
{ "language": "en", "url": "https://stackoverflow.com/questions/7611179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I run multiple commands in SSH through Java? How do I run multiple commands in SSH using Java runtime? the command: ssh [email protected] 'export MYVAR=this/dir/is/cool; /run/my/script /myscript; echo $MYVAR' @Test public void testSSHcmd() throws Exception { StringBuilder cmd = new StringBuilder(); cmd.append("ssh "); cmd.append("[email protected] "); cmd.append("'export "); cmd.append("MYVAR=this/dir/is/cool; "); cmd.append("/run/my/script/myScript; "); cmd.append("echo $MYVAR'"); Process p = Runtime.getRuntime().exec(cmd.toString()); } The command by its self will work but when trying to execute from java run-time it does not. Any suggestions or advice? A: Use the newer ProcessBuilder class instead of Runtime.exec. You can construct one by specifying the program and its list of arguments as shown in my code below. You don't need to use single-quotes around the command. You should also read the stdout and stderr streams and waitFor for the process to finish. ProcessBuilder pb = new ProcessBuilder("ssh", "[email protected]", "export MYVAR=this/dir/is/cool; /run/my/script/myScript; echo $MYVAR"); pb.redirectErrorStream(); //redirect stderr to stdout Process process = pb.start(); InputStream inputStream = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while((line = reader.readLine())!= null) { System.out.println(line); } process.waitFor(); A: The veriant of Runtime.exec you are calling splits the command string into several tokens which are then passed to ssh. What you need is one of the variants where you can provide a string array. Put the complete remote part into one argument while stripping the outer quotes. Example Runtime.exec(new String[]{ "ssh", "[email protected]", "export MYVAR=this/dir/is/cool; /run/my/script/myScript; echo $MYVAR" }); That's it. A: If the Process just hangs I suspect that /run/my/script/myScript outputs something to stderr. You need to handle that output aswell as stdout: public static void main(String[] args) throws Exception { String[] cmd = {"ssh", "root@localhost", "'ls asd; ls'" }; final Process p = Runtime.getRuntime().exec(cmd); // ignore all errors (print to std err) new Thread() { @Override public void run() { try { BufferedReader err = new BufferedReader( new InputStreamReader(p.getErrorStream())); String in; while((in = err.readLine()) != null) System.err.println(in); err.close(); } catch (IOException e) {} } }.start(); // handle std out InputStreamReader isr = new InputStreamReader(p.getInputStream()); BufferedReader reader = new BufferedReader(isr); StringBuilder ret = new StringBuilder(); char[] data = new char[1024]; int read; while ((read = reader.read(data)) != -1) ret.append(data, 0, read); reader.close(); // wait for the exit code int exitCode = p.waitFor(); } A: You might want to take a look at the JSch library. It allows you to do all sorts of SSH things with remote hosts including executing commands and scripts. They have examples listed here: http://www.jcraft.com/jsch/examples/ A: Here is the right way to do it: Runtime rt=Runtime.getRuntime(); rt.exec("cmd.exe /c start <full path>"); For example: Runtime rt=Runtime.getRuntime(); rt.exec("cmd.exe /c start C:/aa.txt"); A: If you are using SSHJ from https://github.com/shikhar/sshj/ public static void main(String[] args) throws IOException { final SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); ssh.connect("10.x.x.x"); try { //ssh.authPublickey(System.getProperty("root")); ssh.authPassword("user", "xxxx"); final Session session = ssh.startSession(); try { final Command cmd = session.exec("cd /backup; ls; ./backup.sh"); System.out.println(IOUtils.readFully(cmd.getInputStream()).toString()); cmd.join(5, TimeUnit.SECONDS); System.out.println("\n** exit status: " + cmd.getExitStatus()); } finally { session.close(); } } finally { ssh.disconnect(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Machine config instead of app.config files for console apps Is it possible to use connection strings in a Console app's app.config file in a single machine config file instead? So all console apps on the server can use the same file? A: You could, but that would mean that any .NET application could gain access to your database. I would advise against it, for several reaons: * *A possible security hole. *Most developers would look for this information in app.config not machine.config. *You may end up sharing connection strings that only one or two applications need with all applications. *You can't limit what applications will be able to use the connection strings. *You will not be able to simply move the application to another machine, with the app.config file and have everything just work (you will also need to import the connection string information to the new machine.config). You really should keep the configuration with the application that uses it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding .lib files in Microsoft Visual Studio 2010 I just downloaded Visual Studio 2010, and they changed a lot since Visual Studio 2008. These options were changed: the header includes, the lib directory to add, and all changed. I followed a series of tutorials to do that, but in the other version I just had to add the mylib.lib string in the textfield, but now I look over and over, and I can't find a place to paste that mylib.lib to link with my project. Where can I find it? A: If you're looking for how to get a lib file imported in to your project, you can do this either by editing the project settings, under Linker>Input: ...or you can use a #pragma... #pragma comment( lib, "MyLib.lib" ) I typically add this right in to the header file for the library I want to import. Alternatively, you can add it to any header or CPP file in your project. A: I personally prefer to do it this way, right in code: #pragma comment(lib, "mylib.lib") This way you don't need to look for the field you need under project settings. See also: What does "#pragma comment" mean?
{ "language": "en", "url": "https://stackoverflow.com/questions/7611198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Recurring payments IPN Working on implementation of paypal's recurring payments, I've got encountered some problems. I have followed paypal's documentation from here: PayPal Express Checkout: Recurring Payments Process Flow It seems that everything works properly and I get ProfileID at the end (from result of CreateRecurringPaymentsProfile() query). Recurring profile is also being created. The problem is there's no IPN confirmation after running CreateRecurringPaymentsProfile() , but according to: PayPal Express Checkout: PayPal Notifications - it should be. A: From my experience this happens only when IPN (Instant Payment Notifications) are not enabled in your merchant account. You can enable IPN in Profile > Instant Payment Notification Preferences.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook - Is it possible to get hidden posts and comments in grey via Graph API or FQL? I have some comments in grey in my Facebook pages's wall and some comments in "Hidden posts" Page tab, not in the wall. I know that Facebook anti-spam filter has put theses comments but i want to know if it's possible to get them via Graph API or FQL? Thanks !
{ "language": "en", "url": "https://stackoverflow.com/questions/7611215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does OpenFire or XMPP Protocol support Message Notification (Pending, Delivered, Read) like BBM (Blackberry Messenger) I am a beginner and need help. I am currently involved in a project, where required to build a chat application (server side and client side). After further explore, eventually I was interested in XMPP. For XMPP Server, I have been interested in the Openfire, which support XMPP Protocol. The question that remains unanswered is whether Openfire can be extended to the needs of Message Notification, which is a feature of the Blackberry Messenger which can determine whether a message is PENDING, DELIVERED, or has been READ by the client (user). Can anyone help me? A: As the (almost!) duplicate thread mentions, this question seems to be about XEP-0184. See also: XEP-0079: Advanced Message Processing http://xmpp.org/extensions/xep-0079.html Discussion thread: XEP-0184 Message Receipts http://community.igniterealtime.org/thread/35128 Add support for XEP-0184: Message Delivery Receipts [Status: Open] http://issues.igniterealtime.org/browse/OF-434
{ "language": "en", "url": "https://stackoverflow.com/questions/7611217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Schedule .bat isn't executing VBScript properly So I've got 2 things going on: a program that checks the status of some folders, then a VBScript that runs afterwards to email recipients of any errors going on in said folders. Even if there is none, it's supposed to send a "No Errors" email. Both of them work perfectly fine individually. The checker .exe program runs with no issues, and when I run the VBScript by itself, it sends all the emails it's supposed to. However, I put the following into a .bat file to run nightly at 11pm: "C:\batch\night_monitor\checker.exe" "C:\batch\night_monitor\emailer.vbs" For some reason, when the batch file is run, only 1 out of 5 emails go out. By default, all the flags are set to true, and when I look in the log file, I see that the emailer.vbs is only checking 2 error logs instead of 5. Like I said though, the emailer works perfectly fine if I just run it by itself. Is there something major that I'm missing here? A: Try this.. @ECHO OFF START "Checker" /WAIT "C:\batch\night_monitor\checker.exe" START "Emailer" /WAIT "C:\batch\night_monitor\emailer.vbs" Run START /? from a command line to see all the options. A: It seems your checker.exe isn't finished when emailer.vbs is started. Try running your programms in sequence: "C:\batch\night_monitor\checker.exe" & "C:\batch\night_monitor\emailer.vbs" ... or execute emailer.vbs only if checker.exe executed successfuly: "C:\batch\night_monitor\checker.exe" && "C:\batch\night_monitor\emailer.vbs" Another alternative would be to call checker.exe from inside emailer.vbs to make sure it has finished before you access the error logs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Supress console output from chrome extensions When troubleshooting my own javascript, I see console messages from my installed chrome extensions. Is there any way to supress these messages? I'd prefer to not see them as they clutter up the console output. A: Temporarily disabling the other extensions is a quick and easy way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How can I have ColdFusion tags in a variable and have them evaluated? I've get a variable that can contain a CF custom tag. E.g. <cfset a = '<model:sparkline id="1"/>'/> And I'd like that to be evaluated into HTML and outputted. Not sure how/if I can do this. A: Can you modify the custom tag? If so you can use the caller scope to set a variable in the calling page. So inside the custom tag you could do <cfset caller.a = "whatever" /> and that will set the value in the calling page's variables scope. If you don't want to modify the custom tag, then you can use <cfsavecontent> to save the output to a variable. Example: <cfsavecontent variable="a"> <model:sparkline id="1" /> </cfsavecontent> A: Sean Coyne's answer is the correct one, provided the import is included within the same context as the cfsavecontent tag: <cfimport taglib="./tags" prefix="model"> <cfsavecontent variable="a"> <model:sparkline id="1" /> </cfsavecontent> <cfoutput>#a#</cfoutput> Will result in the dynamically evaluated output of the sparkline customtag. A: It's impossible to OUTPUT the code and have it execute. OUTPUT just means output. It doesn't mean "run". The only way to get CF code to be executed by CF is to follow normal channels: * request a template; * include a template; * call a template as a custom tag or CFMODULE; * call a method in a CFC; * any others? ANyway, you get the point. So if you have code that you create dynamically and want to execute... you need to write it to a file and then call it via the most appropriate of those mechanisms. Be warned though: running dynamic code like this has a fair overhead, as the code needs to be compiled before it's run, and compilation is not the fastest process in the scheme of things. The "best" thing to do here is to try to write and compile the file before it's needed, and only re-write the file it it needs updatng. Don't re-do it every request. But, ideally, don't do this sort of thing at all. One can usually approach things a different way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Combine syntax highlighting of different Eclipse editors I use Eclipse, StatET and the Sweave plugin to write my R and Latex code. The cool thing is that R and Latex code can be put together into one file, however you end up with a syntax highlighting problem. I have loads of R code and I very much like the Eclipse R syntax highlighting. But now combining R and Latex means that I have to work with .Rnw files where there is no particular syntax highlighting for R. When I go to Eclipse -> Preferences -> Content Types I can add *.Rnw to "R script file" which makes Eclipse to open the .Rnw files with the standard R Editor. However, this means that I do not have syntax highlighting for Sweave any longer. In addition, the Sweave code is shown as an error in the R editor. My question is whether it is possible to combine different syntax highlighting styles in an easy way? A: I don't think any Eclipse plugins/editors really support mixing up several syntaxes inside one editor. At any rate it is not currently supported in Eclipse Platform. However you can try Eclipse Colorer plugin. It allows to switch coloring style for the current editor. It may mot support both R and Latex syntax, but you can create your own highlighting by adding your own HRC file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Segmentation fault when initialization array I have a structure called string typedef struct { char *s; int len; } string_t; typedef struct { uint32_t numb; } msg_t; where in the function void myfunct() { msg_t msg; memset(&msg, 0, sizeof(msg)); msg.numb = 1; char *ClientSendBuf[sizeof(msg)]; string_t buffer = {ClientSendBuf[sizeof(msg)],strlen(ClientSendBuf[sizeof(msg)])}; } Tried to initialize an array (basically a buffer that I need to send later on) using UDP, but it gives me an error of segmentation fault (on the third line in void myfunct. So the thing with buffer is that it should be a type of string_t, how can I fix this segmentation fault? P.S. I forgot to mention, I want to copy the whole structure to the buffer variable (that should be type string_t) using memcopy. So am I doing the wrong thing above? How can I do this? A: There are a few things you have to consider in initializing your structure, as it has a pointer member char *s simple assignment will not work. Simple assignment will just copy the pointer address and not the content it is pointing to. There are a few problems in your assignment code: 1. You declared an array of char * with sizeof(msg) elements, none of which are allocated memory; but your structure need char * and not char *[] 2. You are accessing an array element which is out of bounds (ClientSendBuf[sizeof(msg)]) and also not pointing to any valid address. You can create a simple char array & copy it to the structure. As you are using a pointer member it is your responsibility to allocate memory and free memory. Hope the code below can provide you with some references: void myfunct() { msg_t msg; memset(&msg, 0, sizeof(msg)); msg.numb = 1; char ClientSendBuf[] = "This is my message"; string_t buffer = { strdup(ClientSendBuf), /*Can return NULL so add error check*/ strlen(ClientSendBuf) }; /** Or **/ string_t buffer; buffer.s = malloc(strlen(ClientSendBuf)+1); if(NULL == buffer.s) { /* Memory allocation failed. Handle error.*/ } /* Zero fill */ memset(buffer.s, 0, strlen(ClientSendBuf)+1); strcpy(buffer.s, ClientSendBuf); buffer.len = strlen(ClientSendBuf); /*Opeartions with buffer*/ /*Call free in both cases !*/ free(buffer.s); } Hope this help! A: ClientSendBuf - put some thing in it and also put it on the heap. A: I see two things that are wrong. First, accessing ClientSendBuf[sizeof(msg)] is undefined behavior, because that character is after the end of CliendSendBuf. Then you're assigning a char (namely ClientSendBuf[sizeof(msg)]) when a char * is expected. And if you want to use buffer outside that function you have to put ClientSendBuf on the heap, because it will be overwritten by other stack frames after you exit (i.e. sort of deleted), so the pointed data will be throwed off. Now, since you want a copy of the whole ClientSendBuff, you need an array of string_t. Then, you assign every pointer in ClienSendBuff to buffer: char *ClientSendBuff[sizeof(msg)]; string_t buffer[sizeof(msg)]; int i; for(i = 0; i < sizeof(msg); i++) { ClientSendBuff[i] = malloc(100); // you have to initialize (and free when buffer[i].s = ClientSendBuff[i]; // you don't need them anymore) every pointer buffer[i].len = 100; } But I'm not sure if I got your point. How can a char * [] fit in a char*? A: The problem is that you don't allocate memory to any element of ClientSendBuf. You should use malloc here to first allocate the memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Starting multiple instances of the same Activity from Service I want to start multiple instance of the same Activity class from a Service. The reason I'm doing this, is because I have a Service that runs a "scan" daily, and if it finds any malfunctions it should display a popup for each malfunction. The Activity that I'm starting is more like a Dialog, has a Dialog theme to display info about the malfunction. Manfiest: <activity android:name=".ui.dialogs.MalfunctionActivity" android:theme="@style/MyDialog" android:launchMode="standard"> Intent to start the activity from Service: Intent displayMalf=new Intent(this, MalfunctionActivity.class); displayMalf.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(displayMalf); PROBLEM: to start the Activity from a Service I need the FLAG_ACTIVITY_NEW_TASK which somehow cancels the launchMode="standard" from the manifest, and gives me just one Activity even if I try to start multiple diffrent instances. Is there anyway in which I can achieve this? A: It was so simple. There is the flag FLAG_ACTIVITY_MULTIPLE_TASK which according to the documentation : Used in conjunction with FLAG_ACTIVITY_NEW_TASK to disable the behavior of bringing an existing task to the foreground. When set, a new task is always started to host the Activity for the Intent, regardless of whether there is already an existing task running the same thing. Was exactly what I need. Thanks and sorry for answering on my question. It is not a habit. :) A: Service will take the flag FLAG_ACTIVITY_NEW_TASK to start the activity but here you can try like this: * *Set the instance of the handler of the activity of which you want multiple instances, in the service. *When you want the new instance of the activity use handler.sendMessage(msg) and on receiving this msg in your activity, start this activity again. A: I guess your app works in the background and will display the popups even if the app is not in the foreground at the moment, right? Otherwise I would use normal popup's (AlertViews) instead of starting new activities all the time. If the app works in the background, you could tell the user with the first popup that your app has found one or more malfunctions and that he should activate the app for more details
{ "language": "en", "url": "https://stackoverflow.com/questions/7611249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Visual Studio 2010 - Warnings only shown for active file i hope you can help me with my problem in Visual Studio 2010. Normally in Visual Studio 2008, when i compile a project warnings for all files are shown. But not so in Visual Studio 2010. When i compile a project warnings are shown not until a file is active and then only warnings for the active file are shown in error list. And I have recently found out something new: the problem only seems to be in ASP.NET Pages (.master, .aspx), but not in Behind-Code-Files (.master.cs, .aspx.cs). Is there a problem with warnings in relation with ASP.NET Pages (except the behind-code-files)? Thanks in advance. Best Regards, HeManNew A: Visual Studio 2008 and 2010 actually behave the same when listing errors and warnings for pages. A page's errors and warnings appear in the Error List when its editor is open (regardless of whether it's the active window) or when the errors (not warnings or messages) prevent the application from compiling. But because markup pages are not compiled, only server-side errors prevent the application from compiling. So, in sum, Visual Studio is behaving correctly. To see the errors and warnings particular to a markup page, you need to open it first. Compiling has nothing to do with markup errors. A: I know described behavior since VS2005 (I have no experience with earlier versions). The .aspx is compiled at runtime (or when it is opened in VS 2010). So errors (and warnings) are found when page is run. You can even edit .aspx and new version is used when page is reloaded (the load time is considerably longer). I don't know any way to say to iis to compile all aspx. But maybe we experience a different behavior because I see warnings for all opened .aspx files, not only for the active one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Changing font size with jquery I'm trying to change the font-size of the text in a textarea by using the .css attr but its not working, do you guys have any ideas? <html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> function crap () { var text_input = $('#textarea').val(); text_input.css("font-size", "14px"); } </script> </head> <body> <textarea id="textarea" rows="30" cols="70"> </textarea><br/><br/> Font size:<input type="text" id="font_size"/> <input type="button" id="px" value="14px" onClick="crap()"/> </body> </html> A: $(document).ready(function() { $('#incfont').click(function(){ curSize= parseInt($('#content').css('font-size')) + 2; if(curSize<=200) $('#content').css('font-size', curSize); }); $('#decfont').click(function(){ curSize= parseInt($('#content').css('font-size')) - 2; if(curSize>=12) $('#content').css('font-size', curSize); }); $('#minheight').click(function(){ curSize= 16; $('#content').css('font-size', curSize); }); }); A: function crap () { var text_input = $('#textarea'); text_input.css("font-size", "14px"); } Remove .val. That will get the value within the textarea, you want to affect the textarea itself. A: Alternative: <style type="text/css"> #textarea { font-size:14px; } </style>
{ "language": "en", "url": "https://stackoverflow.com/questions/7611265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MySQL backslash apostrophe I'm having a MySQL issue. I'm trying to select all rows in a table that start with a backslash and an apostrophe: SELECT * FROM table WHERE name like '\\\'%' But this is not working. An example of what I'm trying to select: \'S-GRAVENDEEL How do I do this? Thanks p.s. Yes, this was the result of a faulty import, I know, but now I need to fix it :-) A: You need more backslashes: select * from table where name like '\\\\\'%' You need one of them to get a single quote into the pattern. Then you need four more to get a single literal backslash down to the like. Or you could escape the single quote by doubling it: select * from table where name like '\\\\''%' A: So I've got a solution. Basically what I want to do is fix the entries, so I'll show you what the replace looks like: SELECT *, REPLACE(naam, '\\''', '''') naamnew FROM school_plaats WHERE naam like '%\\''%' Apparently, I need to escape the apostrophe with an apostrophe and the backslash with a backslash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google App Engine: how to speed up database query on a short-string property? I have a quite simple database query: Query q = new Query("person"); q.addFilter("name", Query.FilterOperator.EQUAL, req.getParameter("n")); PreparedQuery pq = datastore.prepare(q); for (Entity result : pq.asList(FetchOptions.Builder.withDefaults())) { // ... } So it's simple search all entries for the given name. The name isn't unique and contains maximal 16 characters. As far as I know the index for the short strings (<500 characters) is generated automatically. In the table are about 100000 entries. The database request needs more than 8 seconds to fetch all (about 10) entities. The question is now how to speed it up? A: The dev appserver's performance is not indicative of production performance. In particular, the dev appserver does not use indexes. At all. Every query just scans every entity of that type. So don't insert that much data into the dev appserver. Use it to test basic functionality, then deploy, and insert your 1000000 entities into the production app engine appserver instead, where indexes actually get generated and used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: is it ok to use StructureMap like this? asp.net MVC 3 i have a doubt that i am not using the best practice for using Structure-Map. all working fine but just a confusion in mind. my code look like this. global.asax IContainer container = new Container( x => { x.For<IUserRepo>().Use<UserRepo>(); x.For<IPostRepo>().Use<PostRepo>(); // this is the soultion for the error }); DependencyResolver.SetResolver(new StructureMapDependencyResolver(container)); PostController private readonly IPostRepo _postRepo; public PostController(IPostRepo postRepo) { this._postRepo = postRepo; } StructureMapDependencyResolver public class StructureMapDependencyResolver : IDependencyResolver { private readonly IContainer _container; public StructureMapDependencyResolver(IContainer container ) { this._container = container; } public object GetService(Type serviceType) { object instance = _container.TryGetInstance(serviceType); if(instance == null && !serviceType.IsAbstract) { _container.Configure(c => c.AddType(serviceType,serviceType)); instance = _container.TryGetInstance(serviceType); } return instance; } public IEnumerable<object> GetServices(Type serviceType) { return _container.GetAllInstances(serviceType).Cast<object>(); } } here is the IPostRepo looks like public interface IPostRepo { bool CreatePost(Post newPost); List<Post> ShowAllPosts(); Post FindPostById(int postId); Post EditPost(Post editPost); UserPostCommentViewModel FindAllPostComments(int postId); int? AddPlusOneToNumberOfViews(int postId); } thx martin for your help A: No. Like I said in your other question, take out the Controller Activator ... unless you are using it for a purpose (which it doesn't seem like you are). Also, this line is plain WRONG: x.ForRequestedType<AccountController>().TheDefault.Is. ConstructedBy(() => new AccountController(new UserRepo())); You should not be using new for your UserRepo ... that is what the line above is taking care of: x.For<IUserRepo>().Use<UserRepo>(); If you take out the ControllerActivator, you should have a nice start to an MVC app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP/CHMOD Questions I am working on a PHP based website. In the admin there is a section that checks a form field and based on the field looks for a folder on the server. This folder will be in a sub-directory. If it does not exist it needs to be created. After that, previously existing or not, PHP will write file to the folder. These folders will hold images and PDF files that will be viewed and/or downloaded on the main site. Here is an example directory structure: merchants/east/user123 In the above merchants and east would definitely exist and user123 may exist or otherwise be created. Given that info my questions are about folder permissions. * *What should folders be set to for the best security. *Should I open them up wider during operations then chmod them (in PHP) after I'm done to something more secure? *What should upper level folders be set to? A: 770 would be a safe bet for the files. Setting it to that would disallow any public access. I would implement some sort of document delivery system in PHP. PHP will be able to access the non-public files and then send them to the user. The upper level folders could be set to the same. Update As others have said, you can easily chmod them to 600 without any issues. That's the more secure way of handling it (prevents other users on the system from accessing the files). It also omits "execute", which isn't needed for file reading anyway. It's my personal practice to leave the extras in unless there's a defined reason not to. A: The upper level folder would need to have read, write and execute permissions for the apache user., the top level folder could be owned by apache, and have permissions like 755 to allow the the webserver to read, write and list files. You might think about permissions 750 or 700 if you are particularly concerned about other local users or services on the web server from seeing the files in this directory. For file permissions: 644 or 600 as conventionally they do not need execute permission. A nice compromise might be to use 750 for directories and 640 for files with owner set to apache, and change the group (chgrp) so that the group for the file allows access to the user that you normally edit the website files with. I can't think of any significant advantage of the php script increasing and then reducing the permissions. I think you should consider @chunk's comment about keeping the uploaded files own of the public html directory completely, and serving them back via an file delivery script. Otherwise you would need some careful validation of the content of the files and to tightening up the apache configuration for that particular directory - perhaps using some mimetype checking to make sure that the files really are docs and pdfs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Memory warnings in IPAD app with UITabbar of 8viewControllers My application which is a UITabbar app has eight tabs. one tab for playing Audio, one for Playing Videos, one for Books(Leavesview is used for opening jpg image pages),one for Gallery.....so on. So, Once I open all tabs the app throws memory warnings and crashes. Then I did this: In each tabs viewController, I have allocated everything(views, imageViews.....) in ViewDidAppear method then I did removeFromSuperView and release in ViewDidDisappear method.Even then the problem persists. Using Activity Monitor I observed that the app crashes when it exceeds 128 MB of Memory. Each tab's ViewController is Occupying around 40MB memory. Even though I release everything in the ViewDidDisapper of the tab the memory is not freed but kept on increasing. Is there anything regarding memory I have missed. Please Help me resolve this , Thank You. A: I have noticed that when instantiating a UITabBarController it loads all it's dependencies and is really stubborn when trying to release an entire UIViewController. I've done a few things to combat this when I've had high memory UIViewControllers attached to a UITabBarController. What I suggest is only releasing the memory hog controls associated with each UIViewController on the ViewWillDisappear and re-Instantiating them on the ViewWillAppear rather than trying to release the entire UIViewController. Typically this is bad practice because you want to recycle as many of the controls as possible but if you have to stick with the UITabBarController this is the only way I've been successful. If I misread your post and you aren't trying to release the UIViewController the I would need to see some code to figure out why things aren' releasing on ViewWillDisappear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SIGINT signal()/sigaction in C++ So here is my code: void sigHandle(int sig) { signal(SIGINT, sigHandle); //Is this line necessairy? cout<<"Signal: "<<sig<<endl; } int main(){ signal(SIGINT, sigHandle); while(true){ //Supposed to loop until user exits. //rest of my code } } Now it is my understanding of signal() that when the SIGINT command (Ctrl+C right?) is received my function sigHandle should be called with an integer value of 2 (the SIGINT number), the method should run and the program should NOT exit. All I would like to do is just print the signal number and move on, however after printing out "Signal: 2" it exits. (Eventually I'm supposed to handle the first 32 interrupts but I figured Ctrl+C would be the most difficult so I'm starting here.) In main if I do signal(SIGINT, SIG_IGN); it ignores the signal correctly and doesn't exit but I now have no way of knowing if I recieved the SIGINT interrupt. Earlier I was playing around with the sigaction struct but I could not find any real comprehensive documentation on it so I decided to go with just "raw" signal handling. This was my sigaction code (same problem as above): struct sigaction action; action.sa_handler = sigHandle; sigemptyset(&action.sa_mask); action.sa_flags = 0; sigaction(SIGINT, &action, 0); Thanks for your help! EDIT OK SO After many many many hours of scowering through man pages and the internet I have happened across a (very) ghetto solution involving saving the stack pre-infinite loop then when the interrupt comes, doing what I need to do, then re-setting the stack back to where it was and calling the sigrelse() command to re-set any states that might have been changed and not re-loaded. I understand that this is not the most elegant/efficient/or even socially acceptable solution to this problem but it works and as far as I can tell I am not leaking any memory anywhere so it's all good... I am still looking for a solution to this problem and I view my stack re-setting shenanigins as only a temporary fix... Thanks! A: It is not. You just replacing SIGINT's handles with same function. How does you program perform wait? If you have something like: int main { // ... int r = read(fd, &buff, read_size); // your program hangs here, waiting for the data. // but if signal occurred during this period of time // read will return immediately, and r may != read_size return 0; // then it will go straight to return. } A: Also note you should not call stdio (or other non-reentrant functions) in signal handlers. (your signal handler might be invoked in the middle of a malloc or it's C++ equivalent)
{ "language": "en", "url": "https://stackoverflow.com/questions/7611281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Plus button fails to load. Uncaught gapi.load Everytime I launch my page containing a google plus icon I see the following error: Uncaught gapi.load: Pending callback https://ssl.gstatic.com/webclient/js/gc/23980661-3686120e/googleapis.client__plusone.js plusone.js:16 Any idea where this is coming from? This is the dating site I see the error on. A: Did you duplicate the Javascript code part every time you have a +1 button (it's very likely that you have more than 1 +1 buttons on a single webpage)? <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> I had the same problem as yours, I removed the above Javascript where it is duplicated and only included it once with the <head> tag of my webpage. The error stopped showing up after that :) I checked out your dating site a few minutes ago, still saw the error so hope this helps :) A: This goes where you want the button to appear: <g:plusone size='small' count='false' href='http://www.zxclasses.com'></g:plusone> This goes just before your tag: <script type='text/javascript'> window.___gcfg = {lang: 'en-GB'}; (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> Google says the script should appear after the final button, but some browsers error with something like NO_MODIFICATION_ALLOWED, if the code appears anywhere else than directly above for IE7, i dont think so its working ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7611292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows Remote Desktop logging I have a Windows 7 machine that several folks Remote Desktop into. I'm looking for a way to log who (IP address) has logged in locally (on the machine that has been logged into) and/or if there is a snazzy way to email myself a notification whenever someone logs in that would be even better. Is this just a matter of port listening? Can Windows do this on it's on without third party tools? A: I don't think this is the end solution but in the interim you could create a shell or batch script that executes at log in and sends an email. The other option is tapping into the EventLogs. Perhaps you can email something form the event log. http://technet.microsoft.com/en-us/library/cc771314.aspx http://www.petri.co.il/send_mail_from_script.htm Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Getting a variable by name and concatention I am having this problem getting a variable by its name. What I am doing is including a path with connections and I want the connections are named in a certain way. I want to iterate through those conenctions and add them to a queue but the problem is, I cannot use '.' to concat a variable. Code looks like this. Config File: //Set the host the databse will connect too $config_db_hostname='xxx.xxx.xxx'; //Set the user who is connecting to the database $config_db_user='a user'; //Set the password for user who is connecting to the database $config_db_pass='abc123'; //Set the database type $config_db_type='mysql'; //Set the name of the database $config_db_name='phonephare_development'; //Optional: Set the schema, if any $config_db_schema=''; //Optional: Set the port, otherwise default port will be used $config_db_port=''; //Set the prefix for the table names $config_db_prefix='pf_'; //Set the host the databse will connect too $config_db_hostname_1='localhost'; //Set the user who is connecting to the database $config_db_user_1='test'; //Set the password for user who is connecting to the database $config_db_pass_1='test'; //Set the database type $config_db_type_1='mysql'; //Set the name of the database $config_db_name_1='test_development'; //Optional: Set the schema, if any $config_db_schema_1=''; //Optional: Set the port, otherwise default port will be used $config_db_port_1=''; //Set the prefix for the table names $config_db_prefix_1='pv_'; Function for getting values: public static function init(){ if(file_exists(PV_DB_CONFIG)){ include(PV_DB_CONFIG); for ($i = 0; $i <= 3; $i++) { if($i){ $profile_id='_'.$i; } else { $profile_id=''; } // Database variables self::$connections['connection'.$profile_id]['dbhost'] = ($config_db_hostname.$profile_id); self::$connections['connection'.$profile_id]['dbuser'] = $config_db_user.$profile_id; self::$connections['connection'.$profile_id]['dbpass'] = $config_db_pass.$profile_id; self::$connections['connection'.$profile_id]['dbtype'] = $config_db_type.$profile_id; self::$connections['connection'.$profile_id]['dbname'] = $config_db_name.$profile_id; self::$connections['connection'.$profile_id]['dbport'] = $config_db_port.$profile_id; self::$connections['connection_'.$profile_id]['dbschema'] = $config_db_schema.$profile_id; self::$connections['connection_'.$profile_id]['dbprefix'] = $config_db_prefix.$profile_id; } } }//end init So how can I dynamically read this variables? A: You can read 'dynamic' variables like this: $varname = 'config_db_user'; if ($i) $varname .= '_' . $i; $varvalue = $$varname; // $varvalue contains the value now. But this will make your code really hard to read and hard to maintain. Rather make your config like this: $profiles[1]['config_db_user'] = 'whatever'; Then, you can just read $profiles[$profile_id]['configfield] to get what you want. There are probably other ways that may even be better, but stop putting together dynamic variable names, because that's the worst of all. A: Check PHP variable variables. Note: that's a bad config file format to start with, you really should put the separate connections to different arrays. Check the config file of phpmyadmin. A: Construct your data in a different way. You want to iterate trough group of variables that share a similar name.. yet, it didn't occur to you to use an array for config options and iterate trough that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7611300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Velocity template has implicit request object? I'm rephrasing my existing question to a more generic one. I want to know if Velocity has got implicit object references like JSP does. I'm particularly interested in knowing about the request object. In JSP we can get the attribute in the request scope like <%= request.getAttribute("req1") %> I know that JSP is a servlet and <%= request.getAttribute("req1") %> ends up as a part of _jspService() method which has the request object available to it before the scope of the request ends. I'm not sure how Velocity works behind the scenes (it may be leaving the request object behind by the time it plays it role) To test that I did the following thing which was a the part of my previous question. I have a Spring MVC TestController in which I'm setting a request attribute. I'm using Velocity templates for rendering the views. @RequestMapping(value="/test", method=RequestMethod.GET) public ModelAndView display(HttpServletRequest req, HttpServletResponse resp){ ... req.setAttribute("req1", "This should be present for first request"); ... } In the Velocity template I'm doing something like Request: $request.getAttribute('req1') but I'm not getting the value of req1. I know I should have put req1 in model map instead of request but I want to know about implicit request object ref. I tried $req1 as well but its not working. When I'm doing the same thing with the model and returning it back, everything is working correctly. Where am I going wrong? Update: The same thing is happening with req.getSession().setAttribute("req1", testObject) also. A: Salaam, req.getSession().getAttribute("req1", testObject) == $req1 AFAIK, you cannot access the request object at VelocityViewServlet's templates, unless you explicity set the request object in context or use a v-tool . A: Take a look at this question: Velocity + Spring. The Spring folks haven't kept the integration with Velocity very up to date. Once you've created that extension and set it up to be used properly in your servlet configuration, you'd be able to simply put the object on the ModelAndView and from there do whatever you need with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I populate a cell based on 3 possible values in another cell selected from a drop down list? Below is the formula I've tried for D9 in my workbook and I get the error NAME? =IF(C9=Yes,"PASS",IF(C9=No,"FAIL",IF(C9=Unclear/Insufficient,"QUERY","-"))) Help appreciated ALSO.... Having solved that, how do I use the Conditional Formatting icon stack to create a green flag for PASS, orange flag for QUERY and red flag for FAIL? A: You have to use quotes for YES, NO and the other one: =IF(C9="Yes","PASS",IF(C9="No","FAIL",IF(C9="Unclear/Insufficient","QUERY","-"))) And using ',' instead of ';' as parameter separator seams strange to me, I supose that is because of your regional configuration or something like that. A: Try =IF(C9="Yes","PASS",IF(C9="No","FAIL",IF(C9="Unclear/Insufficient","QUERY","-")))
{ "language": "en", "url": "https://stackoverflow.com/questions/7611310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory leak when using TBXML in Objective-C I'm new to Objective C and am still not very clear about how to use retain and release. In the following code, I want to use TBXML to parse an XML file and populate a TableView. The code works, but when I "Analyze" my app, Xcode says there are memory leaks in the variable name. I suppose I should release the variable after retaining it, however, whenever I tried to release it, no matter where I do it, it always produced an error. I also tried NOT to retain it, but it also produced an error. Can somebody please explain what is happening here? - (void)loadNews { TBXML * tbxml = [[TBXML tbxmlWithURL:[NSURL URLWithString:@"http://www.abc/def.xml"]] retain]; // If TBXML found a root node, process element and iterate all children if (tbxml.rootXMLElement) { TBXMLElement *categoryElement = [TBXML childElementNamed:@"category" parentElement:[tbxml rootXMLElement]]; do { NSString *name = [TBXML valueOfAttributeNamed:@"name" forElement:categoryElement]; [name retain]; // Something wrong with this line? NewsCategory *newsCategory = [[NewsCategory alloc] initWithCategoryName:name]; // get entries in the category TBXMLElement *entryElement = [TBXML childElementNamed:@"entry" parentElement: categoryElement]; do { NSString *title = [TBXML textForElement:[TBXML childElementNamed:@"title" parentElement:entryElement]]; NSString * icon = [TBXML textForElement:[TBXML childElementNamed:@"icon" parentElement:entryElement]]; NSString * link = [TBXML textForElement:[TBXML childElementNamed:@"link" parentElement:entryElement]]; NSString * desc = [TBXML textForElement:[TBXML childElementNamed:@"desc" parentElement:entryElement]]; NewsEntry *newsEntry = [[NewsEntry alloc] init]; newsEntry.title = title; newsEntry.icon = icon; newsEntry.link = link; newsEntry.desc = desc; [newsCategory addEntry:newsEntry]; [newsEntry release]; } while((entryElement = entryElement->nextSibling)); // save category [newsData addCategory:newsCategory]; [newsCategory release]; } while((categoryElement = categoryElement->nextSibling)); } // release resources [tbxml release]; [newsTableView reloadData]; } A: If the guys who created [TBXML valueOfAttributeNamed: forElement:] followed the naming convention the value should be autoreleased. You do not need to retain it. However, you need to retain or copy it in the [NewsCategory initWithCategoryName:] metod.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magnolia CMS's built-in Form: SMTP configuration overriding "From" input On the following page http://documentation.magnolia-cms.com/modules/mail.html#ConfiguringSMTP In the section "Sending messages >> Plain text and HTML messages", we can read: From:[...]Regardless of the address entered here, Magnolia CMS will use the smtpUser to send the email but the address here is displayed as the sender to the recipient. This means you can send an email from [email protected] and it will appear to come from this address However, when I receive the email I can still see the smtpUser config's email and my "[email protected]" email address is not displayed (it is ignored!?) Am I missing something? Thanks A: I just tried this on the demo site at http://demoauthor.magnolia-cms.com/demo-project/service/contact.html and it seemed to work as expected. Are you using a fresh install of Magnolia 4.4.5? Could you verify that you're hitting the "Edit Form Settings" button on the page, going to the "E-Mail" tab, and entering "[email protected]" into the From field there? If you're then trying the form on a public instance, you'll need to be sure that the form page has been activated so that the public version of it has your "From" setting as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert a coldfusion website into Native Mobile application I have a coldfusion website running in my server.I have to develop an Mobile application say for iPhone/Android.(I am not mentioning mobile website). I dono much about the native mobile development however I guess there is a possibility to achieve using phonegap and other cross platform dev tools. Please suggest me how would I convert my website to native installable mobile application? A: PhoneGap will allow you to convert a html application. However ColdFusion is a serverside generated HTML and thus cant be converted using PhoneGap unless the entire application is html with ajax calls to ColdFusion for the data. I dont know of any technologies that will allow you to convert a server generated html type language to a native app, I dont believe one exists. A: You can also use Appsgeyser.com for convering your HTML website into an app. All online and no SDK to install.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get required folder URL using java swings? I am using Netbeans for java application. during my application at one point i want particular folder URL to store files. how can i achieve this. please can anyone help me.. Thanks in advance :) A: Use a JFileChooser, with JFileChooser.DIRECTORIES_ONLY Take a look at this tutorial: How to Use File Choosers JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); A: You want to select a folder in a swing application, right? you can use JFileChooser http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html to select only a folder, look at this example http://www.rgagnon.com/javadetails/java-0370.html for the saving, check http://download.oracle.com/javase/tutorial/essential/io/file.html if you need something clarified, just ask. A: I guess you want a Open File Dialog box. In Swing it is called JFileChooser. Usage example: JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(yourJFrame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // Do stuff with file } else { // User clicked cancel } yourJFrame should be the JFrame you use for your main window. If you don't have one put null.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: not able to change background using CCLayerColor and initWithColor:cc4(255,255,255,255) i am working on very first tutorial on cocos2d understanding basic concept.I am trying to change background color from default(black) to white.here is my code: #import <Foundation/Foundation.h> #import "cocos2d.h" @interface GameScene : CCLayerColor { CCSprite *player; } +(id) scene; @end and implementation goes here: #import "GameScene.h" @implementation GameScene +(id) scene { CCScene *scene = [CCScene node]; CCLayer *layer = [CCLayer node]; [scene addChild:layer]; return scene; } -(id) init { if ((self=[super initWithColor:ccc4(255, 255, 255, 255)])) { self.isAccelerometerEnabled=YES; player= [CCSprite spriteWithFile:@"Icon-72.png"]; CGSize screenSize=[[CCDirector sharedDirector] winSize]; float imageHeight=[player texture].contentSize.height; player.position=CGPointMake(screenSize.width/2, imageHeight/2); [self addChild:player z:0 tag:123]; } return self; } -(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { CGPoint pos=player.position; pos.x+=acceleration.x*10; player.position=pos; } - (void)dealloc { [super dealloc]; } @end any suggestion? thanks A: CCDirectory only takes CCScenes. So most likely the black screen you experience is not a faulty CCColorLayer, but simply the blank stage. Subclass CCScene as GameScene, then add a CCLayerColor to that with your desired color, as well as your player. Then call [[CCDirector sharedDirector] runWithScene:gameScene].
{ "language": "en", "url": "https://stackoverflow.com/questions/7611335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Prefix.pch not included at compilation time I have defined many constants in GlobalVar.h and other .h files. I import these files in the Prefix.pch file like this : // // Prefix header for all source files of the 'XXX' target in the 'XXX' project // #import "GlobalVar.h" [...] #ifndef __IPHONE_3_0 #warning "This project uses features only available in iPhone SDK 3.0 and later." #endif #ifdef __OBJC__ #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #endif But when I compile the project all the #defined identifiers are missing and reported as "Use of undeclared identifier XXX". I searched in the Build settings and the PCH file is set as "Prefix Header"... I am on Base SDK 4.3 and XCode 4.0.2 Do you have hints to debug this ? Thanks for your help A: I came across this error yet, after cleaning DerivedData and restart Xcode I fix it. Hope to help. A: move your import to like so #ifdef __OBJC__ #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "GlobalVar.h" #endif
{ "language": "en", "url": "https://stackoverflow.com/questions/7611341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSF 2.0, messages not displayed inside a dataTable I have a form with a dataTable which has various columns having links and outputTexts. There is one input field which is evaluated through an ajax request . A custom validator makes sure that only integers are added to the field. The form is below. <form> <h:dataTable var="item" value="#{listItems.model}" id="adminlistItems"> //other columns having commandLinks and outputTexts <h:column> <f:facet name="header" > <h:outputText value="Quantity"/> </f:facet> <f:ajax listener="#{listItems.AddQuantityAction}"> <div style="padding:5px;float:left"> <h:inputText label="changeQuantity" id="addquantity" value="#{item.additionalQuantity}" maxlength="4" size="3"> <f:validator validatorId="integerValidator"/> </h:inputText> <h:outputText value="&nbsp;"/> <h:commandButton value="AddQuantity" /> <h:message for="addquantity"/> </div> </f:ajax> </h:column> </h:dataTable> </h:form> The code for the bean is : @ViewScoped @ManagedBean public class ListItems implements Serializable { //... public String AddQuantityAction(){ //... boolean result = //some action FacesContext context=FacesContext.getCurrentInstance(); UIComponent component=UIComponent.getCurrentComponent(context); String clientID=component.getClientId(context); if (result) { FacesMessage message = new FacesMessage("Quantity added successfully"); FacesContext.getCurrentInstance().addMessage(clientID, message); } else { FacesMessage message = new FacesMessage("Quantity not added.Processing error"); FacesContext.getCurrentInstance().addMessage(clientID, message); } return "adminListItems"; } } The custom validator throws a validator exception which is not displayed. And the listener also has code for messages which too are not displayed. I have read several similar questions and this sounds a common question too. But even if i am missing something obvious,i am in need of a third eye to see what i dont. A: The execute and render of <f:ajax> defaults to @this. So only the currently active component will be processed and refreshed. When you press the button, this won't send the input value nor refresh the message component. Fix it accordingly: <f:ajax execute="addquantity" render="addquantity_message" listener="#{listItems.AddQuantityAction}"> ... <h:message id="addquantity_message" for="addquantity"/> ... </f:ajax> By the way, why don't you just use the builtin javax.faces.Integer converter instead of that validator? <h:inputText ... converter="javax.faces.Integer"> Further, the return value of ajax listener methods should be void. It's totally ignored in any way. Also, method names should start with lowercase. See also Java naming conventions. Update as per the comment, that didn't seem to work out well with regard to validation. The listener is invoked 2 times because essentially 2 ajax requests are been sent, one for the input and one for the command. I suggest to move the listener method to the <h:commandButton action>. <f:ajax execute="addquantity" render="addquantity_message"> ... <h:commandButton action="#{listItems.AddQuantityAction}" /> <h:message id="addquantity_message" for="addquantity"/> </f:ajax> You'll only fix the obtained client ID to be the input ID, not the button ID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# - Load simple Excel file into a datatable using FileUpload control I'm trying to figure out how to populate a datatable with data from and Excel file that's been uploaded using the FileUpload control. Does anyone know of a tutorial to do this? I haven't been able to find anything on Google, maybe using wrong search terms? A: Use LinqToExcel to parse data. Then, when you have the data in memory, put it into a database whichever way you prefer. A: Perhaps an alternative way? This is vb.net but the same objects. I do this sort of thing all the time. http://social.msdn.microsoft.com/Forums/en-US/isvvba/thread/7337ad66-7673-425b-97ff-41adbd8a68e9 A: Look at this: http://forums.asp.net/t/1255191.aspx/1 It is C#, using OLEDB so third party libraries are not needed, and a DataTable is populated with the excel data. These are my google search terms: "upload excel file to datatable c#"
{ "language": "en", "url": "https://stackoverflow.com/questions/7611347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can a page post on another page's wall? Using FQL, I want to get the posts on a page's wall. Each one of these posts hasa an actor_id. Can I assume that all the actor_id's are either users or the owning page's id? This assumption would be false if another page could post on this page's wall. A: Yes, a page can post on another page's wall. If you have a Facebook page (which is NOT an application profile page) then you can click the arrow in the upper-right UI of Facebook and say "Use Facebook as a Page", select your page, and you will be "logged in" as that page. Pages can Like other pages, post on their walls, and comment, but they can't participate in apps or post to individual users. Use that to test the scenario where one page posts to another.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery CSS Selector background I've to do the following simple CSS selector using jQuery , but I can't : "#test > *" I've tried in many ways but I just can't do that! $("#jqt > *") or $('*',$("#jqt")).css() the last one seemed to work but I realized that it shoudnt!! How should I do this simple selection to add a very simple CSS property (background-image and font-family)???? Thanks in advance A: Instead of $("#jqt > *") try $("#jqt").children() A: This works, if you're wanting to select immediate children: $("#jqt > *").css({ 'background-image' : 'url(...)', 'font-family' : 'arial'}) jsFiddle A: I guess you are trying to apply css only on the "direct children" of #jqt. Here is a trick to avoid your style from being applied to the sub child elements: HTML: <div id="jqt"> <a>link</a> <p>paragraph</p> <div>div</div> <div class="no_inherit"> <a>sub link</a> <p>sub paragraph</p> <div>sub div</div> </div> </div> CSS: .mystyle { background-image: url(img.png); font-family: "courier"; } jQuery: $('#jqt').children().not(".no_inherit").addClass('mystyle'); If you remove not(".no_inherit"), the CSS is applied to the elements in the elements in #jqt > div, so all elements are styled. Fiddle here : http://jsfiddle.net/7AM5Z/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7611356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python String to List with RegEx I would like to convert mystring into list. Input : "(11,4) , (2, 4), (5,4), (2,3) " Output: ['11', '4', '2', '4', '5', '4', '2', '3'] >>>mystring="(11,4) , (2, 4), (5,4), (2,3)" >>>mystring=re.sub(r'\s', '', mystring) #remove all whilespaces >>>print mystring (11,4),(2,4),(5,4),(2,3) >>>splitter = re.compile(r'[\D]+') >>>print splitter.split(mystring) ['', '11', '4', '2', '4', '5', '4', '2', '3', ''] In this list first and last element are empty. (unwanted) Is there any better way to do this. Thank you. A: >>> re.findall(r'\d+', "(11,4) , (2, 4), (5,4), (2,3) ") ['11', '4', '2', '4', '5', '4', '2', '3'] A: It would be better to remove whitespace and round brackets and then simply split on comma. A: >>> alist = ast.literal_eval("(11,4) , (2, 4), (5,4), (2,3) ") >>> alist ((11, 4), (2, 4), (5, 4), (2, 3)) >>> anotherlist = [item for atuple in alist for item in atuple] >>> anotherlist [11, 4, 2, 4, 5, 4, 2, 3] Now, assuming you want list elements to be string, it would be enough to do: >>> anotherlist = [str(item) for atuple in alist for item in atuple] >>> anotherlist ['11', '4', '2', '4', '5', '4', '2', '3'] The assumption is that the input string is representing a valid python tuple, which may or may not be the case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Opening multiple files in Fortran 90 I would like to open 10,000 files with file names starting from abc25000 until abc35000 and copy some information into each file. The code I have written is as below: PROGRAM puppy IMPLICIT NONE integer :: i CHARACTER(len=3) :: n1 CHARACTER(len=5) :: cnum CHARACTER(len=8) :: n2 loop1: do i = 25000 ,35000 !in one frame n1='abc' write(cnum,'(i5)') i n2=n1//cnum print*, n2 open(unit=i ,file=n2) enddo loop1 end This code is supposed to generate files starting from abc24000 until abc35000 but it stops about half way saying that At line 17 of file test-openFile.f90 (unit = 26021, file = '') Fortran runtime error: Too many open files What do I need to do to fix the above code? A: This limit is set by your OS. If you're using a Unix/Linux variant, you can check the limit using from the command line using ulimit -n, and raise it using ulimit -n 16384. You'll need to set a limit greater than 10000 to allow for all the other files that the shell will have open. You may also need admin privileges to do this. I regularly bump the limit up to 2048 to run Fortran programs, but never as high as 10000. However, I echo the other answers that, if possible, it's better to restructure your program to close each file before opening the next. A: Operating systems tend to have limits on resources. Typically on, for instance, Linux, there is by default a limit of 1024 file descriptors per process. The error message you're getting is just the Fortran runtime library passing information upwards that it was unable to open yet another file due to an OS error. A: You need to work on the files one at a time (or in small groups that do not exceed the limitation imposed by the operating system). for each file: open file write close file
{ "language": "en", "url": "https://stackoverflow.com/questions/7611360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: alternative to Resharper "go to file" and "go to implementation" features Does anybody know a light plug-in that do (same as Resharper) go to implementation and the quick search for a file where you just insert few characters and it shows the matches? I just want to get rid of Resharper cause it slows me down a lot!! A: To answer the original question, as per this post by Andrew Arnott, you can use Ctrl+/ to move the cursor to the Find text box in the toolbar, then type ">of" and start typing file names. The matching files will appear as you type. Using the ">" prefix causes the find text box to act as the command window would. (Note that the Ctrl+/ short-cut may be overridden by ReSharper to comment a line of code, so this short-cut only works with ReSharper uninstalled.) A: That's interesting. I use ReSharper and it uses about 400mb of RAM. I would consider that pretty low usage. Maybe you can look into Productivity Power Tools (I don't use it). http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/
{ "language": "en", "url": "https://stackoverflow.com/questions/7611364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dynamically created Binding does not work I want to bind TextBlocks to a Modell. But it does not work and I have no idea why. class GameModel : INotifyPropertyChanged { string[] _teamNames; ... public string teamName(int team) { return _teamNames[team]; } public void setTeamName(int team, string name) { _teamNames[team] = name; OnPropertyChanged("teamName"); } protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } And the code which creates the TextBoxes for (int currCol = 0; currCol < teams; currCol++) { TextBlock teamNameBlock = new TextBlock(); Binding myNameBinding = new Binding(); myNameBinding.Source = myGame; myNameBinding.Path = new PropertyPath("teamName", currCol); myNameBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; teamNameBlock.SetBinding(TextBlock.TextProperty, myNameBinding); //The name of the team bind to the TextBlock ... } A: I think the problem is you bind to public string teamName(int team) { return _teamNames[team]; } what is team parameter and the moment of change? Who sets that parameter. Make something like this, instead: public string teamName { get { return _teamNames[currTeam]; } } You bind to a property, which returns the team name based on currTeam index, which is settuped based on you app logic. Hope this helps. A: Here's a full, working example. The idea is to use an indexed property to access the team names. Note how the binding path is created: PropertyPath("[" + currCol + "]") , and how the property change is notified: OnPropertyChanged("Item[]"); After the creation of controls, the name of the 3rd team is changed to "Marge" to test the binding. using System; using System.ComponentModel; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; namespace TestBinding { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } public override void OnApplyTemplate() { base.OnApplyTemplate(); CreateTeamControls(); myGame[2] = "Marge"; } void CreateTeamControls() { var panel = new StackPanel(); this.Content = panel; int teams = myGame.TeamCount; for (int currCol = 0; currCol < teams; currCol++) { TextBlock teamNameBlock = new TextBlock(); panel.Children.Add(teamNameBlock); Binding myNameBinding = new Binding(); myNameBinding.Source = myGame; myNameBinding.Path = new PropertyPath("[" + currCol + "]"); myNameBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; teamNameBlock.SetBinding(TextBlock.TextProperty, myNameBinding); } } GameModel myGame = new GameModel(); } } class GameModel : INotifyPropertyChanged { string[] _teamNames = new string[3]; public int TeamCount { get { return _teamNames.Count(); } } public GameModel() { _teamNames[0] = "Bart"; _teamNames[1] = "Lisa"; _teamNames[2] = "Homer"; } public string this[int TeamName] { get { return _teamNames[TeamName]; } set { if (_teamNames[TeamName] != value) { _teamNames[TeamName] = value; OnPropertyChanged("Item[]"); } } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { var changedHandler = this.PropertyChanged; if (changedHandler != null) changedHandler(this, new PropertyChangedEventArgs(propertyName)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server Express database replication/synchronization Situation: Hi, I'm coding using Lightswitch (C#) and am thinking of deploying to multiple sites the same application and database. The databases need to be synchronized/replicated to each other so each would have a merged database. However connectivity between the sites is not going to be 100%, so the synchronization/replication would be done whenever the connection is possible. Question: Would it be possible to accomplish this through SQL Server Express? If not, what would be the best way to accomplish this by code? Thanks! A: SQL Server Express 2008 can be a subscriber but not a publisher, see details here: Replication Considerations (SQL Server Express) Microsoft SQL Server 2008 Express (SQL Server Express) can serve as a Subscriber for all types of replication, providing a convenient way to distribute data to client applications that use SQL Server Express. When using SQL Server Express in a replication topology, consider the following: SQL Server Express cannot serve as a Publisher or Distributor. A: SQL Express doesn't support replication (except as a subscriber, as Davide pointed out). I think your best bet would probably be a windows service that keeps track of table names and the most recent timestamp processed. Integration Services is also an option if you have a server to run it on. Do you need data to be moving one-way or both ways?
{ "language": "en", "url": "https://stackoverflow.com/questions/7611372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Synchronize two multiselect box, select by value I am new to JS and Jquery and I am using Eric Hynds jquery-ui-multiselect-widget Here's a very good demo: http://jsfiddle.net/PKypd/11/ In this demo the second select box has its values checked by position depending on which option was selected on the first select box. The example also says that: "you can easily swap out .eq() for another .filter() to choose checkboxes by value instead of their position." But I haven't been able to do so and can not find any documentation on how to do it. Could you guys help me do this? Just can't figure out how to do the .filter() condition to select the options on the second select box by its value. Thanks in advance. EDIT: Here's what I've done so far: http://jsfiddle.net/PKypd/54/ In that example I set the same values for both select boxes. When I click on Canada I'm expecting to select bar on the second box, which has the same value, but it selects all the options. I feel that I'm missing something really simple but can't figure it out. A: In your filter, this is your test: return (ui.value == 'can'); ui refers to the checkbox in the first list that you had clicked. When you click the Canada checkbox, ui.value == 'can' will always be true. This is what you want for your filter instead: return this.value == ui.value; This means to compare the current value of the item being inspected in the filter (this) with the value of the item that was clicked (ui).
{ "language": "en", "url": "https://stackoverflow.com/questions/7611375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generating RSA keys in PKCS#1 format in Java When I generate an RSA key pair using the Java API, the public key is encoded in the X.509 format and the private key is encoded in the PKCS#8 format. I'm looking to encode both as PKCS#1. Is this possible? I've spent a considerable amount of time going through the Java docs but haven't found a solution. The result is the same when I use the Java and the Bouncy Castle providers. Here is a snippet of the code: KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA","BC"); keygen.initialize(1024); KeyPair pair = keygen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); byte[] privBytes = priv.getEncoded(); byte[] pubBytes = pub.getEncoded(); The two resulting byte arrays are formatted as X.509 (public) and PKCS#8 (private). Any help would be much appreciated. There are some similar posts but none really answer my question. Thank You A: From RFC5208, the PKCS#8 unencrypted format consists of a PrivateKeyInfo structure: PrivateKeyInfo ::= SEQUENCE { version Version, privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, privateKey PrivateKey, attributes [0] IMPLICIT Attributes OPTIONAL } where privateKey is: "...an octet string whose contents are the value of the private key. The interpretation of the contents is defined in the registration of the private-key algorithm. For an RSA private key, for example, the contents are a BER encoding of a value of type RSAPrivateKey." This RSAPrivateKey structure is just the PKCS#1 encoding of the key, which we can extract using BouncyCastle: // pkcs8Bytes contains PKCS#8 DER-encoded key as a byte[] PrivateKeyInfo pki = PrivateKeyInfo.getInstance(pkcs8Bytes); RSAPrivateKeyStructure pkcs1Key = RSAPrivateKeyStructure.getInstance( pki.getPrivateKey()); byte[] pkcs1Bytes = pkcs1Key.getEncoded(); // etc. A: You will need BouncyCastle: import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemWriter; The code snippets below have been checked and found working with Bouncy Castle 1.52. Private key Convert private key from PKCS8 to PKCS1: PrivateKey priv = pair.getPrivate(); byte[] privBytes = priv.getEncoded(); PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(privBytes); ASN1Encodable encodable = pkInfo.parsePrivateKey(); ASN1Primitive primitive = encodable.toASN1Primitive(); byte[] privateKeyPKCS1 = primitive.getEncoded(); Convert private key in PKCS1 to PEM: PemObject pemObject = new PemObject("RSA PRIVATE KEY", privateKeyPKCS1); StringWriter stringWriter = new StringWriter(); PemWriter pemWriter = new PemWriter(stringWriter); pemWriter.writeObject(pemObject); pemWriter.close(); String pemString = stringWriter.toString(); Check with command line OpenSSL that the key format is as expected: openssl rsa -in rsa_private_key.pem -noout -text Public key Convert public key from X.509 SubjectPublicKeyInfo to PKCS1: PublicKey pub = pair.getPublic(); byte[] pubBytes = pub.getEncoded(); SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(pubBytes); ASN1Primitive primitive = spkInfo.parsePublicKey(); byte[] publicKeyPKCS1 = primitive.getEncoded(); Convert public key in PKCS1 to PEM: PemObject pemObject = new PemObject("RSA PUBLIC KEY", publicKeyPKCS1); StringWriter stringWriter = new StringWriter(); PemWriter pemWriter = new PemWriter(stringWriter); pemWriter.writeObject(pemObject); pemWriter.close(); String pemString = stringWriter.toString(); Check with command line OpenSSL that the key format is as expected: openssl rsa -in rsa_public_key.pem -RSAPublicKey_in -noout -text Thanks Many thanks to the authors of the following posts: * *https://stackoverflow.com/a/8713518/1016580 *https://stackoverflow.com/a/14052651/1016580 *https://stackoverflow.com/a/14068057/1016580 Those posts contained useful, but incomplete and sometimes outdated info (i.e. for older versions of BouncyCastle), that helped me to construct this post. A: I wrote a C programme to convert pkcs8 private key to pkcs1. It works! /***************************************** convert pkcs8 private key file to pkcs1 2013-1-25 Larry Wu created ****************************************/ #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <openssl/rsa.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/engine.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <assert.h> #include <stdarg.h> #include <fstream> #include <sstream> #include <iostream> #include <map> #include <set> #include <list> #include <vector> using namespace std; #define MY_TRACE_ERROR printf /* gcc -Wall -o pkcs_8to1 pkcs_8to1.cpp -g -lstdc++ -lcrypto -lssl */ int main(int argc, char **argv) { EVP_PKEY * pkey = NULL; string kin_fname; FILE *kin_file = NULL; string kout_fname; FILE *kout_file = NULL; // param if(argc != 3) { printf("Usage: %s <pkcs8_key_file> <pkcs1_key_file>\n", argv[0]); return 1; } kin_fname = argv[1]; kout_fname = argv[2]; // init OpenSSL_add_all_digests(); ERR_load_crypto_strings(); // read key if((kin_file = fopen(kin_fname.c_str(), "r")) == NULL) { MY_TRACE_ERROR("kin_fname open fail:%s\n", kin_fname.c_str()); return 1; } if ((pkey = PEM_read_PrivateKey(kin_file, NULL, NULL, NULL)) == NULL) { ERR_print_errors_fp(stderr); MY_TRACE_ERROR("PEM_read_PrivateKey fail\n"); fclose(kin_file); return 2; } // write key if((kout_file = fopen(kout_fname.c_str(), "w")) == NULL) { MY_TRACE_ERROR("kout_fname open fail:%s\n", kout_fname.c_str()); return 1; } if (!PEM_write_PrivateKey(kout_file, pkey, NULL, NULL, 0, NULL, NULL)) { ERR_print_errors_fp(stderr); MY_TRACE_ERROR("PEM_read_PrivateKey fail\n"); fclose(kout_file); return 2; } // clean fclose(kin_file); fclose(kout_file); EVP_PKEY_free(pkey); return 0; } A: I know this is old post. but I spent two days to solve this problem and finally find BouncyCastle can do that ASN1Encodable http://www.bouncycastle.org/docs/docs1.5on/org/bouncycastle/asn1/ASN1Encodable.html A: The BouncyCastle framework has a PKCS1 Encoder to solve this: http://www.bouncycastle.org/docs/docs1.6/index.html A: I was trying to generate OpenSSL-friendly RSA public keys in DER format using BountyCastle J2ME library ported to BlackBerry, my code: public void testMe() throws Exception { RSAKeyPairGenerator generator = new RSAKeyPairGenerator(); generator.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), 512, 80)); AsymmetricCipherKeyPair keyPair = generator.generateKeyPair(); RSAKeyParameters params = (RSAKeyParameters) keyPair.getPublic(); RSAPublicKeyStructure struct = new RSAPublicKeyStructure(params.getModulus(), params.getExponent()); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier("1.2.840.113549.1.1.1"), struct); byte[] bytes = info.getDEREncoded(); FileOutputStream out = new FileOutputStream("/tmp/test.der"); out.write(bytes); out.flush(); out.close(); } Key was still incorrect: $ openssl asn1parse -in test.der -inform DER -i 0:d=0 hl=2 l= 90 cons: SEQUENCE 2:d=1 hl=2 l= 11 cons: SEQUENCE 4:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 15:d=1 hl=2 l= 75 prim: BIT STRING I changed org.bouncycastle.asn1.x509.AlgorithmIdentifier public AlgorithmIdentifier( String objectId) { this.objectId = new DERObjectIdentifier(objectId); // This line has been added this.parametersDefined = true; } And now have nice key: $ openssl asn1parse -in test.der -inform DER -i 0:d=0 hl=2 l= 92 cons: SEQUENCE 2:d=1 hl=2 l= 13 cons: SEQUENCE 4:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 15:d=2 hl=2 l= 0 prim: NULL 17:d=1 hl=2 l= 75 prim: BIT STRING Which can be used to encrypt: $ echo "123" | openssl rsautl -pubin -inkey test.der -encrypt -keyform DER -out y $ wc -c y 64 y
{ "language": "en", "url": "https://stackoverflow.com/questions/7611383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Solving equations in .NET I'm trying to solve some simple equations in .NET. I came across Math.NET and evaluate it. The Solver() methods seemed to be what I need but I can't figure out how to use side conditions with this method. To illustrate my problem I will give you a sample: Given: 0 <= a_i <= 100 0 <= b <= 100 0 <= c a_i, b and c are given x_1, ..., x_n should be optimized f(x) = x_1*a_1 + x_2*a_2 + ... + x_n*a_n = b Side conditions: g(x) = x_1 + x_2 + ... + x_n = c 0 <= x_i Is it possible to solve such a problem using the solve method or any other component of Math.NET or do you know any (free for commercial use) .NET library that can be used for solving this? I wouldn't like to write an algorithm for such a common problem by myself. Best regards & thanks in advance A: ALGLIB is great for these tasks. Check out their page on constrained optimization. EDIT: It has both a free license (GPL) and a commercial license starting from $370. A: IMHO Microsoft Solver Foundation is the way to go for this. The Express Version is free AFAIK and powerful enough for most smaller applications. As I see now the Express Version is only indented for exploration - but there is (now?) a Standard-Lib for MSDN subscribers so I don't remove this post yet, as you might have a MSDN subscribtion. A: You need an optimizer with constraints like simplex method or Marquardt non-linear optimization.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Reason behind deprecating the Thread's stop(), destroy(), resume() methods I read that the Thread class stop(),destroy(),resume() methods been depricated. As a reason it says: "Because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state" Honestly I didn't understand the reason perfectly from the text. Can someone explain it more clearly please (Perticularly that "VM unpredictable" and "unsafe" words ) Thanks A: Because it unlocks all Monitors the Thread has locked, and so other Threads may access an Object with an inconsistent state. For further infos: http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html A: This article http://developer.android.com/resources/articles/painless-threading.html explains the threading model used in Android. Quoting from that page the Android UI toolkit is not thread-safe Meaning if you are doing a lot of thread manipulation you can run into some pretty weird, seemingly random bugs. Instead you should be using AsyncTasks to accomplish things that take too long for the UI thread. This would include things like saving to and SD card, accessing a database, or sending a network request. For more info on AsyncTasks see the article I linked to above as well as http://developer.android.com/reference/android/os/AsyncTask.html A: stop() and resume() have been deprecated in Java for a decade or so. destroy() has been deprecated in Java since Java 1.5. Dalvik is simply mirroring Java's capabilities.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's exactly the difference between using strand::post and io_service::post with strand::wrap? In my understanding, posting handlers to a strand object means: * *Only one of the posted handlers is executed at a time. *The handlers are invoked in order. Posting handlers directly to an io_service object and wrapping them by strand::wrap also means that only one of the posted handlers is executed at a time, but not in order. Is there any other difference? And how can I run two (or more) different kind of works (so, different handlers/functions) parallel (in different threads) by using strand? A: If you want them to run in parallel don't use stands. Strands are for serializing. Just post to the service and have the service run in a thread pool. But you bring up a good point that I would like someone to answer. What exactly is the difference? If wrap serializes all handlers then how could they get out of order, i.e. seems like it does the same thing as posting through a strand? Where would you use one over the other? A: In fact, strand is a queue, so posting a handler to io_service by wrap is same as not to wrap because each time you post it, you do in a distinct temp strand (each queue contains only one handler -- all those handlers can be executed concurrently because they are not in the same strand). If you need serialized handlers, they must be wrapped by the same strand object (which therefore contains more than one handler).
{ "language": "en", "url": "https://stackoverflow.com/questions/7611389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is it possible to use phonegap for just a part of the application? Is it possible to use Phonegap for only a part of an application ? For instance on Android (but my question includes other OS as well), can an Activity use Phonegap components and native components (in the same screen) ? Thank you. A: The little experience below seem to answer my needs, at least on Android. I guess a similar hack can be made on the other OS. public class TestPhonegapActivity extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); loadUrl("file:///android_asset/www/index.html"); LinearLayout linearLayout = new LinearLayout(this); ((ViewGroup) appView.getParent()).removeView(appView); linearLayout.addView(appView); TextView textView = new TextView(this); textView.setText("Native"); linearLayout.addView(textView); setContentView(linearLayout); } } A: You can simply use : LinearLayout layout = super.root; and then add what you want: TextView textView = new TextView(this); textView.setText("Native"); linearLayout.addView(textView);
{ "language": "en", "url": "https://stackoverflow.com/questions/7611391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Maximum size of a varchar(max) variable At any time in the past, if someone had asked me the maximum size for a varchar(max), I'd have said 2GB, or looked up a more exact figure (2^31-1, or 2147483647). However, in some recent testing, I discovered that varchar(max) variables can apparently exceed this size: create table T ( Val1 varchar(max) not null ) go declare @KMsg varchar(max) = REPLICATE('a',1024); declare @MMsg varchar(max) = REPLICATE(@KMsg,1024); declare @GMsg varchar(max) = REPLICATE(@MMsg,1024); declare @GGMMsg varchar(max) = @GMsg + @GMsg + @MMsg; select LEN(@GGMMsg) insert into T(Val1) select @GGMMsg select LEN(Val1) from T Results: (no column name) 2148532224 (1 row(s) affected) Msg 7119, Level 16, State 1, Line 6 Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. The statement has been terminated. (no column name) (0 row(s) affected) So, given that I now know that a variable can exceed the 2GB barrier - does anyone know what the actual limit is for a varchar(max) variable? (Above test completed on SQL Server 2008 (not R2). I'd be interested to know whether it applies to other versions) A: EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value syntax is incorrect. I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. error message. In 2008, the modified script is still successful. declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024); declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024); declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024); declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg; select LEN(@GGMMsg) A: As far as I can tell there is no upper limit in 2008. In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes. the code below fails with REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type. However it appears these limitations have quietly been lifted. On 2008 DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); SET @y = REPLICATE(@y,92681); SELECT LEN(@y) Returns 8589767761 I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory Running select internal_objects_alloc_page_count from sys.dm_db_task_space_usage WHERE session_id = @@spid Returned internal_objects_alloc_page_co ------------------------------ 2144456 so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this. The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables. Paul White confirms the above supposition here and also provides the information that the variable is held entirely in memory if <= 512KB and changes to the tempdb-based backup scheme for values larger than that. Addition I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run). DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); SET @y1 = @y1 + @y1; SELECT LEN(@y1), DATALENGTH(@y1) /*4294967294, 4294967292*/ DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); SET @y2 = @y2 + @y2; SELECT LEN(@y2), DATALENGTH(@y2) /*2147483646, 4294967292*/ DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1 SELECT LEN(@y3), DATALENGTH(@y3) /*6442450940, 12884901880*/ /*This attempt fails*/ SELECT @y1 y1, @y2 y2, @y3 y3 INTO Test
{ "language": "en", "url": "https://stackoverflow.com/questions/7611394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "101" }
Q: Passing ampersand from JavaScript to PHP/MySQL I have a textarea which I'm using JavaScript to retrieve the value of and send to a MySQL database via a PHP script (don't ask why - long story and an unavoidable resolution!). The PHP script sanitizes the input, but for some reason ampersands aren't ever reaching the said script - it also culls any information after the ampersand. var Reason = $('textarea#txt_reason').val(); Reason = Reason.replace(/&/g,'&amp;'); If I use the above, all text after the ampersand is culled. var Reason = $('textarea#txt_reason').val(); Reason = Reason.replace(/&/g,'%26'); If I use the above, the %26 does indeed get sent through to PHP and thus the MySQL database. If I var_dump the $_GET request in the PHP script, the ampersands never get that far so it isn't anything to do with mysql_real_escape_string/htmlentities etc. Is there a way I can directly send "&" to my PHP script, without having to encode/decode? Cheers, Duncan A: Any data that you send using Javascript should be encoded with encodeURIComponent(). This will take care of the &, =, and other troublemakers. The data is automatically decoded into the $_GET array. (Most Javascript frameworks such as JQuery do this for you...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7611395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error setting layout params to ImageView I'm having issues trying to set layoutparams to an ImageView created programmatically: imageView.setLayoutParams(new LinearLayout.LayoutParams(gallerySize.x, gallerySize.y)); The imageView is inside an LinearLayout, and I think that should work, but I get this error: 09-30 10:33:24.450: ERROR/AndroidRuntime(5418): java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams Maybe, the fact that this imageView Activity is configured to use an different layout for portrait and landscape view (I'm using this with an different copy of xml layout inside the layout-land folder). When it's in portrait view the problematic code line isn't executed, instead I execute the following line: imageView.setLayoutParams(new Gallery.LayoutParams(gallerySize.x, gallerySize.y)); I tried to keep this line unchanged, but then I get the error: 09-30 10:49:47.450: ERROR/AndroidRuntime(5760): java.lang.ClassCastException: android.widget.Gallery$LayoutParams The main difference in the portrait and landscape layout, is that portrait uses a LinearLayout with vertical orientation and have an Gallery widget (that uses that imageView), while the problematic landscape uses horizontal orientation and ListView instead of Gallery. I'm kind lost here, any tips will be appreciated. EDITED The imageView is implemented in this class: public class ImageAdapter extends BaseAdapter { @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(mContext); Bitmap temp = BitmapFactory.decodeFile(appFolder+"/"+imagesPath[position]); //productImages[position] = temp; imageView.setImageBitmap(temp); if(landscape) imageView.setLayoutParams(new LinearLayout.LayoutParams(gallerySize.x, gallerySize.y)); else imageView.setLayoutParams(new Gallery.LayoutParams(gallerySize.x, gallerySize.y)); imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); imageView.setBackgroundResource(mGalleryItemBackground); return imageView; } } And the ImageAdapter instance is used here: public onCreate(...) { ... if(!landscape) { Gallery gallery = (Gallery) findViewById(R.infoproduto.gallery); gallery.setAdapter(new ImageAdapter(this)); gallery.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View v, int position, long id) { setSelectedImage(position); } }); } else { ListView galleryLView = (ListView) findViewById(R.infoproduto.galleryLView); galleryLView.setAdapter(new ImageAdapter(this)); galleryLView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View v, int position, long id) { setSelectedImage(position); } }); } } A: Well, I figured out the solution, it was so obvious! The ImageView is used inside ImageAdapter, and this ImageAdapter is setted as adapter in an ListView instance: ListView galleryLView = (ListView) findViewById(R.infoproduto.galleryLView); galleryLView.setAdapter(new ImageAdapter(this)); So Instead using LinearLayout.LayoutParams (that is the only layout in my xml file), i used ListView.LayoutParams and it works perfectly!
{ "language": "en", "url": "https://stackoverflow.com/questions/7611396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I put some space around td text? I have a demo here how can I put some space around the texts in side the table? also why not the css class is working in the demo? css .recomendationsTable{ width:100%;overflow:hidden; } .recomendationsTable tr{ border:#2F5882 1px solid; } .recomendationsTable tr th{ color :#ffffff; background-color: #93A8BF; } .recomendationsTable tr .odd{ color :#FFFFFF; background-color: #8EA4BB; border:#2F5882 1px solid; } .recomendationsTable tr .even{ color :#2F5882; background-color: #EDF1F5; border:#2F5882 1px solid; } A: The reason it didn't work was because of the spaces between the class and the element. .recomendationsTable { width:100%;overflow:hidden; } .recomendationsTable tr { border:#2F5882 1px solid; } .recomendationsTable tr th { color :#ffffff; background-color: #93A8BF; } .recomendationsTable tr.odd { color :#FFFFFF; background-color: #8EA4BB; border:#2F5882 1px solid; } .recomendationsTable tr.even { color :#2F5882; background-color: #EDF1F5; border:#2F5882 1px solid; } Additionally, to add space you need to add the following (first value vertical padding, second horizontal - this example gives 10px on both sides): .recomendationsTable tr td { padding: 0 10px; } A: Add some padding: td { padding: 5px; } As far as the even and odd rows not showing up, just remove the space between tr .even and tr .odd. With the space, the CSS selector is looking for a descendant with the even or odd class. Without the space, you're telling it to look for a tr with an even or odd class attached to it. On another note, it might be better to generate your table programmatically instead of through HTML strings; it's a little easier to maintain: var $table = jQuery("<table></table>").attr("class", "recommendationsTable"); var $tr = jQuery("<tr></tr>"); $tr.append(jQuery("<th></th>".attr("align", "left").text("Recommendation(s)")); $table.append($tr); $tr = jQuery("<tr></tr>").attr("class", "even"); $tr.append(jQuery("<td></td>").text(ruleactionresult1)); $table.append($tr); ... An even better way would be to put this into a loop: var rules = ["bbbbb", "aaaa"]; var classes = ["even", "odd"]; var i = 0; var $table = jQuery("<table></table>").attr("class", "recommendationsTable"); var $tr = jQuery("<tr></tr>"); $tr.append(jQuery("<th></th>".attr("align", "left").text("Recommendation(s)")); $table.append($tr); for(var i = 0; i < 5; i++) { $tr = jQuery("<tr></tr>").attr("class", class[i % 2]); $tr.append(jQuery("<td></td>").text(rules[i % 2])); $table.append($tr); } Updated fiddle. A: why not the css class is working in the demo ? You should remove the space between tr and .odd, tr and .even I have a demo here how can I put some space around the texts in side the table? Use Td padding see answers above A: /* tr.even & tr.odd (joined) means tr with the evenodd class applied if there is a space, it means an element within the tr element */ .recomendationsTable tr.odd { color :#FFFFFF; background-color: #8EA4BB; border:#2F5882 1px solid; } .recomendationsTable tr.even { color :#2F5882; background-color: #EDF1F5; border:#2F5882 1px solid; } /* Also, add some padding between the cell's border and the text */ .recomendationsTable tr th, .recomendationsTable tr td { padding: 2px; } Demo can be found here A: in one shot add cellpadding to the created table as attribute or if you want to play with classes set new definition in your css to the td also i.e. .recomendationsTable td { padding:'what ever you want';} A: Put a DIV in the cell, surrounding the text and give the DIV some padding. or: table tr td, table tr th { padding: 5px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the date of the next Sunday? Possible Duplicate: ASP.net get the next tuesday Given a day of the month, how can I get the next sunday from that day? So if I pass in Tuesday September 13th 2011, it will return Sept. 18th. A: /// <summary> /// Finds the next date whose day of the week equals the specified day of the week. /// </summary> /// <param name="startDate"> /// The date to begin the search. /// </param> /// <param name="desiredDay"> /// The desired day of the week whose date will be returneed. /// </param> /// <returns> /// The returned date is on the given day of this week. /// If the given day is before given date, the date for the /// following week's desired day is returned. /// </returns> public static DateTime GetNextDateForDay( DateTime startDate, DayOfWeek desiredDay ) { // (There has to be a better way to do this, perhaps mathematically.) // Traverse this week DateTime nextDate = startDate; while( nextDate.DayOfWeek != desiredDay ) nextDate = nextDate.AddDays( 1D ); return nextDate; } Source: http://angstrey.com/index.php/2009/04/25/finding-the-next-date-for-day-of-week/ A: date.AddDays(7 - (int)date.DayOfWeek) should do it I think. date.DayOfWeek will return an enum value that represents the day (where 0 is Sunday). A: Here's the code: int dayOfWeek = (int) DateTime.Now.DayOfWeek; DateTime nextSunday = DateTime.Now.AddDays(7 - dayOfWeek).Date; Get first the numerical value of the day of the week, in your example: Tuesday = 2 Then subtract it from Sunday, 7 -2 = 5 days to be added to get the next Sunday date. :) A: I use this extension method: public static DateTime Next(this DateTime from, DayOfWeek dayOfWeek) { int start = (int)from.DayOfWeek; int target = (int)dayOfWeek; if (target <= start) target += 7; return from.AddDays(target - start); } A: var date = DateTime.Now; var nextSunday = date.AddDays(7 - (int) date.DayOfWeek); If you need nearest sunday, code little bit different (as if you're on sunday, nearest sunday is today): var nearestSunday = date.AddDays(7 - date.DayOfWeek == DayOfWeek.Sunday ? 7 : date.DayOfWeek); A: DateTime dt=dateTime; do { dt=dt.AddDays(1); } while(dt.DayOfWeek!= DayOfWeek.Sunday); // 'dt' is now the next Sunday Your question isn't clear whether the same date is returned if the date is already a Sunday; I assume no, but change the above to a while loop if I'm wrong. A: Example using recursion private static DateTime GetNextSunday(DateTime dt) { var tomorrow = dt.AddDays(1); if (tomorrow.DayOfWeek != DayOfWeek.Sunday) { GetNextSunday(tomorrow); } return tomorrow; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: Highchart datepicker I am trying to get jquery-ui datepicker to work with highcharts so that a user can select a date an example being A user selects 10th October to 25th October Once the user has selected the dates the highchart should redraw and show the hours for the projects that have done along with the tasks. My chart looks like the following: Chart From the photo currently the highchart shows the hours a user has done for a task against the project “Asda”. At the moment I have the chart simply displays the hours for the current week. What I am trying to do is use the jquery datepicker so that it can display past hours that the user has entered. If the user selects “from 10th October” “to “25th October” the chart should redraw and show the hours and projects for the selected date range. My code follows: Index.html.erb <%= javascript_include_tag 'highcharts', 'exporting' %> <%= render 'projectselect' %> <div class = 'right'> <label for="from">From</label> <input type="text" id="from" name="from" size="15"/> <label for="to">to</label> <input type="text" id="to" name="to" size="15"/> </div> <button id="button">Redraw</button> <div id="container" style="height: 400px"></div> <script> $(document).ready(function() {var chart = new Highcharts.Chart(options);}); onchange: $(function() { var dates = $( "#from, #to" ).datepicker({ defaultDate: "+1w", changeMonth: true, numberOfMonths: 1, onSelect: function( selectedDate ) { var option = this.id == "from" ? "minDate" : "maxDate", instance = $( this ).data( "datepicker" ), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); dates.not( this ).datepicker( "option", option, date ); } }); }); $('#button').click(function() { chart.redraw(); }); var options = { chart: { renderTo: 'container', defaultSeriesType: 'column' }, title: { text: '<%= current_user.username %>', }, subtitle: { text: 'Project Hours' }, xAxis: { categories: [ 'Pre-Sales', 'Project', 'Fault Fixing', 'Support', 'Out Of Hours', 'Sick', 'Toil', 'Leave' ] }, yAxis: { min: 0, title: { text: 'Hours' } }, plotOptions: { series: { stacking: 'normal' } },ip: { formatter: function() { return ''+ this.x +': '+ this.y +' Hours'; } }, credits: { text: '', href: '' }, exporting: { enabled: true, filename: 'Project-Hours' }, plotOptions: { column: { pointPadding: 0.3, borderWidth: 0 } }, series: [ <% @users_projects.each do |users_project| %> <% if !users_project.user.nil? && current_user.full_name == users_project.user.full_name %> <% @data.each do |data| %> <% if data[ :values ] == [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] %> <% else %> <% if data[ :name ] == users_project.project.project_name %> { name: '<%= data[ :name ] %>', data: [ <% data[ :values ].each do |value| %> <%= value %>, <% end %> ] }, <% end %> <% end %> <% end %> <% else %> <% end %> <% end %> ] }; </script> What would be the best way to approach this? A: In onSelect callback of datepickers, you should validate, if both #from and #to are selected (or provide sensible defaults if not) and at the end fire and xhr request to server to get new series of data. onSelect: function( selectedDate ) { var option = this.id == "from" ? "minDate" : "maxDate", instance = $( this ).data( "datepicker" ), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); dates.not( this ).datepicker( "option", option, date ); // validate if we have both dates and get new series from server if ($(dates[0]).datepicker("getDate") && $(dates[1]).datepicker("getDate")) { $.ajax({ type: 'POST', url: '<%= user_projects_path(params[:user_id]) %>', data: {"from": $(dates[0]).datepicker("getDate"), "to" : $(dates[1]).datepicker("getDate") }, success: function(data) { // now we have new series of data to display in graph // we remove the old one, add the new and redraw the chart for(var i=0; i<chart.series.length; i++) { chart.get(chart.series[i].options.id).remove(); } // fiddle with json data from xhr response to form valid series var series = data; chart.addSeries(series, true); // second param says we want to redraw chart } }); } } Controller method under user_projects_path url needs to exists and return JSON formatted series data for given user_id of course. You can filter your series data before returning with params sent by jquery xhr request (from and to). Quick and dirty solution but I hope you got the point...
{ "language": "en", "url": "https://stackoverflow.com/questions/7611406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fill Form Fields From mySQL Search From some very sound guidance from this forum I've put together a php script that allows an administrator, via an html form, to search for member records using the email address as the search criteria and it works fine. The problem I have is populating the first and surname fields in the html fields upon the search being complete. Instead of filling out the relevant form fields, the results appear on a separate web page. I'm sure the answer is really simple, but I've been trying to get this to work over the last couple of days without success. I've posted the php script and html form below. Could someone perhaps take a look at this please and let me know where I'm going wrong. Many thanks PHP Script <?php require("phpfile.php"); // Opens a connection to a MySQL server $connection=mysql_connect ("hostname", $username, $password); if (!$connection) { die('Not connected : ' . mysql_error());} // Set the active MySQL database $db_selected = mysql_select_db($database, $connection); if (!$db_selected) { die ('Can\'t use db : ' . mysql_error()); } $email = $_POST['email']; $result = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'"); while($row = mysql_fetch_array($result)) { echo $row['forename']; echo $row['surname']; echo "<br />"; } ?> HTML Form <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Map!</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <link href="style.css" rel="stylesheet" type="text/css" /> <link href="layout.css" rel="stylesheet" type="text/css" /> <script src="js/gen_validatorv4.js" type="text/javascript"></script> </head> <body> <h1>Member Password Reset </h1> <form name="memberpasswordreset" id="memberpasswordreset" method="post" action="search.php"> <div class="title1"> <h2>Member Details </h2> </div> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="26%" height="25"><strong>Email Address </strong></td> <td width="4%">&nbsp;</td> <td width="70%"><input name="email" type="email" id="email" size="50" /></td> </tr> <tr> <td height="25"><strong>Confirm Email</strong></td> <td>&nbsp;</td> <td><input name="conf_email" type="email" id="conf_email" size="50" /></td> </tr> <tr> <td height="25"><label> <input type="submit" name="Submit" value="search" /> </label></td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>First Name </strong></td> <td>&nbsp;</td> <td><input name="fname" type="text" id="fname" size="30" value="<?php echo $forename; ?>" /> </td> </tr> <tr> <td height="25"><strong>Last Name </strong></td> <td>&nbsp;</td> <td><input name="lname" type="text" id="lname" size="30" value="<?php echo $surname; ?>" /> </td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>Password</strong></td> <td>&nbsp;</td> <td><input name="pass" type="password" id="pass" size="30" /></td> </tr> <tr> <td height="25"><strong>Confirm Password </strong></td> <td>&nbsp;</td> <td><input name="conf_pass" type="password" id="conf_pass" size="30" /></td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>Password Hint </strong></td> <td>&nbsp;</td> <td><input name="hint" type="text" id="hint" size="30" /></td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> </form> <script language="JavaScript" type="text/javascript"> // Code for validating the form var frmvalidator = new Validator("memberpasswordreset"); frmvalidator.addValidation("email","req","Please enter the users email address"); frmvalidator.addValidation("email","email","Please enter a valid email address"); frmvalidator.addValidation("conf_email","eqelmnt=email", "The confirmed email address is not the same as the email address"); </script> </body> </html> A: Not sure If I understand... Do you want to auto-fill the names after the email? If so, you have to use AJAX to call a PHP page. With jQuery you can do that easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: weird permission issue while deleting android bookmarks I'm facing some permission issue while deleting android bookmarks: java.lang.SecurityException: Permission Denial: writing com.android.browser.provider.BrowserProvider2 uri content://browser/bookmarks from pid=8045, uid=10028 requires com.android.browser.permission.WRITE_HISTORY_BOOKMARKS The problem is, I've already set that permission in manifest: <uses-permission android:name="com.android.broswer.permission.WRITE_HISTORY_BOOKMARKS" /> A: if this is a copy paste of your permission, you wrote broswer and not browser
{ "language": "en", "url": "https://stackoverflow.com/questions/7611414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I run POCO C++ server pages? I'm a beginner in C++ server pages. I have tried C++ Server Pages by micronovae, but couldnt connect ODBC it used to give link error "undefined reference to SQLAllocHandle@12", I could not resolve it. Similar to micronovae,POCO also provides C++ Server Pages. so thought of try it. I tried one sample from http://pocoproject.org/docs/PageCompilerUserGuide.html#0 . What I did is, firstly created a file called TimeHandler.html along with following contents inside it: <%@ page class="TimeHandler" %> <%! #include "Poco/DateTime.h" #include "Poco/DateTimeFormatter.h" #include "Poco/DateTimeFormat.h" using Poco::DateTime; using Poco::DateTimeFormatter; using Poco::DateTimeFormat; %> <% DateTime now; std::string dt(DateTimeFormatter::format(now, DateTimeFormat::SORTABLE_FORMAT)); %> <html> <head> <title>Time Sample</title> </head> <body> <h1>Time Sample</h1> <p><%= dt %></p> </body> </html> Then, I used the commandline Pagecompiler tool, i.e., CPSPCD from command prompt, and it generated following two files,.. 1) TimeHandler.cpp #include "TimeHandler.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/HTMLForm.h" #line 2 "C:\\Users\\Admin\\Desktop\\data structures\\vinz\\TimeHandler.html" #include "Poco/DateTime.h" #include "Poco/DateTimeFormatter.h" #include "Poco/DateTimeFormat.h" using Poco::DateTime; using Poco::DateTimeFormatter; using Poco::DateTimeFormat; void TimeHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) { response.setChunkedTransferEncoding(true); response.setContentType("text/html"); Poco::Net::HTMLForm form(request, request.stream()); std::ostream& responseStream = response.send(); responseStream << ""; responseStream << "\n"; responseStream << ""; responseStream << "\n"; responseStream << "\n"; responseStream << ""; #line 13 "C:\\Users\\Admin\\Desktop\\data structures\\vinz\\TimeHandler.html" DateTime now; std::string dt(DateTimeFormatter::format(now, DateTimeFormat::SORTABLE_FORMAT)); responseStream << "\n"; responseStream << "<html>\n"; responseStream << "<head>\n"; responseStream << "<title>Time Sample</title>\n"; responseStream << "</head>\n"; responseStream << "<body>\n"; responseStream << "<h1>Time Sample</h1>\n"; responseStream << "<p>"; #line 23 "C:\\Users\\Admin\\Desktop\\data structures\\vinz\\TimeHandler.html" responseStream << ( dt ); responseStream << "</p>\n"; responseStream << "</body>\n"; responseStream << "</html>"; } 2) TimeHandler.h #ifndef TimeHandler_INCLUDED #define TimeHandler_INCLUDED #include "Poco/Net/HTTPRequestHandler.h" class TimeHandler: public Poco::Net::HTTPRequestHandler { public: void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response); }; #endif // TimeHandler_INCLUDED And then I created new project in VS 2010 and added these two files and compiled. There were few issues, but later I updated environment variables and it went on fine. But there is one last error, "....Unresolved symbol _main....". There was no main inside it.. so how do I run this program?? if not this program, atleast would someone give an overview as to how to embed C++ code inside html, compile and run it..! A: The samples you show only create the individual page (handler) implementation. You need to add an actual HTTPServer to serve that page. See: http://pocoproject.org/docs/Poco.Net.HTTPServer.html There is a sample in the sources download under poco-1.4.2p1.zip\poco-1.4.2p1\Net\samples\HTTPTimeServer You should be able to get something working from there
{ "language": "en", "url": "https://stackoverflow.com/questions/7611416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to pass PHP variable value to jquery function? i have this JQuery Script in Wordpress /js folder and i need to change some values that i store in the Database. $( "#slider-range2" ).slider({ range: true, min: 18, max: 90, values: [ 35, 50 ], slide: function( event, ui ) { $( "#amount2" ).val( ui.values[ 0 ] + "-" + ui.values[ 1 ] ); } }); $( "#amount2" ).val( $( "#slider-range2" ).slider( "values", 0 ) + "-" + $( "#slider-range2" ).slider( "values", 1 ) ); The Jquery documentation is not clear to me. Values that i need to change are [35 , 50]. These values ​​are stored in the database. How can i do this from the js file? How can i pass a PHP variable value to jquery function? Thanks. A: Assuming you want to keep the external js file and not embed it into your php script, have php write out two global js vars, and modify the js file to use those instead. e.g. in php: echo "<script>var val1 = $var1; var val2 = $var2;</script>"; and in your js file: values: [val1, val2] But if you can change your js file to be a php file instead, you can do something like: <?php header('Content-type: text/javascript'); ?> ... // your regular js code here values: <?php echo $var1 ?> , <?php echo $var2 ?> ... Now, you can use on your page: <script type="text/javascript" src="yourfile.js.php"> A: I'd say you just do it like this: $( "#slider-range2" ).slider({ range: true, min: 18, max: 90, values: [ <?php echo $value1; ?>, <?php echo $value2; ?> ], slide: function( event, ui ) { $( "#amount2" ).val( ui.values[ 0 ] + "-" + ui.values[ 1 ] ); } }); where of course $value1 and $value2 are the values you get from the database. -edit- or what the other guy said, you can use a php for loop to make the size of your array dynamic that way :) A: PHP code runs on the server and jQuery code runs in the browser, so you can't directly pass PHP variables to jQuery functions because you can't directly call jQuery functions from PHP code. What you need to do is make the PHP code generate JavaScript code that, when it runs later in the browser, will set some JavaScript variables to the values you want. For example, you could make the PHP code generate a <script> element in the page's header that contains JavaScript assignment statements, and then modify your .js file so that instead of the numbers 35 and 50, it refers to those variables. You can also put PHP code in your .js file itself, as other answers have suggested, but only if it's actually a PHP script rather than a static file. My recommendation would be to keep the majority of the JavaScript code in static files (so that browsers can cache them) and have the PHP just generate assignments for a few global variables that the rest of the scripts can refer to. A: Well you could make an ajax request to the server before you define your slider. eg. var myValues = function(){ //do ajax call to php script that returns values return value}; $( "#slider-range2" ).slider({ range: true, min: 18, max: 90, values: myValues(), slide: function( event, ui ) { $( "#amount2" ).val( ui.values[ 0 ] + "-" + ui.values[ 1 ] ); } }); $( "#amount2" ).val( $( "#slider-range2" ).slider( "values", 0 ) + "-" + $( "#slider-range2" ).slider( "values", 1 ) ); A: Just echo it out, like this. $( "#slider-range2" ).slider({ range: true, min: 18, max: 90, values: <?php echo $your_variable ?> , slide: function( event, ui ) { $( "#amount2" ).val( ui.values[ 0 ] + "-" + ui.values[ 1 ] ); } }); A: It depends on the value. If it's a simple numeric value, you can just echo it. If it's complex or a string, you might echo it in JSON format via json_encode (since JSON is a subset of JavaScript literal syntax), since that will handle escaping and such for you. Note in both cases that the PHP is happening on the server as the page request is satisfied, and JavaScript is using it later on the client-side. A: One of my favorite tricks is naming your javascript file somename.js.php and then sending a javascript header: Header("content-type: application/x-javascript"); Now, you can use full php functionality (including db calls) inside your javascript. However, you'll want to ensure that you're properly caching your file with the server, so it's not downloaded on every page. Something like: header("Expires: Sat, 26 Jul 2012 05:00:00 GMT") As a rule of thumb, I generally keep any changing JS variables in the main php file, and pass them to functions declared in an external JS file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why should I use Object instead of DataSet as the return type of my WCF Method? I heard some people saying Returning DataSet as a return type of your WCF method is not a good practice. What are the problems if I use DataSet as return type of my method? What are the advantages of using a List of Objects instead of DataSet? Sending a List of State object (ID,StateCode,StateName) or DataSet? I was told by a friend that having DataSet as return type has an advantage. If tomorrow client is saying (assume I published the service and some outside customers are using that), my client is saying I want some more information about the object (ex: Need a "Notes" field about the State), I don't need to change the signature of my contract. I just add the notes to my dataset. This will not break any existing contract. I heard that there is performance issues if I use dataset? How big is that impact? What are the other issues? Why people write DataSet is evil? Trying to evolve as a good developer by switching to good coding practices. A: Dataset leaks platform details. Dataset is microsoft implementation and when you expose that over a service, then clients who use the same platform as the data being exposed can only consume the service. That basically makes your service consumable only on microsoft platforms which against the whole point of a service. Other thing is that dataset when serialized contains huge amoount of unrelated data for a client, like datarelations etc.. And regarding your "Notes" example, Boundaries are supposed to be explicit when you define a service. So the outside world has to know what is the type of data that you are sending across the service and its structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Function Returns "No Solution" Instead Of "Nothing" I have a standard datatype representing formulae of predicate logic. A function representing a natural deduction elimination rule for disjunction might look like: d_el p q = if p =: (Dis r s) && q =: (Neg r) then Just s else if q =: (Dis r s) && p =: (Neg r) then Just s else Nothing where r,s free x =: y = (x =:= y) == success Instead of evaluating to Nothing when unification fails, the function returns no solutions in PACKS: logic> d_el (Dis Bot Top) (Not Bot) Result: Just Top More Solutions? [Y(es)/n(o)/a(ll)] n logic> d_el (Dis Bot Top) (Not Top) No more solutions. What am I missing, and why doesn't el evaluate to Nothing when unification fails? A: It seems that this is not the best way to use equational constraints. When a =:= b fails then complete function clause fails also. E.g.: xx x = if (x =:= 5) == success then 1 else x xx x = 3 Evaluating xx 7 results in 3 (not 7) because 7 =:= 5 completely terminates first clause of the xx function. I think the code should look like this: d_el p q = case (p,q) of (Dis a s, Neg b) -> if a == b then Just s else Nothing (Neg a, Dis b s) -> if a == b then Just s else Nothing _ -> Nothing
{ "language": "en", "url": "https://stackoverflow.com/questions/7611426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: JNI build with MinGW I have a problem with building a dll with gcc (mingw). From this site I read how to do it : http://www.mingw.org/node/41 and the problem is that the file jni.h cannot be found unless it is in current folder where is the java file, the header c file and c file. So my question is how to compile the source file *.c with gcc and to include the path to the file jni.h and jni_md.h with no error occurred? Thanks in advance. A: You can use -I switch to locate jni.h file. For more information read this
{ "language": "en", "url": "https://stackoverflow.com/questions/7611434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML performance (Asp.Net) I have a large HTML file (In ASP.NET) that has several smaller ... tags to control content based on users at the company I work for. In my current setup I load the entire page, but many of the panels are hidden until the user clicks on a link.button and then I have some JQuery that displays or hides it. The site seems fine in reference to performance, but as other departments add content, I worry about the HTML file itself growing to large. Is there a best practice to this? Almost all of the hidden panels are available to each user, its just a matter if they click not he link to show it. Beloe are a few ideas thats crossed my mind and would love some feedback from you experts out there. 1.) Should I store this type of content in a DB and have it retrieved every time a user click on the link (This seems like it would be easier to read/maintain code wise, but I worry about performance) 2.) Should I have each separate ... content loaded in a separate html file and loaded via java-script. 3.) Keep what I have? Thanks again for your ideas. Jonathan A: A few thoughts come to mind. Does all the information need to be on the same page? If you can break the content up into multiple pages, I'd suggest you start there. Assuming you need to keep everything on one page, I agree with rick regarding a lazy-loading approach. Your HTML output will be just a DIV, and some jQuery to download and populate the content via AJAX. You might have that content download when the user clicks to see the hidden content, or just have the hidden content download in the background on page load. Either way will yield performance improvements. The decision to store the content in a DB vs. separate HTML files is separate from the performance issue. The database will likely not be your bottleneck, but of course I'm just guessing here not knowing much about your application. Use the DB if it is more convenient, leads to a more stable architecture, etc. But in my opinion it's not a necessity here. A: If the child content divs/html/controls are small, I recommend lazy loading them with jQuery and AJAX. A: There's a lot that can go into a decision like this. I would say though, if you're concerned about the size, store it somewhere (database or other) and load it as necessary through JavaScript: jQuery or whatever your preference. Another thing to keep in mind is: It may not end up being much of an issue, you could be over thinking it, and you may end up doing a lot of work for nothing. If you store that extra user data externally already, it can be adjusted down the road to load like above. If this is an internal site, size could be negligible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: EXC_BAD_ACCESS in protocol? I am getting EXC_BAD_ACCESS at the following line, what can be possbile reason, can any one explain if([self.delegate respondsToSelector:@selector(dealInfo:imageDidDownload:indexPath:)])//Here is EXC_BAD_ACCESS [self.delegate dealInfo:self imageDidDownload:thumbImage indexPath:self.indexPath]; I have done deal.delegate=self;, and deal is declared in delegate method of UITableView cellForRowAtIndexPath something like below DealInfo *deal = [nearByDeals objectAtIndex:(section - 1)]; deal.delegate = self; deal.indexPath = indexPath; HELP! A: EXC_BAD_ACCESS usually means you're trying to access a released object. In this case, delegate is probably released before you call respondsToSelector: on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C#, check whether integer array has negative numbers in it I have a array int[] numArray . I want to know is there any straight forward way to just check whether array has negative numbers in it ? If there is no direct method even linq will do . I am bit new to linq . Can anyone suggest ? A: If you're open to using LINQ: var containsNegatives = numArray.Any(n => n < 0); Or, if you want to do it the "old fashioned" way...you just have to loop: var containsNegatives = false; foreach(var n in numArray) { if(n < 0) { containsNegatives = true; break; } } And if you really want to get fancy, you could turn that into an Extension method: public static class EnumerableExtensions { public static bool ContainsNegatives(this IEnumerable<int> numbers) { foreach(n in numbers) { if(n < 0) return true; } return false; } } And call it from your code like: var containsNegatives = numArray.ContainsNegatives(); A: You could use Any: bool containsNegative = numArray.Any(i => i < 0) Or bool containsNegative = numArray.Min() < 0; EDIT int[] negativeNumbers = numArray.Where(i => i < 0).ToArray(); A: var negativeExist = numArray.Any(a => a < 0); A: You can use Array.Find(T) method to perform this task. public static T Find<T>( T[] array, Predicate<T> match ) For example, using System; using System.Drawing; public class Example { public static void Main() { // Create an array of five Point structures. Point[] points = { new Point(100, 200), new Point(150, 250), new Point(250, 375), new Point(275, 395), new Point(295, 450) }; // To find the first Point structure for which X times Y // is greater than 100000, pass the array and a delegate // that represents the ProductGT10 method to the static // Find method of the Array class. Point first = Array.Find(points, ProductGT10); // Note that you do not need to create the delegate // explicitly, or to specify the type parameter of the // generic method, because the C# compiler has enough // context to determine that information for you. // Display the first structure found. Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y); } // This method implements the test condition for the Find // method. private static bool ProductGT10(Point p) { if (p.X * p.Y > 100000) { return true; } else { return false; } } } /* This code example produces the following output: Found: X = 275, Y = 395 */ A: Traditional: foreach (int number in numArray) { if (number < 0) return true; } return false; With LINQ: bool result = numArray.Any(x => x < 0); A: A bit twidling version would be public static bool AnyNegative(int[] arr){ const long firstBit = 2147483648; var res = false; for (var i = 0; i < arr.Length && !res; i++) res = (arr[i] & firstBit) == firstBit; return res; } you can the call it like this> int arr = {...} if(arr.AnyNegative()){ //do stuf if there's any negative numbers } of course this is just an obfuscated version of public static bool AnyNegative(int[] arr){ var res = false; for (var i = 0; i < arr.Length && !res; i++) res = arr[i] < 0; return res; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AppMobi background issues basically I am trying to set a background color (or image). I am writing in HTML CSS and JQuery Mobile. I'm trying to create a basic AppMobi app but I don't seem to be able to change my background in the following example: <div data-role="page" id="page"> <div data-role="header" data-theme="c"> <h1>Page One</h1> </div> <div data-role="content" data-theme="c"> <ul data-role="listview" data-theme="b"> <li><a href="#page2">Page Two</a></li> <li><a href="#page3">Page Three</a></li> <li><a href="#page4">Page Four</a></li> <li><a href="#page3" data-role="button" data-icon="delete">Delete</a></li> </ul> </div> <div data-role="footer" style="position:fixed; bottom:0;" data-theme="c"> <h4>Page Footer</h4> </div> </div> I have tried to both change the background in HTML and CSS, but I don't seem to be able to change the background color page 1 (example). Page 1 includes 4 buttons, and a "sticky footer". The buttons shown on top of screen, but the content between buttons or lists and footer will not change color. I tried writing HTML or CSS in Header and also inline. How would I be able to change the background color of this 'div' chunk? Thanx in advance A: Your issue isn't related to AppMobi, but JQuery Mobile in general. The way JQuery Mobile works is it loads the content, then "processes" it and applies styles. What's happening is that JQuery Mobile is overriding your default CSS styles. Open up the JQuery Mobile CSS file and change it there. A: In standard sample apps, here is the block of code in index.html that sets your background. /* Set up the page with a default background image */ body { background-color:#fff; color:#000; font-family:Arial; font-size:48pt; margin:0px;padding:0px; background-image:url('images/background.jpg'); } Which you can see just sets the image titled background.jpg, located in the images directory. You can either edit that background image, get a new one and point to that, or put in some nifty webkit code or something: (head tag of index.html) <style type="text/css"> * { -webkit-user-select:none; -webkit-tap-highlight-color:rgba(255, 255, 255, 8); } input, textarea { -webkit-user-select:text; } body { font-family:Arial;font-size:24pt;font-weight:bold; background: -webkit-gradient(radial, 50% 60%, 0, 53% 50%, 50, from(rgba(255,255,255,0)), color-stop(99%,rgba(255,255,255,.15)), to(rgba(255,255,255,0))), -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 100, from(rgba(255,255,255,0)), color-stop(99%,rgba(255,255,255,.1)), to(rgba(255,255,255,0))), -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 200, from(rgba(255,255,255,0)), color-stop(99%,rgba(255,255,255,.1)), to(rgba(255,255,255,0))), -webkit-gradient(radial, 40% 50%, 0, 40% 55%, 25, from(rgba(255,255,255,0)), color-stop(99%,rgba(255,255,255,.1)), to(rgba(255,255,255,0))), -webkit-gradient(linear, 0% 0%, 0% 100%, from(#8D4212), to(#28580C), color-stop(.5,#DA881B)); background-size: 400px 400px, 470px 470px, 600px 600px, 300px 300px, 100% 100%; background-color: #28580C; } </style> So you should be able to give your Page 1 div an id, and just apply either the image or whatever else you want to that div id.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: replacing a single line of a .txt file using php I am trying to use a php call through AJAX to replace a single line of a .txt file, in which I store user-specific information. The problem is that if I use fwrite once getting to the correct line, it leaves any previous information which is longer than the replacement information untouched at the end. Is there an easy way to clear a single line in a .txt file with php that I can call first? Example of what is happening - let's say I'm storing favorite composer, and a user has "Beethoven" in their .txt file, and want's to change it to "Mozart", when I used fwrite over "Beethoven" with "Mozart", I am getting "Mozartven" as the new line. I am using "r+" in the fopen call, as I only want to replace a single line at a time. A: If this configuration data doesn't need to be made available to non-PHP apps, consider using var_export() instead. It's basically var_dump/print_r, but outputs the variable as parseable PHP code. This'd reduce your code to: include('config.php'); $CONFIG['musician'] = 'Mozart'; file_put_contents('config.php', '<?php $CONFIG = ' . var_export($CONFIG, true)); A: This is a code I've wrote some time ago to delete line from the file, it have to be modified. Also, it will work correctly if the new line is shorter than the old one, for longer lines heavy modification will be required. The key is the second while loop, in which all contents of the file after the change is being rewritten in the correct position in the file. <?php $size = filesize('test.txt'); $file = fopen('test.txt', 'r+'); $lineToDelete = 3; $counter = 1; while ($counter < $lineToDelete) { fgets($file); // skip $counter++; } $position = ftell($file); $lineToRemove = fgets($file); $bufferSize = strlen($lineToRemove); while ($newLine = fread($file, $bufferSize)) { fseek($file, $position, SEEK_SET); fwrite($file, $newLine); $position = ftell($file); fseek($file, $bufferSize, SEEK_CUR); } ftruncate($file, $size - $bufferSize); echo 'Done'; fclose($file); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7611457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between two methods of creating of 2d array What is the difference between two arrays definitions? Are they realized different in memory? int var = 5; int (*p4)[2] = new int [var][2]; // first 2d array int** p5 = new int*[var]; // second 2d array for(int i = 0; i < var; ++i){ p5[i] = new int[2]; } A: Yes, they're very different. The first is really a single array; the second is actually var+1 arrays, potentially scattered all over your RAM. var arrays hold the data, and one holds pointers to the var data arrays. A: The first is an ordinary, fully contiguous array, the second is also known as jagged array or lliffe vector and can e.g. be used to represent triangular structures.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to check if relationship exists - Many to many relationship I need your help to figure out how to make a query. My idea was to build a credit system to reward users. The administrator enters the description of credits (e.g., user is subscribed to the newsletter, he had post at least 10 comments...). I have 3 tables: * *users (id and name), *rewards (id and description), *rewards_users (id_reward, id_user). I would pull out a summary html table whose rows are formed by the user's name and a Y or an N depending on whether there is a relationship between the user and the reward. A: use the following query to show all of the rewards for a specific user SELECT r.description, CASE WHEN ru.user_id IS NULL THEN 'N' ELSE 'Y' END awarded FROM rewards r LEFT JOIN rewards_users ru ON r.reward_id=ru.reward_id AND ru.user_id = 1 and use it as a sub query to get the users details too e.g: SELECT u.user_id, u.user_name, ua.award, ua.awarded FROM users u, ( SELECT r.description, CASE WHEN ru.user_id IS NULL THEN 'N' ELSE 'Y' END awarded FROM rewards r LEFT JOIN rewards_users ru ON r.reward_id=ru.reward_id AND ru.user_id = u.user_id ) ua WHERE u.userid=1 Note: not tested. A: Sounds to me like you need a LEFT JOIN between your users table and the rewards_users table and then to handle instances of null rewards_id: select u.id as users_id, u.name as users_name, case when ur.rewards_id is null then 'N' else 'Y' end as hasRewards from users u left join users_rewards ur on u.id = ur.users_id;
{ "language": "en", "url": "https://stackoverflow.com/questions/7611471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Removing trailing empty values from an array in ruby How to remove the trailing empty and nil values from an array in Ruby. The "Compact" function is not fullfil my requirement. It is removing all the 'nil' values from an array. But I want to remove the trailing empty and nil values alone. Please give me any suggestion on this.. A: ['a', "", nil].compact.reject(&:empty?) => ["a"] A: This will do it and should be fine if you only have a couple trailing nils and empty strings: a.pop while a.last.to_s.empty? For example: >> a = ["where", "is", nil, "pancakes", nil, "house?", nil, '', nil, nil] => ["where", "is", nil, "pancakes", nil, "house?", nil, "", nil, nil] >> a.pop while a.last.to_s.empty? => nil >> a => ["where", "is", nil, "pancakes", nil, "house?"] The .to_s.empty? bit is just a quick'n'dirty way to cast nil to an empty string so that both nil and '' can be handled with a single condition. Another approach is to scan the array backwards for the first thing you don't want to cut off: n = a.length.downto(0).find { |i| !a[i].nil? && !a[i].empty? } a.slice!(n + 1, a.length - n - 1) if(n && n != a.length - 1) For example: >> a = ["where", "is", nil, "pancakes", nil, "house?", nil, '', nil, nil] => ["where", "is", nil, "pancakes", nil, "house?", nil, "", nil, nil] >> n = a.length.downto(0).find { |i| !a[i].nil? && !a[i].empty? } => 5 >> a.slice!(n + 1, a.length - n - 1) if(n && n != a.length - 1) => [nil, "", nil, nil] >> a => ["where", "is", nil, "pancakes", nil, "house?"]
{ "language": "en", "url": "https://stackoverflow.com/questions/7611474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which date time object is the smartest that will take leap years etc. into consideration? If I do this: DateTime now = DateTime.Now; And then: DateTime dt = new DateTime(now.Year, now.Month, now.Year, ..).AddDays(1); It will take into consideration leap years and anything else that might be an issue with dates :) I can't recall but I know .net 4 or 3.5 has new date time objects. A: To save Jon Skeet from having to advertise his own project: * *Noda Time Noda Time is a .NET library designed to simplify the correct handling of dates and times in the .NET environment. It is based on Joda Time, the industry standard date and time handling library for Java A: The DateTime.AddYears() method does consider leap years.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CAST to package type Is it possible to CAST to a type within a package? For example: CAST(v_variable AS Mypackage.type) I know CAST states the ability to cast to built-in types but I was wondering if this was possible. I'm interested in this approach because I prefer keeping my utilities in one package instead of having a separate TYPE object. Thanks! A: No. CAST() is a SQL function so we can only use it with SQL types. This means we cannot use it with types we have declared in a PL/SQL package.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MSI installer cancel not working I have an MSI installer (set-up project) which actually calls a Windows Forms exe through system.diagnostic.process. This form actually takes input from the user to restore a .bak file in sql server. But if any exception occur, I am not able to cancel the setup. Even after clicking the cancel button of installer the installation roll-back will not start. Please suggest how to handle it. A: Create new project that calls your windows forms exe and add installer class to it, or just add installer class to your windows forms exe (you'll have to change it's output type and modify it a little, so, for example, there is no Main() method, or startup object is not set, and your form is called from inside of install action) Installer class should look like this: [RunInstaller(true)] public partial class Installer1 : System.Configuration.Install.Installer { public Installer1() { InitializeComponent(); } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Install(IDictionary stateSaver) { base.Install(stateSaver); // Do your magic here, call your form, do your thing... } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Commit(IDictionary savedState) { base.Commit(savedState); } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Rollback(IDictionary savedState) { // if something goes wrong, it's here you correct it and rollback the system to its previous state and undo what you already changed base.Rollback(savedState); } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Uninstall(IDictionary savedState) { // Here you undo changes when you cancel base.Uninstall(savedState); } } When you have your installer project ready, go to your setup project Custom Action and add primary output of your installer project to its install, commit, rollback and uninstall "folders". Another usefull thing is getting the directory in which your app is being installed and passing its path to your installer class. you do this setting CustomActionData property of your custom action to /INSTALLDIR="[TARGETDIR]\" and in your installer class you get the directory using: Context.Parameters["INSTALLDIR"] EDIT: And installation will be canceled if an exception is thrown from within the Install method. As far as I know it's the only way to "cancel" your installation in the middle. You have to create an exception and throw it., for example like this: If (SomethingWentWrong) throw new Exception("My exception description") Of course, if the exception was thrown by something else (I mean, not willingly "created" by you) the rollback shoud also start. But if you do some custom changes, it has to be thrown from within the custom action's installer's install method. Sorry if I was a bit too detailed but I got through my own set of troubles over this so I'll be happy if I can help someone to avoid it :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7611494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android, setSelected() and state_selected I'm having trouble with View.setSelected(). Views are flagged as selected -- TextViews, for example, change their font color -- but my background selectors don't seem to register the change. Example selector: <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@android:color/transparent" /> <item android:state_selected="true"> <shape android:shape="rectangle"> <solid android:color="#ff8600" /> </shape> </item> </selector> I'm not even sure which kind of context information would be useful. The views are children of a LinearLayout, and I'm programatically setting the selected state inside a touch event. As I said, it does seem to work, since the font color goes from white to gray, but the background stays the same. Edit: I checked for silly mistakes before posting :P. The answer is not "add the android:background attribute". A: not only the selected state order is important, even the order of all states is important. In my case, I added state_pressed as first and my state_selected doesn´t work. So I changed the order like this, and then it worked: <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_selected="false" android:drawable="@drawable/chooser_normal"></item> <item android:state_selected="true" android:drawable="@drawable/chooser_pressed"></item> <item android:state_pressed="true" android:drawable="@drawable/chooser_pressed"></item> <item android:state_pressed="false" android:drawable="@drawable/chooser_normal"></item> </selector> EDIT I faced now also the problem, if I press the button, it will be in the selected-state but not in pressed-state. So, the solution must be, to order the states like this and additional, it´s a good practise to add a default button look: First, set the selected state and after this, set the same as pressed state alternately. (For now, stackoverflow isn´t showing my edit completely, don´t know why, just be patient please). A: The order of items matters in selector xmls, the default item should always be at the bottom in the items list. A: It's not obvious why, but I think this might work (notice the addition of state_selected="false"): <item android:state_selected="false" android:drawable="@android:color/transparent" /> <item android:state_selected="true"> <shape android:shape="rectangle"> <solid android:color="#ff8600" /> </shape> </item> I hope that's helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Weaving the same aspect into multiple jars I've been having problems weaving this project correctly with AspectJ (ajc). Here's the situation : I'm using a benchmarking library called DaCapo Benchmarks, and in it I'm trying to intercept all calls to Iterator.HasNext() and Next() [academic research]. This seems to be working in a vacuum, however DaCapo works in a way such that it's own jar contains other jars which it extracts according to which benchmark I want to run along with it's dependencies and runs it. I want to intercept all HasNext()s and Next()s with the same aspect so my total is tracked across all the jar files instead of in each individual one. I hope I'm coming across as clear enough. I'm fully available to answer any questions you might have in order to be able to help me through this weird problem. P.S. I have the weird feeling it's not actually doable, but a test in eclipse with AJDT (I'm using raw aspectj with ajc for the DaCapo Benchmarks weaving) hints at the possibility. A: I know it is too late but may help someone else . . Whatever i understood from your question is you want to wave same aspect in multiple jars . So there are 2 ways * *if you are using eclipse : Then create aspect project and go to its properties > click on aspect build option at left panel >select inpath tab at right panel > now click on add external jars > add the jars you want to wave the aspect into >click on OK again go to its properties > click on aspect build option at left panel >select Output jar tab at right panel >and give the name for new jar you want to create . .>click ok . create and write your aspect and build or clean your project . It will generate The jar in root directory of project by the name you have given in the "output jar" and this jar will have all the jars you have given in inpath jars with aspect waved . . Thats it . . * *If you are using command propmt then : Write your aspect for intercepting mehtods you want to .> now fire following command on command prompt : ajc -inpath myJar1.jar -inpath myJar2.jar myAspect.java -outjar MyOutputJar.jar thats it it will generate final jar with all jar you mentioined in inpath . . You can use as many -inpath as many jars you want to wave code into . For any dependency error, give required dependency jars in classpath. A: If you are using load-time weaving, it is unlikely that this is possible. There is a circularity problem. You need to weave the JDK, but the weaver needs the JDK to load itself and so many parts of the JDK cannot be woven using LTW. So, you will need to go with compile time weaving. Something like this will work: ajc -inpath rt.jar -outjar woven_rt.jar *.aj I'm not sure if this is the problem you are having, but it might fix things.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is eval/alarm is executing? I'm writing a quick script to test the failures and interpreted traffic of a load balancer. I want it to keep trying to make connections after it can't connect to one host or another. My current script doesn't look like it's executing the eval block in the mkcnct sub, and I can't figure out why. Can anyone spot what I'm doing wrong? #!/usr/bin/perl use strict; use Net::HTTP; use Getopt::Std; my %opts; getopts('ht:',\%opts); my @hostlist ("www.foo.com","www1.foo.com","www2.foo.com"); my $timeout; if ($opts{t} =~ /\d+/) { $timeout = $opts{t} + time(); } else { $timeout = 3600 + time(); } while ($timeout < time()) { foreach my $host (@hostlist) { my $cnct = mkcnct($host); if ($cnct) { mkreq($cnct) }; } } sub mkreq { my $cnct = shift; my $time = gettime(); my $out; $cnct->write_request(GET => "/index.html"); ($out->{code},$out->{message},%{$out->{headers}}) = $cnct->read_response_headers; printf "%s\t%s - Size %d\tLast modified %s\n", $time, $out->{message}, $out->{headers}{'Content-Length'}, $out->{headers}{'Last-Modified'}; $out = ""; $cnct->write_request(GET => "/pki/ca.crl"); ($out->{code},$out->{message},%{$out->{headers}}) = $cnct->read_response_headers; printf "%s\t%s - Size %d\tLast modified %s\n", $time, $out->{message}, $out->{headers}{'Content-Length'}, $out->{headers}{'Last-Modified'}; } sub mkcnct { my $host = shift; my $time = gettime(); my $cnct; eval{ local $SIG{ALRM} = sub { print "$time\tCannot connect to $host\n"}; alarm(2); $cnct = Net::HTTP->new(Host => $host); alarm(0); }; alarm(0); return($cnct); } sub gettime { my @time = localtime(time); my $out; $out = sprintf "%d\/%d\/%d %d:%d", ($time[4] + 1), $time[3], ($time[5] % 100 ), $time[2], $time[1]; return($out); } A: Try replacing return($cnct); with return $cnct; in mkcnct. You might want to revue the docs on returning scalars and lists
{ "language": "en", "url": "https://stackoverflow.com/questions/7611509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is Eclipse python autocomplete adding the self parameter? I recently started to use PyDev and the method autocomplete seems to be stupid: I select the method name in the dropdown list, click enter and it completes the line adding the self parameter, but in Python you are not supposed to specify the self parameter when you call the methods!? A: If you are writing a new method in a Class, it does this. But not if you have previously decorated with for example @staticmethod, this is what gets autocompleted for me in PyDev: def normal_method(): #nothing gets autoinserted pass class Foo: def instance_method(self): #self gets autoinserted pass @staticmethod def static_method(): # nothing is inserted pass @classmethod def class_method(cls): #cls is autoinserted pass Are you sure that you're not in a class when this happens? If you are, then I think it is a reasonable behavior, if not, PyDev is bugging out for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I change the background of a selected li in jquery? I have an unordered list with a bunch of list items. I am setting the background of the selected <li> in its click: $(this).animate({ backgroundColor: '#0000FF' }, 'fast'); When I click another <li>, I want to change its backgroundColor property, but I want the rest of the <li>s to default back to another color. This way, it looks like I am changing the selected state. A: You could simply do the following: $(this).siblings("li").css("backgroundColor", ""); Example on jsfiddle A: $('ul li').click(function() { $(this).animate({backgroundColor:"#0000ff"},'fast') .siblings().animate({backgroundColor:"#000000"},'fast'); // or whatever other color you want }); A: I would use a mixe of classes and CSS transitions: $('li').click(function(){) $('li.active').removeClass('active'); $(this).addClass('active'); }) li{background:#fff; -webkit-transition:all 0.25s linear; -moz-transition:all 0.25s linear;} li.active{background:#00f;} A: $('li').each.click(function(){ $(this).css("backgroundColor", ""); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7611520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: maven tomcat deploy plugin so that no rebuild is done I use jenkins to build my gwt app, now I want to run a tomcat:deploy on that built project so that it can deploy the built war to tomcat. Problem is it insists on doing a package beforehand even though the package was just done. This causes a gwt recompile - this takes a Very long time. Is there a way I can invoke a deploy to tomcat with maven that will simply deploy an already existing war? A: You can use deploy-only goal, which won't invoke the package build lifecycle. A: Mre generally, check out the list of Maven Tomcat Plugin Goals Doing a sequence of mvn tomcat:undeploy mvn tomcat:deploy-only is essentially a "redeploy without building" which you sometimes want to do to see what happens at startup. Although if you really just want to see the webapp start up, there's mvn tomcat:reload
{ "language": "en", "url": "https://stackoverflow.com/questions/7611523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android media player(android.media.MediaPlayer) two music concurrently Before open my application I played some of the music from default music player. With that background music I opened my application with the mediaplayer (android.media.MediaPlayer) to play the mp3 available in assets. The default doesn't stop the music and I am getting two music concurrently from the device. How do I stop or pause music of the default music player whenever my app started playing the music? A: I think thats impossible. The default music player is a different app and out of your control. android does not allow controlling other app features from your app. A: I had the same problem. I was trying to stop the background music of the default music player (if it is playing) when my VoIP SIP application receives an incoming call. I came up with: AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE); am.setStreamMute(AudioManager.STREAM_MUSIC, true); This does not stop or pause the music, but it make the music stream silent. Do not forget to unmute it later. This solution works well only if your second sound does not use the same stream.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Integrating CLI PHP with CakePHP I have a nice functioning CakePHP 1.3.11 site and I need a scheduled maintenance CLI script to run, so I'm writing it in PHP. Is there any way to make a cake-friendly script? Ideally I could use Cake's functions and Cake's Database models, the CLI requires database access and not much else however. I would ideally like to include my CLI code in a controller and the datasource in a model so I can call the function like any other Cake function, but only from the CLI as a sheduled task. Searching for CakePHP CLI mostly brings results about CakeBake and cron jobs; this article sounded very helpful but it's for an old version of cake and requires a modified version of index.php. I'm no longer sure how to change the file to make it work in the new version of cakePHP. I'm on Windows if it matters, but I have complete access to the server. I'm currently planning to schedule a simple cmd "php run.php" style script. A: Using CakePHP's shells, you should be able to access all of your CakePHP app's models and controllers. As an example, I've set up a simple model, controller and shell script: /app/models/post.php <?php class Post extends AppModel { var $useTable = false; } ?> /app/controllers/posts_controller.php <?php class PostsController extends AppController { var $name = 'Posts'; var $components = array('Security'); function index() { return 'Index action'; } } ?> /app/vendors/shells/post.php <?php App::import('Component', 'Email'); // Import EmailComponent to make it available App::import('Core', 'Controller'); // Import Controller class to base our App's controllers off of App::import('Controller', 'Posts'); // Import PostsController to make it available App::import('Sanitize'); // Import Sanitize class to make it available class PostShell extends Shell { var $uses = array('Post'); // Load Post model for access as $this->Post function startup() { $this->Email = new EmailComponent(); // Create EmailComponent object $this->Posts = new PostsController(); // Create PostsController object $this->Posts->constructClasses(); // Set up PostsController $this->Posts->Security->initialize(&$this->Posts); // Initialize component that's attached to PostsController. This is needed if you want to call PostsController actions that use this component } function main() { $this->out($this->Email->delivery); // Should echo 'mail' on the command line $this->out(Sanitize::html('<p>Hello</p>')); // Should echo &lt;p&gt;Hello&lt;/p&gt; on the command line $this->out($this->Posts->index()); // Should echo 'Index action' on the command line var_dump(is_object($this->Posts->Security)); // Should echo 'true' } } ?> The whole shell script is there to demonstrate that you can have access to: * *Components that you load directly and that are not loaded through a controller *Controllers (first import the Controller class, then import your own controller) *Components that are used by controllers (After creating a new controller, run the constructClasses() method and then the particular component's initialize() method as shown above. *Core utility classes, like the Sanitize class shown above. *Models (just include in your shell's $uses property). Your shell can have a startup method that is always run first, and the main method, which is your shell scripts main process and which is run after the startup. To run this script, you would enter /path/to/cake/core/console/cake post on your command line (might have to check the proper way to do this on Windows, the info is in the CakePHP book (http://book.cakephp.org). The result of the above script should be: mail &lt;p&gt;Hello&lt;/p&gt; Index action bool(true) This works for me, but maybe people who are more advanced in CakePHP shells could offer more advice, or possibly correct some of the above... However, I hope this is enough to get you started. A: As of CakePHP 2, the shell scripts should now be saved to \Console\Command. There is good documentation at http://book.cakephp.org/2.0/en/console-and-shells.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7611538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using cedet semantic wisent-ruby I'm just getting started setting up cedet following various guides including Alex Ott's. Here is what I have so far in my init file. (require 'cedet) (semantic-load-enable-code-helpers) ;; imenu breaks if I don't enable this (global-semantic-highlight-func-mode 1) (global-semantic-tag-folding-mode) I quite like the code folding, because semantic know more about code than packages like hideshow, etc. I would like to have the same folding for ruby. I know there is other stuff cedet does, but I'm just dipping my toes in for now. So I see in the contrib/ folder there is wisent-ruby.el. It sure looks like semantic knows how to parse Ruby. The INSTALL says that it's supposed to be installed "automatically". I open up a Ruby file and code folding magic triangles aren't there. What now? A: As I see in contrib-loaddefs.el, correct hooks & autoloads are generated only for php & C# modes. You can explicitly load wisent-ruby and setup corresponding hook, as in following example: (require 'wisent-ruby) (add-hook 'ruby-mode-hook #'wisent-ruby-default-setup) but I hadn't checked, does folding works for Ruby or not (because I also don't know status of Ruby parser). You can write to cedet mailing list with more questions about wisent-ruby...
{ "language": "en", "url": "https://stackoverflow.com/questions/7611539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: c-ares specifying network interface for the DNS resolves Is there a way in which you can set the network interface to which the DNS requests can be bound to. We have a project which requires to use a highpriority streaming session go through one interface and all the other requests channeled through the second one. example: setting 'eth0' so that all the ares requests will go through 'eth0' and not on 'wlan0'. I was not able to find any API in c-ares (in ares_init_options() API) that gives this option of setting interface. Can you please let me know if there is some way to achive this or if I missed something. Thanks, Arjun A: If you have a fairly new c-ares (c-ares >= 1.7.4), check out ares.h (It's the only place I've actually found it referenced). /* These next 3 configure local binding for the out-going socket * connection. Use these to specify source IP and/or network device * on multi-homed systems. */ CARES_EXTERN void ares_set_local_ip4(ares_channel channel, unsigned int local_ip); /* local_ip6 should be 16 bytes in length */ CARES_EXTERN void ares_set_local_ip6(ares_channel channel, const unsigned char* local_ip6); /* local_dev_name should be null terminated. */ CARES_EXTERN void ares_set_local_dev(ares_channel channel, const char* local_dev_name);
{ "language": "en", "url": "https://stackoverflow.com/questions/7611544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java Project Template We are starting to build a large middle tier java application (webservices, etc.,). I want to create a template project, so it can used for any other future projects. Here is what i am thinking of defining in the template project: * *Caching mechanism (for look up and other meta information) *Exception handling *Logging *Needed third party frameworks (build, test, spring) any thing else that can be included here? I am looking for expert suggestions on each of these areas: 1) * *I am thinking ehCache, any comments on this? positives, negatives or alternatives? *I dont want developers just to use blanket try/catch blocks.. some mechanism to automatically catch those and log it and configure in a way we want. any suggestions? *log4j *I think i will go with Maven, JUnit and Spring; any other 3rd party frameworks worth considering? I dont want to discuss maven versus ant, etc., Thank you, A: Exception Handling: If you pick spring framework then you would get some help in this regards * *I say spring provides exception translation for persistence layer so no boiler plate code *I think if you cannot recover and finish the task on hand why not just make it a RuntimeException *I am not big fan of expressing a business rule as an exception (ex: PatientNotFoundException just from my personal experience) Log4j: I would just say use slf4j abstraction Maven: I think Maven is a good build tool as any, I would recommend you to look into Gradle, Since it is a new project it might be worth while to have a look I would also add that, It is worth while to invest some time into Continuous Integration and tools like Jenkins or Bamboo
{ "language": "en", "url": "https://stackoverflow.com/questions/7611545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ocamlfind, where to find/how to build? I know next to nothing about ocaml, but I want to install Coccinelle (on cygwin), which has a dependency to the binary ocamlfind. However, installing either ocaml-3.11.0-win-mgw.exe or ocaml-3.11.0-win-msvc.exe from http://caml.inria.fr/download.en.html, there are no such binary. In fact not a single file in the installed directory contains any reference to the string "ocamlfind". And downloading the source code (ocaml-3.12.1), grep only finds the following references: ./Changes:- PR#5165: ocamlbuild does not pass '-thread' option to ocamlfind ./Changes:- PR#5217: ocamlfind plugin should add '-linkpkg' for toplevel ./ocamlbuild/command.ml: else None (* Sh"ocamlfind ocamlc" for example will not be digested. *) ./ocamlbuild/findlib.ml: | Cannot_run_ocamlfind ./ocamlbuild/findlib.ml: | Cannot_run_ocamlfind -> ./ocamlbuild/findlib.ml:let ocamlfind = "ocamlfind" ./ocamlbuild/findlib.ml: run_and_parse Lexers.ocamlfind_query ./ocamlbuild/findlib.ml: "%s query -l -predicates byte %s" ocamlfind name ./ocamlbuild/findlib.ml: "%s query -a-format -predicates native %s" ocamlfind name ./ocamlbuild/findlib.ml: run_and_parse Lexers.blank_sep_strings "%s query -r -p-format %s" ocamlfind name ./ocamlbuild/findlib.ml: (* TODO: Improve to differenciate whether ocamlfind cannot be ./ocamlbuild/findlib.ml: error Cannot_run_ocamlfind ./ocamlbuild/findlib.ml: run_and_parse Lexers.blank_sep_strings "%s list | cut -d' ' -f1" ocamlfind ./ocamlbuild/findlib.ml:make another ocamlfind query such as: ./ocamlbuild/findlib.ml: ocamlfind query -p-format -r package1 package2 ... *) ./ocamlbuild/lexers.mli:val ocamlfind_query : Lexing.lexbuf -> ./ocamlbuild/lexers.mll:and ocamlfind_query = parse ./ocamlbuild/lexers.mll: | _ { raise (Error "Bad ocamlfind query") } ./ocamlbuild/manual/manual.tex:\texttt{ocamlfind}). Here is the list of relevant options: ./ocamlbuild/ocaml_specific.ml: if !Options.use_ocamlfind then begin ./ocamlbuild/ocaml_specific.ml: (* Note: if there is no -pkg option, ocamlfind won't be called *) ./ocamlbuild/ocaml_specific.ml:if not !Options.use_ocamlfind then begin ./ocamlbuild/options.ml:let use_ocamlfind = ref false ./ocamlbuild/options.ml: "ocamlyacc"; "menhir"; "ocamllex"; "ocamlmklib"; "ocamlmktop"; "ocamlfind"] ./ocamlbuild/options.ml:let ocamlfind x = S[V"OCAMLFIND"; x] ./ocamlbuild/options.ml: "-use-ocamlfind", Set use_ocamlfind, " Use ocamlfind to call ocaml compilers"; ./ocamlbuild/options.ml: if !use_ocamlfind then begin ./ocamlbuild/options.ml: ocamlc := ocamlfind & A"ocamlc"; ./ocamlbuild/options.ml: ocamlopt := ocamlfind & A"ocamlopt"; ./ocamlbuild/options.ml: ocamldep := ocamlfind & A"ocamldep"; ./ocamlbuild/options.ml: ocamldoc := ocamlfind & A"ocamldoc"; ./ocamlbuild/options.ml: ocamlmktop := ocamlfind & A"ocamlmktop"; ./ocamlbuild/signatures.mli: val use_ocamlfind : bool ref ./ocamlbuild/signatures.mli: | Cannot_run_ocamlfind ./ocamlbuild/signatures.mli: (** Transitive closure, as returned by [ocamlfind query -r]. *) and none of this is any references to install of such a binary. So I am sort of lost on how to proceed. Go back to older releases of ocaml? BTW, the native ocaml cygwin packages did also not contain any ocamlfind binary. A: Is google down today? http://projects.camlcity.org/projects/findlib.html There is no precompiled binary, but on cygwin it compiles fine out of the box.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why would an Overlapped call to recv return ERROR_NO_MORE_ITEMS(259)? I did a few tests with an I/O-Completion port and winsock sockets. I encountered, that sometimes after I received data from a connection and then adjacently call WSARecv again on that socket it returns immediately with the error 259 (ERROR_NO_MORE_ITEMS). I am wondering why the system flags the overlapped transaction with this error instead of keeping the recv call blocking/waiting for incoming data. Do You know what´s the sense of this ? I would be glad to hear about your thoughts. Edit: Code do { OVERLAPPED* pOverlapped = nullptr; DWORD dwBytes = 0; ULONG_PTR ulKey = 0; //Dequeue a completion packet if(!m_pIOCP->GetCompletionStatus(&dwBytes, &ulKey, &pOverlapped, INFINITE)) DebugBreak(); //Evaluate switch(((MYOVERLAPPED*)pOverlapped)->WorkType) { case ACCEPT_OVERLAPPED_TYPE: { //cast ACCEPT_OVERLAPPED* pAccept = (ACCEPT_OVERLAPPED*)pOverlapped; //Associate the newly accepted connection with the IOCP if(!m_pIOCP->AssociateHandle((HANDLE)(pAccept->pSockClient)->operator SOCKET(), 1)) { //Association failed: close the socket and and delte the overlapped strucuture } //Call recv RECV_OVERLAPPED* pRecvAction = new RECV_OVERLAPPED; pRecvAction->pSockClient = pAccept->pSockClient; short s = (pRecvAction->pSockClient)->Recv(pRecvAction->strBuf, pRecvAction->pWSABuf, 10, pRecvAction); if(s == Inc::REMOTECONNECTION_CLOSED) { //Error stuff } //Call accept again (create a new ACCEPT_OVERLAPPED to ensure overlapped being zeroed out) ACCEPT_OVERLAPPED *pNewAccept = new ACCEPT_OVERLAPPED; pNewAccept->pSockListen = pAccept->pSockListen; pNewAccept->pSockClient = new Inc::CSocket((pNewAccept->pSockListen)->Accept(nullptr, nullptr, pNewAccept)); //delete the old overlapped struct delete pAccept; } break; case RECV_OVERLAPPED_TYPE: { RECV_OVERLAPPED* pOldRecvAction = (RECV_OVERLAPPED*)pOverlapped; if(!pOldRecvAction->InternalHigh) { //Connection has been closed: delete the socket(implicitly closes the socket) Inc::CSocket::freewsabuf(pOldRecvAction->pWSABuf); //free the wsabuf delete pOldRecvAction->pSockClient; } else { //Call recv again (create a new RECV_OVERLAPPED) RECV_OVERLAPPED* pNewRecvAction = new RECV_OVERLAPPED; pNewRecvAction->pSockClient = pOldRecvAction->pSockClient; short sRet2 = (pNewRecvAction->pSockClient)->Recv(pNewRecvAction->strBuf, pNewRecvAction->pWSABuf, 10, pNewRecvAction); //Free the old wsabuf Inc::CSocket::freewsabuf(pOldRecvAction->pWSABuf); delete pOldRecvAction; } Cutted error checkings... The Recv-member-function is a simple wrapper around the WSARecv-call which creates the WSABUF and the receiving buffer itself (which needs to be cleaned up by the user via freewsabuf - just to mention)... A: It looks like I was sending less data than was requested by the receiving side. But since it´s an overlapped operation receiving a small junk of the requested bunch via the TCP-connection would trigger the completion indication with the error ERROR_NO_MORE_ITEMS, meaning there was nothing more to recv than what it already had.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GetSchemaTable Columns Missing? I am using this code to get data from a dataReader into a DataTable which can then be serialised. However, it looks like any column with a null value isnt being written to the xml. I cant see the issue. This is my entire class, and im calling this method Process(IDataReader data, string filePath) Im certain that this works, because i have used it to serialise dataTables before Process(DataTable table, string filePath) So i think it must be in the "GetDataTableFromSqlDataReader" method?? public class DataSerialisation { public static DataRow GetFirstDataRow(string xmlFilePath) { return GetDataTable(xmlFilePath).Rows[0]; } public static DataTable GetDataTable(string xmlFilePath) { DataSet ds = new DataSet(); ds.ReadXml(xmlFilePath); return ds.Tables[0]; } private static DataTable GetDataTableFromSqlDataReader(IDataReader dr) { DataTable dtSchema = dr.GetSchemaTable(); DataTable dt = new DataTable(); ArrayList listCols = new ArrayList(); if (dtSchema != null) { foreach (DataRow drow in dtSchema.Rows) { string columnName = Convert.ToString(drow["columnName"]); //drow["columnName"].ToString(); DataColumn column = new DataColumn(columnName, (Type) (drow["DataType"])); //column.ColumnName = columnName; //column.Unique = (bool) (drow["IsUnique"]); column.AllowDBNull = (bool) (drow["AllowDBNull"]); //column.AutoIncrement = (bool) (drow["IsAutoIncrement"]); //column.AutoIncrement = (bool) (drow["IsAutoIncrement"]); listCols.Add(column); dt.Columns.Add(column); } while (dr.Read()) { DataRow dataRow = dt.NewRow(); for (int i = 0; i < listCols.Count; i++) dataRow[((DataColumn) listCols[i])] = dr[i]; dt.Rows.Add(dataRow); } } return dt; } public static void Process(IDataReader data, string filePath) { Process(GetDataTableFromSqlDataReader(data), filePath); } public static void Process(DataTable table, string filePath) { DataSet ds = new DataSet(); ds.Tables.Add(table.Clone()); foreach (DataRow row in table.Rows) { DataRow newRow = ds.Tables[0].NewRow(); for (int col = 0; col < ds.Tables[0].Columns.Count; col++) newRow[col] = row[col]; ds.Tables[0].Rows.Add(newRow); } ds.WriteXml(new StreamWriter(filePath)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7611563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using ItextSharp I am getting Unbalanced begin/end text operators. But they are Matched I working on a app that uses ItextSharp to generate PDF files for students to print name tags and parking permits... However it keeps throwing: Unbalanced begin/end text operators. at the doc.close() The blocks appear to be properly openned and closed.. Below is the function: Function ID_and_Parking(ByVal id As Integer) As ActionResult Dim _reg_info As reg_info = db.reg_info.Single(Function(r) r.id = id) Dim _conf_info As conf_info = db.conf_info.Single(Function(f) f.id = 0) Dim _LastName As String = _reg_info.last_name Dim _Employer As String = _reg_info.business_name Dim _Class_1 As String = _reg_info.tues_class Dim _Class_2 As String = _reg_info.wed_class Dim _Class_3 As String = _reg_info.thur_class Dim _Class_4 As String = _reg_info.fri_class Dim _BeginDate As String = _conf_info.conf_start_date Dim _endDate As String = _conf_info.conf_end_date If IsDBNull(_reg_info.tues_class) Then _Class_1 = "" End If If IsDBNull(_reg_info.wed_class) Then _Class_2 = "" End If If IsDBNull(_reg_info.thur_class) Then _Class_3 = "" End If If IsDBNull(_reg_info.fri_class) Then _Class_4 = "" End If 'Dim pdfpath As String = Server.MapPath("PDFs") 'Dim imagepath As String = Server.MapPath("Images") Dim pdfpath As String = "C:\temp\" Dim imagepath As String = "C:\temp\" Dim doc As New Document doc.SetPageSize(iTextSharp.text.PageSize.A4) doc.SetMargins(0, 0, 2, 2) Try Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(pdfpath + "/Images.pdf", FileMode.Create)) doc.Open() Dim cb As PdfContentByte = writer.DirectContent cb.BeginText() cb.SetTextMatrix(100, 400) cb.ShowText(_LastName) cb.EndText() doc.Add(New Paragraph("JPG")) Dim jpg As Image = Image.GetInstance(imagepath + "/Asads_Tags.jpg") jpg.Alignment = iTextSharp.text.Image.UNDERLYING jpg.ScaleToFit(576, 756) doc.Add(jpg) Catch dex As DocumentException Response.Write(dex.Message) Catch ioex As IOException Response.Write(ioex.Message) Catch ex As Exception Response.Write(ex.Message) Finally doc.Close() End Try Return RedirectToAction("Index") End Function Anyone know where I could be going wrong at?????? A: The Try Catch block is what caused the unbalanced start/end exception.....Once I moved the doc.close() up to the bottom of try the error went away... Oh well maybe someone else will need the insight... –
{ "language": "en", "url": "https://stackoverflow.com/questions/7611565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java Application conversion into Java applet and passing Parameters from HTML I'm new to Java and tried to create an application which runs a system command when executed. I accomplished just that with the following code: package printtest; import java.io.*; import java.util.*; public class PrintTest { public static void main(String args[]) throws InterruptedException,IOException { List<String> command = new ArrayList<String>(); command.add(System.getenv("programfiles") +"\\Internet Explorer\\"+"iexplore.exe"); command.add("http://www.google.com"); ProcessBuilder builder = new ProcessBuilder(command); Map<String, String> environ = builder.environment(); builder.directory(new File(System.getenv("programfiles")+"\\Internet Explorer\\")); System.out.println("Directory : " + System.getenv("programfiles")+"Internet Explorer\\"); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } System.out.println("Program terminated!"); } } If I run the application, it runs a system command in the following syntax "iexplore.exe http://www.google.com". This is great. The problem I'm having, and I would like to ask for help in it, is this: I would like to pass variables to this application from a HTML page so the arguments after the executable can be passed in the java application by changing PARAMS in HTML. For this I understood that this app needs to be an applet. I don't know how to modify this to compile for inclusion in HTML. Can you help me with this issue?! I've been searching for 2 days now for an answer. UPDATE: I'm sorry, I think I'm not explaining as I should. Here's what needs to be done: 1. An order management interface written in PHP needs a way to run a system command with extra parameters to print transport recepts. To do this somehow a webpage should trigger the printing via an applet or any other solution. If you have a an idea about solving this please do tell me. Thanks A: I would like to pass variables to this application from a HTML page so the arguments after the executable can be passed in the java application by changing PARAMS in HTML. For this I understood that this app needs to be an applet. No. As long as you have something on the server side that will generate documents dynamically (e.g. for parameters in HTML or a JNLP launch file), you can use that functionality to create an unique (includes parameters for that use) launch file for a Java Web Start launch. Of course, whether it is an applet or JWS app., it will require a GUI. BTW - in case you do not realize: * *The code being used will open IE on Windows. * *I use Windows but my default browser is FireFox. *It will fail completely on Mac, Linux, Unix.. *Java has 3 built-in ways to open a web page. * *An Applet has access to the 'AppletContext' class, which offers AppletContext.showDocument(URL). *Java Web Start apps. have access to the JNLP API, which offers BasicService.showDocument(URL). *Java 6+ apps. can use Desktop.browse(URI). Either of the last two is superior to the Applet method, since they either return a boolean to indicate success, or throw a range of helpful exceptions. For use in an applet or an app. launched using JWS, either of the Desktop class or using a Process would require digitally signed and trusted code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add new class and autoload in zend framework I am new on Zend framework and using first time it. I am looking for simple basic tutorials which I can read in very short time. I also stuck on if I want to add new class in Zend library. And it should also auto load when I make any new controller. Please give your opinions if you have. Regards, A: This helped me At the beginning: http://www.zendcasts.com/ http://devzone.zend.com/search/results?q=autoload (just search) As autoload your class, This is the my way: Create folder 'My' into library/ in it create folder 'Utils' and in Utils file 'Utils.php' so the path is library/My/Utils/Utils.php For this path You must call class: class My_Utils_Utils{ ... } and in configs/application.ini Put appnamespace = "Application" autoloaderNamespaces.my = "My_" Then you can use namespace My_ and class My_Utils_Utils In controller: $test = new My_Utils_Utils(); A: * *I am looking for simple basic tutorials Here are a few tutorials I found while googling: * *Official quickstart tutorial *A great book by frequent ZF-contributer Padráic Brady: Survive the deep end! *http://akrabat.com/zend-framework-tutorial/ *Page with different tutorials: ZFTutorials.com *I also stuck on if I want to add new class in Zend library You should not add new classes to the library per se, but instead create your own library or add classes in the "models"-folder/folders (if you use the modular project layout). Autoloading is achieved by utilizing Zend_Loader_Autoloader and its subclasses. As long as you follow the PEAR convention, i.e. if you have a class MyLib_Database_Table, then it should be inside the folder MyLib/Database, and the filename should be Table.php. (also make sure that the parent folder of MyLib is on the project include path. To autoload simply use new MyLib_Database_Table, and the autoloader will load the class behind the scenes if necessary. Since 1.10 (I think), the autoloader also fully support PHP 5.3 namespaces. I.e: // Filepath: lib\MyLib\Database\Table.php namespace MyLib\Database; class Table { } will work with the same folder structure. Code example: use MyLib\Database\Table; class IndexController extends Zend_Controller_Action { public function indexAction () { $myTable = new Table(); } } *auto load when I make any new controller I'm not quite sure what you mean here. ZF does not have any dependency injection setup per default. But you can instantiate your classes without requiring them first if that's what you mean.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Altering fake repository for unit testing when using dependency injection In my program I have a situation that I can simplify to the following: * *An IRepository of which I create a MemoryRepository and a SqlRepository implementation *A Mapper that gets the IRepository constructor injected. *A Mapper.Map() that contains business logic I want to test I created a test where the Mapper receives the MemoryRepository. By explicitly setting a property on the memory repository that will be used in the business logic I can now test this logic. If I use injection however, I wouldn't have access to this repository anymore. A bit of code tells you more then a 1000 normal words, here is the pastebin link. How would you go about this? A: Not entirely sure what you're asking here, are you testing the mapper or the repository? If you're testing the mapper, then fake the repository. You've already got the seams in place, either use a framework or create a fake repository manually in your tests that makes whatever happy noises you want for the sake of testing Mapper and create the mapper by passing in your fake into the constructor. So by your own simplification, * *Create a fake Repository inheriting from IRepository *Inject the fake into your Mapper that you are going to test *Test Mapper.Map() If you need to verify some information on the Repository, use a Mock rather than a Stub. Difference Between Mocks and Stubs A: If I understand your question correctly basically you are concerned that your repository was created AND injected when the test class was instantiated and so in your test method you cannot modify the state of your repository since it is already inside your mapper and, of course, your mapper should not expose the internals of the repository. If that is the case then I don't think you have to worry, just modify the state of the myMemoryCategoryRepository and execute the mapper's method. Your mapper should behave accordingly because what you injected is a reference to the repository so the object inside the mapper is the same one as the one you would be modifying. Dim myMemoryCategoryRepository As MemoryCategoryRepository = MemoryKernel.Instance.Get(Of MemoryCategoryRepository)() Dim myCategoryMapper As CategoryMapper = New CategoryMapper(myMemoryCategoryRepository) <TestMethod()> _ Public Sub GetCategoryStartDate_CategoryStartDateAndContractStartDate_ContractStartDateIsOldestDate() myMemoryCategoryRepository.AnyFlag = True myCategoryMapper.Execute() Assert.AreEqual(expectedValue, myCategoryMapper.Value) End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7611583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A guide to hacking IE8 into shape? I've finished making my website, but then I loaded it up in IE8. Big problems! For instance, a bunch of my div and span elements seem to be transparent (they should have coloured backgrounds), and floating elements don't work. When I was developing my site, I had hoped I would just be able to ignore the older internet explorers - ie9 is standards compliant, and eventually everyone will end up using that. However, Microsoft are not releasing IE9 for XP, but people are going to be using that operating system for a long time still, I think. As such, I need to support IE8. Does there exist a comprehensive list of all the things that IE8/ do wrong? Not something like Quirksmode.org, but a guide to the common issues with layout in IE8, and the hacks needed to fix them? EDIT: The transparent elements thing seems to be somehow related to my use of css3pie. A: You could try using conditional classes to target specific fixes for specific versions of IE. This is from Paul Irish's HTML5 Boilerplate: <!doctype html> <!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en"> <![endif]--> <!--[if IE 7]> <html class="no-js ie7 oldie" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js ie8 oldie" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> With these comments you can specify something like: .ie7 #container {margin-left:-1px;} And it would only change your #container margin on IE7. If those don't work, post some of your code and people might be able to point out some incompatibilities.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google crawling, AJAX and HTML5 HTML5 allows us to update the current URL without refreshing the browser. I've created a small framework on top of HTML5 which allows me to leverage this transparently, so I can do all requests using AJAX while still having bookmarkable URLs without hashtags. So e.g. my navigation looks like this: <ul> <li><a href="/home">Home</a></li> <li><a href="/news">News</a></li> <li>...</li> </ul> When a user clicks on the News link, my framework in fact issues an AJAX GET request (jQuery) for the page and replaces the current content with the retrieved content. After that, the current URL is updated using HTML5's pushState(). However, it is still equally possible to just type http://www.example.com/news in the browser, in which case the content will be provided synchronously of course. The question now is, will Google crawl the pages for this site? I know that Google provides a guide for crawling Ajax applications, but the article supposes that hashtags are used for bookmarkability, and I don't (want to) use hashtags. A: Since you have actual hard links to the pages and they load the same content, Google will crawl your site just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java how to avoid duplicate in recursion i'm trying to search synonym(which i declare as 'synset') recursively. Unfortunately, there are duplicate of synonym. For example: when i search the word student, the output will be like this: Search word: student Synset 0: pupil Synset 0: student Synset 0: pupil . . . Synset 1: educatee Synset 2: schoolchild Synset 1: educatee Synset 2: scholar Synset 3: bookman I want to store all the output into database and I do not need the duplicate output.This is part of my code that consist recursive function. Hope anyone can help me..Thanks public String printSynset(String word) { //call wordnet library RiWordnet wordnet = new RiWordnet(); //call stemmer method PorterStemmer s = new PorterStemmer(); Vector<String> synsetVec = new Vector<String>(); String[] synset = wordnet.getAllSynsets(word, "n"); for (int k=0; k<synset.length; k++) { synsetVec.add(synset[k]); if (!synsetVec.isEmpty()) { for (int j = 0; j < synsetVec.size();) { GUIsynonymTA.append("\n"); GUIsynonymTA.append(" No." + j + ": " + (s.Stem(synsetVec.get(j)))); GUIsynonymTA.append("\n"); return printSynset(synsetVec.get(j)); } } else if (synsetVec.isEmpty()) return word; } return word; }//end printSynset() A: You should maintain a Set of the items you've already seen. Every time you hit an item, first check whether it's been seen before; if it is, stop the recursion; if it's not, add it to the set and proceed. The result is the classic depth-first search for general graphs, which you can find in any algorithms textbook or in Russell & Norvig chapter 3. Pseudocode: Set<Node> printSynset(Node root) { HashSet<Node> closed; printDFS(root, closed); } // recursive graph dfs void printDFS(Node n, Set<Node> closed) { if (!closed.contains(n)) { print(n.item); closed.add(n); for (Node s : n.neighbors()) printDFS(n, closed); } } Note that when printDFS returns to printSynset, it will have filled closed with all nodes it has visited, so you could also choose to return that Set<Node> and loop over it in printSynset, instead of doing the printing in printDFS. That would leave you with a general, re-usable DFS routine. A: Use a Set to store the previously found matches. If the word is in the Set don't output it again. Set Maintain the Set as a class level field so that all the recursions of the method have access to the Set. If Set.add(word) returns false you know that the word was already in the Set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7611587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use of undeclared identifier in json for iOS I am getting a use of undeclared identifier error in my json but I am following the example from http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c how do I fix this? Yes I am very new to objective-c \ ios :) Thanks I am putting this code in my view based application in my viewcontroller.m file The issue is with "SBJSON *parser = [[SBJSON alloc] init];" // Create new SBJSON parser object SBJSON *parser = [[SBJSON alloc] init]; // Prepare URL request to download statuses from Twitter NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://twitter.com/statuses/public_timeline.json"]]; // Perform request and get JSON back as a NSData object NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // Get JSON as a NSString from NSData response NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; // parse the JSON response into an object // Here we're using NSArray since we're parsing an array of JSON status objects NSArray *statuses = [parser objectWithString:json_string error:nil]; // Each element in statuses is a single status // represented as a NSDictionary for (NSDictionary *status in statuses) { // You can retrieve individual values using objectForKey on the status NSDictionary // This will print the tweet and username to the console NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"user"] objectForKey:@"screen_name"]); } A: Try changing the line to SBJsonParser *parser = [[SBJsonParser alloc] init]; Edit: A way that can be easier is to use the NSString category that SBJSON provides: NSArray *statuses = (NSArray *)[json_string JSONValue];
{ "language": "en", "url": "https://stackoverflow.com/questions/7611589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }