text
stringlengths
8
267k
meta
dict
Q: jQuery Drag/Drop * element styling I have a list that I want to be drag and droppable to another list with jQuery. The drag drop works fine but I'm running into a problem because I need to display two different bits of information from a database on the same "li" item, but with different styling. I'd like to be able to add a "track length" to each list item below but I need the track length text to have a different background and text color, but still be part of the same "li" so that the entire thing is draggable. Is there a neat and tidy way to do this with basic htm/css? <ul class="songs"> <li class="song_title">Title 1</li> <li class="song_title">Title 2</li> </ul> A: Not really a jquery question but you should be able to maintain draggability with the following html structure and get the styling needed for both data pieces. <ul class="songs"> <li class="song_title"> <span class="title">Title 1</span> <span class="track_length">Some Length</span> </li> <li class="song_title"> <span class="title">Title 2</span> <span class="track_length">Some Length</span> </li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/7550373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can sbt pull dependency artifacts from git? I've heard (and I know I've seen examples too, if only I can remember where) that sbt can obtain dependencies from a git repo. I am looking to obtain the dependency harrah/up from github. The repository does not provide any artifact JAR files, only a source tree which is set up to be built using sbt. The process that I am imagining is that sbt will download the source repo, build it, and then use that as the dependency artifact. I may be imagining that sbt can in fact do something like this. Can it? And if so, how? A: I wanted to add an answer for sbt 0.13+. Just put something like this to your build.sbt on project root folder (not Build.scala): lazy val root = (project in file(".")).dependsOn(playJongo) lazy val playJongo = RootProject(uri("https://github.com/bekce/play-jongo.git")) A: Yes indeed. You can give your Project a dependency with the dependsOn operator, and you can reference a Github project by its URI, for example RootProject(uri("git://github.com/dragos/dupcheck.git")). Alternatively, you can git clone the project, and then reference your local copy with RootProject(file(...)). See "Full Configuration" on the SBT wiki for details and examples. A: You can import unpackaged dependencies into your project from GitHub by treating them as project dependencies, using the dependsOn operator. (This is distinct from the way that precompiled library dependencies are included). Note that you can specify which branch to pull using # notation. Here's some Scala SBT code that is working well for me: object V { val depProject = "master" // Other library versions } object Projects { lazy val depProject = RootProject(uri("git://github.com/me/dep-project.git#%s".format(V.depProject))) } // Library dependencies lazy val myProject = Project("my-project", file(".")) .settings(myProjectSettings: _*) .dependsOn(Projects.depProject) .settings( libraryDependencies ++= Seq(... Note that if you have multiple SBT projects dependending on the same external project, it's worth setting up a central sbt.boot.directory to avoid unnecessary recompilations (see instructions here). A: Since I had problems getting the dependencies of my library resolved (using the suggested RootProject) I'd like to point out to the object called ProjectRef. Thus, if one need to depend on a library residing in git, I suggest to do so as follows: import sbt.Keys._ import sbt._ object MyBuild extends Build { lazy val root = Project("root", file(".")) .dependsOn(myLibraryinGit) .settings( ..., libraryDependencies ++= Seq(...)) lazy val myLibraryinGit = ProjectRef(uri("git://git@github.com:user/repo.git#branch"), "repo-name") } Source: http://blog.xebia.com/git-subproject-compile-time-dependencies-in-sbt/
{ "language": "en", "url": "https://stackoverflow.com/questions/7550376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "108" }
Q: Calculating cumulative sum for each row I am trying to calculate the cumulative sum for each row using the following code: df <- data.frame(count=1:10) for (loop in (1:nrow(df))) {df[loop,"acc_sum"] <- sum(df[1:loop,"count"])} But I don't like the explicit loop here, how can I modify it? A: You want cumsum() df <- within(df, acc_sum <- cumsum(count)) A: With data.table you can also use dt <- as.data.table(df) dt[, acc_sum := cumsum(count)] A: You can also try mySum = t(apply(df, 1, cumsum)). The transpose is in there because the results come out transposed, for a reason I have not yet determined. I'm sure there are fine solutions with plyr, such as ddply and multicore methods. A: To replicate the OP's result, the cumsum function is all that is needed, as Chase's answer shows. However, the OP's wording "for each row" possibly indicates interest in the cumulative sums of a matrix or data frame. For column-wise cumsums of a data.frame, interestingly, cumsum is again all one needs! cumsum is a primitive that is part of the Math group of generic functions, which is defined for data frames as applying the function to each column; inside the code, it just does this : x[] <- lapply(x, .Generic, ...). > foo <- matrix(1:6, ncol=3) > df <- data.frame(foo) > df [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 > cumsum(df) X1 X2 X3 1 1 3 5 2 3 7 11 Interestingly, sum is not part of Math, but part of the Summary group of generic functions; for data frames, this group first converts the data frame to a matrix and then calls the generic, so sum returns not column-wise sums but the overall sum: > sum(df) [1] 21 This discrepancy is (in my opinion) most likely because cumsum returns a matrix of the same size as the original, but sum would not. For row-wise cumulative sums, there not a single function that replicates this behavior that I know of; Iterator's solution is probably one of the most straightforward. If speed is an issue, it would be almost certainly be fastest and most foolproof to write it in C; however, it speeds up a little (~2x ?) for long loops by using a simple for loop. rowCumSums <- function(x) { for(i in seq_len(dim(x)[1])) { x[i,] <- cumsum(x[i,]) }; x } colCumSums <- function(x) { for(i in seq_len(dim(x)[2])) { x[,i] <- cumsum(x[,i]) }; x } This can be sped up more by using the plain cumsum and subtracting off the sum so far when you get to the end of a column. For row cumulative sums, one needs to transpose twice. colCumSums2 <- function(x) { matrix(cumsum(rbind(x,-colSums(x))), ncol=ncol(x))[1:nrow(x),] } rowCumSums2 <- function(x) { t(colCumSums2(t(x))) } That's really a hack though. Don't do it. A: An alternative to cumsum() could be: within(df, acc_sum <- Reduce("+", count, accumulate = TRUE)) count acc_sum 1 1 1 2 2 3 3 3 6 4 4 10 5 5 15 6 6 21 7 7 28 8 8 36 9 9 45 10 10 55 A: We can use library(collapse) dapply(df, MARGIN = 1, FUN = fcumsum)
{ "language": "en", "url": "https://stackoverflow.com/questions/7550383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Is it possible to add a "Combine" step to the Amazon Elastic MapReduce workflow? I am referring to the Combine step mentioned on the Hadoop wiki. I have been unable to find a reference to it in the AWS documentation, and I'd like to utilize this step. A: The documentation for Combiner will be in the Apache documentation and not in the AWS documentation. Amazon Elastic MapReduce supports 0.18.3 and 0.20.2 versions of Hadoop with custom patches. Apache MR Tutorial has reference to how the combiner function should be used. Call the Job.setCombinerClass() to set the combiner class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I set the taglib character set on Windows to use unicode? TagLib uses the CMake build system to create the Visual Studio 2010 solution and project files. The only problem with the generated projects is that the Character Set is set to MBCS, when I'd like it to be Unicode. Is there a way to set this option via CMake? I'm currently using this to build taglib on Windows on a VS2010 command prompt: cmake -DWITH_MP4=ON -DENABLE_STATIC=ON . A: Alternatively to Andrey's answer you could specify the character set in a CMakeLists.txt file by target_compile_definitions (TargetName PRIVATE -D_UNICODE -DUNICODE <additional defines>) A: The following command should do the job: cmake -DCMAKE_CXX_FLAGS=/D_UNICODE .. cmake automatically turns on the Unicode character set in Visual Studio projects if _UNICODE macro is defined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "Kill a process tree" on windows using Java I have a Java webstart process that is part of a windows batch script. I'm using the javaws command in a batch script in this case. This match script ( start.bat) is invoked programatically using the "apache commons exec". Under some conditions the java process invoked by javaws hangs and I'd have to kill the entire process thread starting from the batch script start.bat. Is there a programatic way of doing killing an entire process tree through apache commons exec? I've tried using the "execWatchdog.destroyProcess();" on the "start.bat" script. However it only kills the start.bat process and not the entire process tree. Is there a way of killing the entire process tree through apache-commons-exec or a similar code? I've seen this question Performing equivalent of "Kill Process Tree" in c++ on windows that performs an equivalent task in c++. I'm wondering if anyone has implemented calling windows native system calls through JNI. A: Finally got something workable even though its a roundabout way. Apache Commons Exec API contains the CommandLauncher class that returns a java.lang.Process object. Thanks to the link Here the link to get the windows Process Id from a java.lang.Process. This uses the JNA libraries. Finally with the Process Id, here the command string that kills the process tree //String killCmd = "taskkill /F /T /PID " + JNAHandler.getPid(process); A: Unfortunately, as you've discovered, there isn't a pure Java way of doing this. You'll have to resort to native commands or JNI libraries, all of which are platform-dependent and more complex than a pure Java solution would be. It may be worth upvoting the relevant bug in the Java bug database: http://bugs.sun.com/view_bug.do?bug_id=4770092 With luck we can persuade the Java developers that the poor handling of subprocesses is worth fixing for Java 8. A: As far as I know, there's no such option in commons-exec. It's not even possible to obtain the PID of whatever process you just started. You could trap the kill signal within your bash script, and have the handler kill the subprocess(es) when the script process is killed. A: Java Version 9 Onwards, Java has come up with feature that can query and kill the main process and its descendants. A code snippet to query about the child processes import java.io.IOException; public class ProcessTreeTest { public static void main(String args[]) throws IOException { Runtime.getRuntime().exec("cmd"); System.out.println("Showing children processes:"); ProcessHandle processHandle = ProcessHandle.current(); processHandle.children().forEach(childProcess -> System.out.println("PID: " + childProcess.pid() + " Command: " + childProcess.info().command().get())); System.out.println("Showing descendant processes:"); processHandle.descendants().forEach(descendantProcess -> System.out.println("PID: " + descendantProcess.pid() + " Command: " + descendantProcess.info().command().get())); } } To kill the process and its children, Java9 has API Iterate through all the children of the process and call destroy on each of them For Example : As in your case you are getting Process object from apache-commons, then try out following code Process child = ...; kill (child.toHandle()); public void kill (ProcessHandle handle) { handle.descendants().forEach((child) -> kill(child)); handle.destroy(); } References : https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html https://www.tutorialspoint.com/how-to-traverse-a-process-tree-of-process-api-in-java-9 How do i terminate a process tree from Java? Note - I have not tried this feature, Just reading about Java9 and found helpful to share here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Tipsy Jquery plugin won't load inside another Javascript? I'm working with a the JQuery tipsy plugin and I can get it to work fine on my normal php page but when I run data from XML thru another javascript it's not loading or working properly... I've tried every imaginable change/variable and I'm stuck. All my jquery & jquery.tipsy scripts are linked correctly because it works outside of this JS. $(function() { $('.instructions').tipsy({gravity: 's'}); }); Then when I call it inside the other JS it won't show at all: return "<table cellpadding='8' cellspacing='0'><tr>" + "<tr>" + "<td class='mn'>" + vs.manualName + "</td>" + "<td><a class='instructions' href='#' title='" + vs.manInstr + "'>Instructions</a></td>" + "<td class='sku'>" + vs.skuNum "</td>" + "</tr></table>" }; Do I have to write it out in the JS for the tipsy to see it? A: You have to ensure that by the time the Tipsy is fired, the .instructions are already loaded and inside the DOM. So after the data from XML thru another javascript is loaded, execute. $('.instructions').tipsy({gravity: 's'});
{ "language": "en", "url": "https://stackoverflow.com/questions/7550395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does this Genetic Algorithm stagnate? Roger Alsing wrote an Evolutionary Algorithm for recreating the Mona Lisa using C#. His algorithm is simple: * *Generation a random population of size two. *Replace the least-fit individual with a clone of the fittest. *Mutate one of the individuals. *Go to step 2 There is a Java Evolutionary Algorithm framework called Watchmaker. The author reimplemented the Mona Lisa problem using a genuine Genetic Algorithm: http://watchmaker.uncommons.org/examples/monalisa.php It starts out well enough, but within 30 minutes the Watchmaker implementation stagnates with a poor approximation whereas Roger's implementation looks close to complete. I tried playing around with the settings but it didn't help much. Why is Watchmaker's implementation so much slower than Roger's and why does it stagnate? Links: * *Roger's source-code *Watchmaker's source-code A: I've studied this problem over the past month and made some interesting discoveries: * *Using opaque polygons improves rendering performance (and by extension the performance of the fitness function) by an order of magnitude. *In all things, favor many small changes over drastic large changes... *When adding a new polygon, give it a size of 1 pixel instead of assigning it vertexes with random coordinates. This improves its chances of survival. *When adding a new vertex, instead of dropping it into a random position give it the same position as an existing vertex in the polygon. It won't modify the polygon in any noticeable way, but it will open the door for the "move vertex" mutation to move more vertexes than it could before. *When moving vertexes, favor many small moves (3-10 pixels at a time) instead of trying to span the entire canvas. *If you're going to damp mutations over time, damp the amount of change as opposed to the probability of change. *The effects of damping are minimal. It turns out that if you've followed the above steps (favor small changes) there should be no real need to damp. *Don't use Crossover mutation. It introduces a high mutation rate which is great early on but very quickly high mutation becomes a liability because an image that is mostly converged will reject all but small mutations. *Don't scale the image in the fitness evaluator function. This one took me a while to figure out. If your input image is 200x200 but the fitness evaluator scales the image down to 100x100 before generating a fitness score it will result in candidate solutions containing steaks/lines of errors that are invisible to the fitness function but are clearly wrong to the end-user. The fitness function should process the entire image or not at all. A better solution is to scale the target image across-the-board so your fitness function is processing 100% of the pixels. If 100x100 is too small to display on the screen you simply up-scale the image. Now the user can see the image clearly and the fitness function isn't missing a thing. *Prevent the creation of self-intersecting polygons. They never yield good results so we can substantially speed up the algorithm by preventing mutations from creating them. Implementing the check for self-intersecting polygons was a pain in the ass but it was worth the trouble in the end. *I've modified the fitness score to remove hidden polygons (purely for performance reasons): fitness += candidate.size(); This means that the fitness score will never hit zero. *I've increased the maximum number of polygons from 50 to 65535. When I first tried running Watchmaker's Mona Lisa example it would run for days and not look anything close to the target image. Roger's algorithm was better but still stagnated after an hour. Using the new algorithm I managed to recreate the target image in less than 15 minutes. The fitness score reads 150,000 but to the naked eye the candidate looks almost identical to the original. I put together a diagnostics display that shows me the entire population evolving over time. It also tells me how many unique candidates are active in the population at any given time. A low number indicates a lack of variance. Either the population pressure is too high or the mutation rates are too low. In my experience, a decent population contains at least 50% unique candidates. I used this diagnostic display to tune the algorithm. Whenever the number of unique candidates was too low, I'd increase the mutation rate. Whenever the algorithm was stagnating too quickly I'd examine what was going on in the population. Very frequently I'd notice that the mutation amount was too high (colors or vertices moving too quickly). I'm glad I spent the past month studying this problem. It's taught me a lot about the nature of GAs. It has a lot more to do with design than code optimization. I've also discovered that it's extremely important to watch the entire population evolve in real time as opposed to only studying the fittest candidate. This allows you to discover fairly quickly which mutations are effective and whether your mutation rate is too low or high. I learned yet another important lesson about why it's extremely important to provide the fitness evaluator the exact same image as shown to the user. If you recall the original problem I reported was that the candidate image was being scaled down before evaluation, thereby allowing many pixels to avoid detection/correction. Yesterday I enabled anti-aliasing for the image shown to the user. I figured so long as the evaluator was seeing 100% of the pixels (no scaling going on) I should be safe, but it turns out this isn't enough. Take a look at the following images: Anti-aliasing enabled: Anti-aliasing disabled: They show the exact same candidates with anti-aliasing enabled and disabled. Notice how the anti-aliased version has "streaks" of errors across the face, similar to the problem I was seeing when the candidate was being scaled. It turns out that sometimes the candidates contains polygons that introduce errors into the image in the form of "streaks" (polygons rendered with sub-pixel precision). The interesting thing is that aliasing suppresses these errors so the evaluator function does not see it. Consequently, the users sees a whole bunch of errors which the fitness function will never fix. Sounds familiar? In conclusion: you should always (always!) pass the fitness function the exact same image you display to the user. Better safe than sorry :) Genetic Algorithms are a lot of fun. I encourage you to play with them yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Excel crashing on longer unicode string returned from xll addin The development of is with C/C++ on top of MS SDK. The C++ piece of XLL is as follows: __declspec(dllexport) LPWSTR WINAPI xlGetLang(LPSTR in_key) { try { static XLOPER12 lang; static size_t buffer_size = 0; static wchar_t * buffer = NULL; std::wstring unicode_str; // This step get the unicode string assigned to unicode_str // with the key in_key from internal dictionary. pms::get_instance()->get_lang(in_key, unicode_str); // over size_t msg_len = unicode_str.length(); // This step checks whether we need to incraese the buffer // for the unicode string to be returned. if (buffer_size == 0) { buffer = (LPWSTR) malloc(sizeof(wchar_t) * (msg_len + 1)); buffer_size = msg_len; } else if (buffer_size < msg_len) { buffer = (LPWSTR) realloc(buffer, sizeof(wchar_t) * (msg_len + 1)); buffer_size = msg_len; } // over wcsncpy(buffer, unicode_str.c_str(), msg_len); buffer[msg_len] = 0; return buffer; } catch (...) { ; } } The Excel VBA crashes in the Application.Run line: Dim var As String var = Application.Run("xGetLang", key) The combination of XLL & VBA runs ok when XLL returns short unicode string (i.e. with wchar_t of lenghth 6), but will start crashing when the longer unicode string (i.e. with wchar_t of lenghth 8) is returned (one such case is "OFFICE :"). The crashing environment is Excel 2007 or Excel 2010 on Vista. However, this combination of XLL & VBA runs with no issue at all on another machine Excel 2007 on XP. I have tried to put a try catch block in the XLL addin function. There is no exception caught. I also tried to put an ON ERROR statement in the VBA code, it does not catch anything either. It looks like the crashing happens between XLL return statement and excel VBA Application.Run statment. I tried to check the running stack when it crashes. it is as follows: * *NTDLL.DLL (crashing point, due to writing to memory 0X000000000 ) *Kernal32.dll *XLL addin DLL *Excel.exe Anybody has any clue? A: If you want to get VBA out of the picture use http://nxll.codeplex.com. There are wrappers for converting wide to MBCS strings in xll/utility/strings.h.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magento specific attribute per category I want to only display specific attribute to specific type of product. For example I have Shoes and a footID. footID will only be available in Shoes product page and not any other. In time I'll also have a few more similar attributes for example tennisID that only applies to tennis Products. A: In order to achieve this you first have to create all the different attributes you need. (Such as footID and tennisID) After that you have to create multiple attribute sets. In your example you would have to create two attribute sets called "Shoes" and "Tennis". In each of these attribute sets you add the attributes that belong to them. (Example when creating the attribute set tennis you have to add (drag) the tennisID attribute to it. (same goes for the shoes attribute set) These attributes will only be visible (both frontend and backend) for the attribute sets they have been added too. Regards, Kenny
{ "language": "en", "url": "https://stackoverflow.com/questions/7550403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using FetchXML in CRM 2011 I am using FetchXML and I am grouping and using count for two of the entities but the rest of the entities I don't need grouped I just need the data to be pulled down. For example this is my code: string groupby1 = @" <fetch distinct='false' mapping='logical' aggregate='true'> <entity name='opportunity'> <attribute name='name' alias='opportunity_count' aggregate='countcolumn' /> <attribute name='ownerid' alias='ownerid' groupby='true' /> <attribute name='createdon' alias='createdon' /> <attribute name='customerid' alias='customerid' /> </entity> </fetch>"; EntityCollection groupby1_result = orgProxy.RetrieveMultiple(new FetchExpression(groupby1)); foreach (var c in groupby1_result.Entities) { Int32 count = (Int32)((AliasedValue)c["opportunity_count"]).Value; string OwnerID = ((EntityReference)((AliasedValue)c["ownerid"]).Value).Name; DateTime dtCreatedOn = ((DateTime)((AliasedValue)c["createdon"]).Value); string CustomerName = ((EntityReference)((AliasedValue)c["customerid"]).Value).Name; } But I get this error: EXCEPTION: System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: An attribute can not be requested when an aggregate operation has been specified and its neither groupby nor aggregate. NodeXml : (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault). How do you use aggregates on some values and not others? A: The error message is giving you the answer - this isn't possible with FetchXML. You'll need to make two FetchXML calls; one for your aggregates and one for your data. A: So, there are a few things going on here. The problem isn't so much that your query is not achievable with FetchXML as it is it's not achievable in any query language, including SQL. The SQL of your FetchXML above is as follows: SELECT ownerID, createdon, customerid FROM dbo.Opportunity GROUP BY ownerID If you try to run this SQL against your database, you'd get the standard Column 'dbo.Opportunity.CreatedOn' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. error, which is exactly what your exception is trying to tell you. To solve this, you need to also group by every non-aggregated column (in this case, createdon and customerid) by including the groupby='true' attribute in each respective attribute element. Secondly, grouping by the create date of each opportunity is more or less a fruitless grouping, as opportunities are generally created on different datetimes, so this grouping would just return the whole table. Microsoft rightly recognizes this, so if you fix the grouping issue above, you will encounter another exception related to the datetime column. If you continue reading the article I'd previously shared, there is an example that address the different ways you can group by different date intervals (year, month, quarter, etc.) using the dategrouping attribute. But, I get the feeling that even after fixing the general grouping issues, and then the dategrouping issue, the result set might still not be what you want. If it's not, it might help to post an example of a result set that you'd expect to see and then address whether FetchXML has the power to deliver that set to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to make a website with tabs that don't go to a new page. Suggestions? I'm in the process of writing a website and I want some tabs on the side of my website. I want the website to flow well, so I don't want a simple graphical link to a website, but rather an interactive tab system where you can click on what you want and you will get there instantly. My experience is limited to XHTML and CSS, so I probably am not advanced enough to know how to do this, but I am willing to learn anything needed to accomplish making my vision reality. Sorry I can't give examples. I know I've seen it before, I just can't think of where. A: Use Javascript; I would recommend jQuery. Approach 1: The idea is to initially hide the contents of the tab, then show the corresponding one when a tab is clicked. There's already a JQuery Plugin for this: http://jqueryui.com/demos/tabs/ Approach 2: If you have huge contents, I would suggest to use AJAX to load the contents of each tab on demand. This way, all of the contents are not loaded in one go thus saving bandwidth and improving performance. However, this approach needs knowledge in server-side programming, in a way this is more advanced than Approach 1. A: There are plenty of examples of HTML/CSS layouts on the internet. Here are some resources: * *http://www.maxdesign.com.au/articles/css-layouts/ *http://www.code-sucks.com/css%20layouts/
{ "language": "en", "url": "https://stackoverflow.com/questions/7550410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript: Extract a date from a string? I have a string formatted as either Today 3:28AM Yesterday 3:28AM 08/22/2011 3:28AM What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY. Is something like this possible at all with Javascript? A: Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string: function strToDate(dateStr) { var dayTimeSplit = dateStr.split(" "); var day = dayTimeSplit[0]; var time = dayTimeSplit[1]; if (day == "Today") { day = new Date(); } else if (day == "Yesterday") { day = new Date(); day.setDate(day.getDate() - 1); } else { day = new Date(day); } var hourMinutes = time.substring(0, time.length -2); var amPM = time.substring(time.length -2, time.length); return new Date((day.getMonth() + 1) + "/" + day.getDate() + "/" + day.getFullYear() + " " + hourMinutes + " " + amPM); } Then you can call stroToDate to convert your date formats to a valid JavaScript Date: console.log(strToDate("Today 3:28AM")); console.log(strToDate("Yesterday 3:28AM")); console.log(strToDate("08/22/2011 3:28AM")); Outputs: Sun Sep 25 2011 03:28:00 GMT-0700 (Pacific Daylight Time) Sat Sep 24 2011 03:28:00 GMT-0700 (Pacific Daylight Time) Mon Aug 22 2011 03:28:00 GMT-0700 (Pacific Daylight Time) A: Obviously "Today" and "Yesterday" can never be transformed back to a real numeric date, for now it seems that what are you trying to do here is to save it as "Today" and "Yesterday", right? It appears that the dd/mm/yyyy hh:mmxx you specified is always separated by a space. so you can just split the string into two, and save the first part as your date. the javascript function: http://www.w3schools.com/jsref/jsref_split.asp As for how to transform from "Today" back to 26/09/2011 etc, you need to seek solution from the XML side. A: Here is a similar question: Javascript equivalent of php's strtotime()? Here is the linked article: http://w3schools.com/jS/js_obj_date.asp And the suggested solution: Basically, you can use the date constructor to parse a date var d=new Date("October 13, 1975 11:13:00"); A: There are a couple of ways you could do this. I will offer 2 of them. option1: If the day always at the beginning of the string you could capture the the first part by using a regular expression like /([a-z0-9]*)\s|([0-9]{1,})\/([0-9]{1,})\/([0-9]{1,})\s/ <- im not the best regex writer. option2: You could also do a positive look ahead if the time come immediately after the day (like your example above. Here is a link with the proper syntax for JS regex. http://www.javascriptkit.com/javatutors/redev2.shtml you can scroll down to lookaheads and see an example that should get you suared away there. A: var reTYD = /(today|yesterday|\d{1,2}\/\d{1,2}\/\d{4})/i; console.log( myString.match(reTYD) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7550416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does throw crash my program but return doesn't? I am trying to catch exceptions for my form client not being able to establish a connection to a server with this in the Connect callback: try { client.EndConnect(async); } catch (Exception e) { client.Close(); return; } This works fine but this behavior is encapsulated in to a class so I want to call throw; instead of return; so that the client class can handle it instead, like so: try { client.Connect(host, port); } catch { Console.WriteLine("Could not connect to: " + host + ":" + port.ToString()); } So why not just call throw; then? Well, for some reason if I call throw;, throw new Exception();, or basically anything other than return; the program failsfast. I'm really not sure what's causing this. I tried removing client.Close(); to see if it was the problem but nothing. If I don't call return; the program just immediately exits with no error. Anyone know what's going on here? Edit: I do not understand why I am getting downvoted so much. I showed how I am attempting to catch these exceptions and am asking why they are not working properly. I think the problem may be (not sure, just came up with this) because within the asynchronous callback, because it is a new thread in the ThreadPool, calling throw; does not do anything because, because it is not synchronous, there is nothing to throw back to and the application dies. Even with this knowledge, I am not sure how to solve this problem unless I put some sort of try-catch on the entire program. I suppose a solution could be just sticking with return; because there is nothing to throw back to (due to the asynchronous callback nature of the method) and instead raise an event indicating a failure of connection. Regardless, many thanks for the downvotes and helping me solve this problem. Oh wait... A: What's happening is that the EndConnect is not happening on the same thread as your BeginConnect. When EndConnect throws an exception, it is caught by the worker thread's unhandled exception handler, which fails fast (the other option is that it gets ignored and you never find out that your code isn't working). You have to come up with a way to tell your main form thread that the connect failed. A: As others have pointed out, you'll need to catch your exception one way or another to avoid program termination. For some ideas on how you can do that "globally", see How to catch ALL exceptions/crashes in a .NET app. Whether this is actually a good idea depends on the specific needs of your program... Relevant for WinForms: Can't tell based on your question alone, but in case this is actually a WinForms application, you may need to be cognizant of the difference in behavior of modal forms that throw exceptions, depending on whether the debugger is active or not. Let's say we have two forms - the second one is shown as a modal child of the first one: * *If application was started through debugger, second form is closed and and stack unwinding goes all the way to the first form's catch block (if any). *If application is started outside debugger, stack unwinding stops before second form is closed and generic exception message is displayed. The second form stays open and catch block in the first form is never reached.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bluetooth vs. Wifi for iPhone data transfer I'm working on adding sharing support to my iPhone app. Right now, I'm using Bonjour to create plain TCP connections over a wifi network. This works great, except that it turns out that many wifi networks in the real world (for example, those at Starbucks and other chains) forbid Bonjour publishing and discovery over their networks. So that limits the usefulness of sharing, since one of the use cases we imagined was that people could bump into each other where wifi was available and seamlessly share data with each other. Is Bluetooth a viable alternative for this? We're sending large amounts of data (PNG images) over the wire, so latency and throughput might be one issue. (I'm also interested in any other ways to make it easy to transfer data between two iPhone apps)
{ "language": "en", "url": "https://stackoverflow.com/questions/7550420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: how to transform lat & lon in a given angle? I have lat & lon that need to plot into floor map image. The problem is the floor map image's angle is not proportionate with the real world map. Anybody knows how to transform real lat & lon values in a given angle? UPDATES1 I have previous posted question which has relation with this post. Please take a look. plot real world coor to still image map A: Latitude, Longitude refers to a single point on earth's surface. It does not have an angle. If you are talking about the Location class however, you can get it's bearing from North, using if(location.hasBearing()) location.getBearing() If you are talking about a pair of lat, lon values, you can calculate the bearing using the bearingTo() api
{ "language": "en", "url": "https://stackoverflow.com/questions/7550427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: About translate="label" attribute in Magento, how does it work? I see in a config.xml file. I know that <template> block and this is the block hold the email template, and translate attribute which is present will be translate in the locale folder. But I don't know what is it exactly, and how does it work? translate="label", how does it work? <template> <email> <customer_active_account_email_template translate="label" module="customer"> <label>Active Customer</label> <file>customer_active.html</file> <type>html</type> </customer_active_account_email_template> </email> </template> A: When you see translate="label" module="customer", this tells Magento that it should pass the value in the <label> tag through the customer module's data helper's translate method before displaying it to the screen. In over simplified terms $label_value = (string) $node->label; echo Mage::helper('customer')->__($label_value); If the module attribute is not present, the core module is used. You may specify multiple tags to be translated with a space delimited string. translate="label type" As far as I know, this is supported in the System Configuration section, and the layout xml <action> nodes (for translating paramaters) only.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Which application layer should dispose DataContext (Silverlight WCF RIA) My silverlight application is design with 3 layers at server side * *Interface Layer - This layer contain only interface that bridge between silverlight client and RIA service. What I do in this layer is send ObjectContext (DataContext that generated from DAL) which create automatically in this layer and send it do Business Logic Layer *Business Logic Layer - All of class in this layer has overload constructor which is DataContext that send from Interface Layer. All logic is doing in this layer, such as, filter result, validate data, etc. *Data Access Layer - Pure Entity Framework. Current implementation of Business Layer is all class implement IDisposable interface which call Dispose method of DataContext inside it, as example below. MyServerInterfaceLayer.cs using (var myBusinesessLogicLayer = new MyBLL(this.DataContext1, this.DataContext2)) { myBusinesessLogicLayer.DoSomething(); } MyBLL.cs public void DoSomething() { // .. } public void Dispose() { // dispose all datacontext inside Dispose method of BLL this._dataContext1.Dispose(); this._dataContext2.Dispose(); } Currently I have problem when I have 2 class in Business Layer, MyBLL1 and MyBLL2. MyBLL1 need to call some method in MyBLL2 now I send DataContext from MyBLL1 to MyBLL2 after it out of scope of MyBLL2 it will dispose. So I want to know what layer should I call DataContext.Dispose?
{ "language": "en", "url": "https://stackoverflow.com/questions/7550438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change order of google calendar events fetched via Zend_Gdata_Query? When using the Zend_Gdata_Query library to fetch google calendar events using the example below my results are in the opposite order that I need. Is there a simple variation on the $query->setOrderby('starttime'); method that will achieve a list with the closest to now date at top and furthest in the future at the bottom? Code below taken from http://framework.zend.com/manual/en/zend.gdata.calendar.html $query = $service->newEventQuery(); $query->setUser('default'); // Set to $query->setVisibility('private-magicCookieValue') if using // MagicCookie auth $query->setVisibility('private'); $query->setProjection('full'); $query->setOrderby('starttime'); $query->setFutureevents('true'); Any help will be greatly appreciated. A: You just have to set descending order instead of ascending. $query->setSortOrder('d'); Valid values are ascending (with synonyms ascend and a) and descending (with synonyms descend and d). As seen in the gData API reference. A: $query->setSortOrder('a'); This will sort by current date to future date. a stands for ascending. if this does not do the trick, try: $query->setOrderby('starttime'); $query->setSortOrder('a'); //ascending
{ "language": "en", "url": "https://stackoverflow.com/questions/7550444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is IDataErrorInfo is firing multiple times? I am having an issue where IDataErrorInfo is getting fired multiple times. Transaction Class public class Transaction : INotifyPropertyChanged, INotifyPropertyChanging, IDataErrorInfo { private Double? _transAmount; [Column(DbType = "decimal(19,4)")] public Double? TransAmount { get { return _transAmount; } set { if (_transAmount != value) { NotifyPropertyChanging("TransAmount"); _transAmount = value; NotifyPropertyChanged("TransAmount"); } } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; // Used to notify that a property changed private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion #region INotifyPropertyChanging Members public event PropertyChangingEventHandler PropertyChanging; // Used to notify that a property is about to change private void NotifyPropertyChanging(string propertyName) { if (PropertyChanging != null) { PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } } #endregion #region Data Validation public string Error { get { return null; } } public string this[string property] { get { switch (property) { case "TransAmount": if (TransAmount != null) { double value; bool valid = double.TryParse(TransAmount.ToString(), out value); if (!valid) { return TransAmount.ToString() + " is not a valid number"; } else if (value <= 0) { return "Dollar amount must be greater than $0.00"; } } return null; default: return null; } } } #endregion } and the xaml <toolkit:PhoneTextBox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" x:Name="txtAmount" Width="Auto" Text="{Binding TransAmount, Mode=TwoWay, NotifyOnValidationError=True, StringFormat=\{0:c\}, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" BindingValidationError="txtAmount_BindingValidationError" InputScope="CurrencyAmount" GotFocus="txtAmount_GotFocus" LostFocus="txtAmount_LostFocus"> </toolkit:PhoneTextBox> I'm not sure of the pattern, but validation method is getting hit 2-3 times? Why? Edit 1 The value TransAmount is being set in the txtAmount_LostFocus event. Edit 2 Added WP7 tag A: The trick is the following. Use DataErrorValidationRule instead of ValidatesOnDataErrors=True. <TextBox> <TextBox.Text> <Binding Path="..." UpdateSourceTrigger="LostFocus" NotifyOnValidationError="True"> <Binding.ValidationRules> <DataErrorValidationRule ValidatesOnTargetUpdated="False"/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> Refer to this article https://social.msdn.microsoft.com/forums/vstudio/en-US/099164f8-72aa-4c59-a7b6-7ccbd56702ce/idataerrorinfo-validation-called-twice
{ "language": "en", "url": "https://stackoverflow.com/questions/7550448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to color the background of the application in android I added a color folder, with this xml file: <?xml version="1.0" encoding="utf-8"?> <item xmlns:android="http://schemas.android.com/apk/res/android"> <color name="orange">#FF9912</color> </item> But when I put as the value in the screen_display.xml that i created in the values folder. It gives me a mistake: <?xml version="1.0" encoding="utf-8"?> <resources> <style name="MyTheme.Background" parent="@android:style/Theme"> <item name="android:windowNoTitle"> true</item> <item name="android:windowFullscreen">true</item> <item name="android:windowBackground">@colors/color/orange</item> </style> </resources> UPDATE <activity android:name=".EasyLearningActivity" android:launchMode="singleTask" android:alwaysRetainTaskState="true" android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden" android:theme="MyTheme.Background"...shows mistake, saying that Strying type inst allowed :( > A: pls chk out this in values folder create two xml file first one color.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="orange">#FF9912</color> </resources> styles.xml <?xml version="1.0" encoding="utf-8"?> <resources> <style name="MyTheme.Background" parent="@android:style/Theme"> <item name="android:windowNoTitle"> true</item> <item name="android:windowFullscreen">true</item> <item name="android:windowBackground">@color/orange</item> </style> </resources> In manifest file: <activity android:name=".EasyLearningActivity" android:launchMode="singleTask" android:alwaysRetainTaskState="true" android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden" android:theme="@style/MyTheme.Background"></activity> A: It's @color, not @colors... and are you setting the android:theme attribute for your application tag in the manifest to use MyTheme.Background? A: You can't use directly string for android:theme. You need to include one of the styles like **@style/**MyTheme.Background. A: Thanks for the color.xml , finally after 7 hours of research and lots of frustration I now have a purple action bar like I wanted. <color name="orange" type="color">#FF9912</color> <color name="red" type="color">#FF0000</color> <color name="blue" type="color">#FF33B5E5</color> <color name="purple" type="color">#FFAA66CC</color> <color name="green" type="color">#FF99CC00</color> <color name="darkblue" type="color">#FF0099CC</color> <color name="darkpurple" type="color">#FF9933CC</color> <color name="darkgreen" type="color">#FF669900</color> <color name="darkorange" type="color">#FFFF8800</color> <color name="darkred" type="color">#FFCC0000</color> <!--Black #000000 (0,0,0) White #FFFFFF (255,255,255) Red #FF0000 (255,0,0) Lime #00FF00 (0,255,0) Blue #0000FF (0,0,255) Yellow #FFFF00 (255,255,0) Cyan / Aqua #00FFFF (0,255,255) Magenta / Fuchsia #FF00FF (255,0,255) Silver #C0C0C0 (192,192,192) Gray #808080 (128,128,128) Maroon #800000 (128,0,0) Olive #808000 (128,128,0) Green #008000 (0,128,0) Purple #800080 (128,0,128) Teal #008080 (0,128,128) Navy #000080 (0,0,12--> <!--color name="orange" type="color">#FFFFBB33</color--> <!--<color name="red" type="color">#FFFF4444</color-->
{ "language": "en", "url": "https://stackoverflow.com/questions/7550449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I make the text edges in the images smooth? How can I make the text edges in the images smooth? Here's the image: A: If you're thinking of anti aliasing, you can typecast Graphics to Graphics2D then use g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);. You can do this after you draw the lines. A: The above solution from Kevin Hikaru Evans should works, maybe you missed something. Graphics2D g2=(Graphics2D)g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g2.drawString("SCQSCQSCQ",x,y); A: Try this (quickly, crudely) adapted example.. import java.awt.*; import java.awt.image.BufferedImage; import java.awt.font.*; import java.awt.geom.*; import javax.swing.*; import javax.imageio.ImageIO; import java.io.File; class PictureText { public static BufferedImage getImage(Area textOutline) { Rectangle bounds = textOutline.getBounds(); System.out.println(bounds); int width = (2*(int)bounds.getX())+(int)bounds.getWidth(); int height = (2*(int)bounds.getY())+(int)bounds.getHeight(); BufferedImage bi = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB); Color outline = new Color(0,0,0,255); Graphics2D g = bi.createGraphics(); g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(1.5f)); g.setColor(outline); g.draw(textOutline); showImage(bi); return bi; } public static void showImage(Image image) { JLabel textLabel = new JLabel( new ImageIcon(image)); textLabel.setBackground(Color.WHITE); textLabel.setOpaque(true); JPanel gui = new JPanel(new GridLayout(0,1,5,5)); gui.add(textLabel); JOptionPane.showMessageDialog(null,gui); } public static void main(String[] args) throws Exception { AffineTransform shrinkTransform2 = AffineTransform.getScaleInstance(.5,.5); AffineTransform shrinkTransform4 = AffineTransform.getScaleInstance(.25,.25); final BufferedImage originalImage = new BufferedImage( 260, 50, BufferedImage.TYPE_INT_ARGB); GradientPaint gp = new GradientPaint( 0f,0f,Color.GRAY.brighter(), 0f,22f,Color.GRAY.brighter().brighter(),true); Graphics2D g0 = originalImage.createGraphics(); g0.setPaint(gp); g0.fillRect(0,0,300,100); int width = originalImage.getWidth(); int height = originalImage.getHeight(); final BufferedImage textImage = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = textImage.createGraphics(); FontRenderContext frc = g.getFontRenderContext(); Font font1 = new Font( //"Wide Latin" //"Pythagoras" "Denmark" ,0,48); GlyphVector gv1 = font1.createGlyphVector( frc, "The quick brown fox.."); Shape shape1 = gv1.getOutline(0,0); int y = (int)shape1.getBounds().getHeight()+2; Shape shapea = gv1.getOutline(6,y); Area area1 = new Area(shapea); Area area2nd = area1.createTransformedArea(shrinkTransform2); Area area4th = area1.createTransformedArea(shrinkTransform4); ImageIO.write(getImage(area1),"png",new File("text-image.png")); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7550454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Checkbox behaviour modification with javascript I have got this group of checkboxes that behave like radio buttons. I need some help in letting the user allow to uncheck a checkbox too, so there can be no selection within the group. <label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label> <label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label> <label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label> <label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label> $(".chb").each(function() { $(this).change(function() { $(".chb").attr('checked',false); $(this).attr('checked',true); }); }); A: $(".chb").change(function() { $(".chb").parent().siblings() .find('input').prop('checked', false); }); Or even better: var $inputs = $(".chb"); $inputs.change(function() { $inputs.not(this).prop('checked', false); }); And here's the fiddle: http://jsfiddle.net/zjJKc/
{ "language": "en", "url": "https://stackoverflow.com/questions/7550455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installing ExtJS I am new to ExtJS. I tried installing it as per the steps given here. But I am getting one error while running this command. sencha create jsb -a http://localhost:8080/helloext/index.html -p app.jsb3 Error msg : C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\helloext>sencha create jsb -a http://localhost:8080/helloext/index.html -p app.jsb3 'sencha' is not recognized as an internal or external command, operable program or batch file. What is the problem ? PS : I already done with the prior steps of installing Apache Server and unzipping ExtJS SDK. Thanks. A: Windows is not finding the sencha executable. Are you sure you downloaded the Sencha Tools SDK? (Current version is 1.2.3beta). The link from that tutorial shows a page with an obvious link to download the ExtJS library, and less obvious link for the Sencha SDK. Try downloading and installing this from here. Then see if typing "sencha" on the command line does something sensible. A: I dont have time to reaad te tutorial but I will let you know how I get started using extjs. I download the library and extract the folder. Name the folder extjs. Then in my webroot or whatever you prefer I make a directory called lib and place extjs inside of it. Then when i create a html document I reference the library by using <script type="text/javascript" src="/lib/extjs/ext-all.js></script>. This is how you can call it up in order to use it. If you have a "app/js" file simply reference it after the example I gave you above so that it is loaded after the ext-all.js file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Searchable jQuery list view I'm looking for a searchable list view widget for jquery. Something like the inbox email list in the iPad mail app. Any suggestions?
{ "language": "en", "url": "https://stackoverflow.com/questions/7550463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: session with no cookies I ran into a situation that I brought onto myself by disabling cookies: session state wasn't working as expected. How do you check to see that the user has cookies enabled in an http module? Thanks. A: Set a cookie and then redirect them to a page inside the same site. If you don't get a cookie back, then they don't have cookies enabled. You can track them through this adventure by embedding a code in the URL or submitting a form. Assuming you've rigged the page to set a cookie already, you can also use JavaScript to retrieve a "did you send a cookie" page. Then you can look at what you got back to see if the browser returned the cookie you sent it. A: If you have cookies disabled on your browser , then you can create a hidden field in your html page which will store your cookie value. < input type='hidden' name='sessionid' > Retrieve this value when you move to next page .
{ "language": "en", "url": "https://stackoverflow.com/questions/7550465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i see Timestamps in Unix files Files in UNIX filesystems have 3 types of timestamps: Access, Modify, and Change. In order to investigate this, I created a file and I want to look at timestamps . Anybody knows how can i look the different timestamps. Then, which commands timestamps. A: Use stat command: stat filename A: to change the atime and mtime, use the touch command: touch --time=atime -t 198805232211.45 touch --time=mtime -t 205012300945.30
{ "language": "en", "url": "https://stackoverflow.com/questions/7550472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: socket programming with implement & interface I tried this tutorial with socket programming. BUT, it is unable to send message to server when doing socket programming with implement & interface. Do you think that i can do socket programming with implement & interface?? There is also no "hello" debug message. private class OnReadyListener implements MyCustomDialog.ReadyListener { @Override public void ready(String name) { try { DatagramSocket clientSocket = new DatagramSocket(); String serverHostname = new String("192.168.1.12"); InetAddress IPAddress = InetAddress.getByName(serverHostname); byte[] sendData = new byte[1024]; String sentence = "hello"; Log.d(TAG, "OnReadyListener ready" + " " + sentence ); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); clientSocket.close(); } catch (UnknownHostException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } A: here is code implemented in different form than yours, but it is pure socket programming and works well. http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/
{ "language": "en", "url": "https://stackoverflow.com/questions/7550473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reset the form data on unload I'm using this code: if(isset($_POST['btitle'])) { if(count($errors) > 0) { foreach($errors as $error) $errContent .= "<li>".$error; echo notification( $errContent, FALSE, "The following errors were encountered:" ) . "<div style='margin-bottom: 10px;'></div>"; } else { echo notification( "<li>New form added!", TRUE, "Success:" ) . "<div style='margin-bottom: 10px;'></div>"; } } When I type something in the input named 'btitle' and hit the submit button, everything is fine, until I refresh the page - it should loose the data and start again after refreshing, but it keep saying "Success:" even if the 'btitle' input is empty. What am I doing wrong? A: you need to redirect the user to the same page and loose the post data. header("Location: file.php?success=true");//or ?errors[]=blabla exit(); now, in the same page (file.php) you need to: if(isset($_GET['success']) && $_GET['success'] == true){ //handle true }else if(/* here you can ask about errors or what ever */){ } BTW, if you don't do it, the entire submitting form will be act again like you resubmit it. for instance, if you insert data to the database, it will be insert over and over again when you refresh the page, so if you redirect as suggested, you loose the posted data and now you can show the errors or success. A: When you hit refresh, your browser resends POST data to the page. This question has been asked many times, for instance here and here. Take a look at the answers to some of those questions to get an idea of what you can do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using SQL to retrieve the most popular queries in a dataset I have a table of data with fields: search, search_location, num_searches. I want to put together a SELECT statement that will generate a list of the 100 most popular search_locations, determined by the SUM() of the num_searches field for all searches with the same search_location (regardless of the value of the search field). How can I accomplish this? A: You can use a GROUP BY, a method that reduces a table by grouping all rows that share some of the same values. SELECT search_location, SUM(num_searches) as total_searches FROM my_table GROUP BY search_location ORDER BY total_searches DESC LIMIT 100;
{ "language": "en", "url": "https://stackoverflow.com/questions/7550476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: put text to div with dropdown option I have the following code and its not working. I want to put the selected text to my selected-locations div. Any ideas? Thanks! <select name='available_locations' class='select-location'> <option value='Germany'>Germany</option> <option value='Venice'>Venice</option> <option value='Spain'>Spain</option> </select> <div id='selected-locations'> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script type='text/javascript'> $(document).ready(function() { $('.select-location').change(function(){ var location = $( this ).attr( 'value' ); alert( location ); //new_text = $('#selected-locations').val() + location; $('div.selected-locations').text( location ); }); }); </script> A: You need to read up on css selectors and jQuery selectors $('div.selected-locations').text( location ); should be $('div#selected-locations').text( location ); OR <div id='selected-locations'> </div> shoould be <div class='selected-locations'> </div> A: You can do this $('.select-location').change(function(){ var location = $('.select-location option:selected').val(); $('div#selected-locations').text(location); }); Working example: http://jsfiddle.net/jasongennaro/F3A62/ A few things needed to change with your code: * *change $('div.selected-locations') to $('div#selected-locations') ... period to hash *use the option:selected *use the val() A: use $('#selected-locations').text(location ); You need to use # as selected-locations is a id not a css class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use to_sentence with an AR collection I have User.all, which returns 3 results. How can I make it so I can render each result to something like: <a href="path_to_user_foo_here">Foo</a>, <a href="path_to_user_bar_here">Bar</a>, and <a href="path_to_user_foobar_here">Foobar</a> Which when rendered in the browser, will display as: Foo, Bar, and Foobar I know about the to_sentence helper. But not very sure how to execute this, since User.all returns 3 hash objects. I can use .map(&:first_name), but how will I be able to provide the route path in the link_to method. Looking for an approach that works. A: I think you're looking for something like this. (answer updated) In a helper: module ApplicationHelper ... include ActionController::UrlWriter def generate_user_links_sentence links = User.all.collect do |user| link_to user.first_name, user_path(user) end links.to_sentence end ... end # Example: <%= generate_user_links_sentence %> You can separate out the generation logic into your controller if you so wish, but it's difficult enough accessing route paths from a helper, let alone the controller. There may be a better way to do this in a view, but this is all I can really think of right now. Update: Just in a view: <%= User.all.collect{|u| link_to u.first_name, user_path(u)}.to_sentence %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7550486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any case for which returning a structure directly is good practice? IMO all code that returns structure directly can be modified to return pointer to structure. When is returning a structure directly a good practice? A: Modified how? Returning a pointer to a static instance of the structure within the function, thus making the function non-reentrant; or by returning a pointer to a heap allocated structure that the caller has to make sure to free and do so appropiately? I would consider returning a structure being the good practice in the general case. A: The biggest advantage to returning a complete structure instead of a pointer is that you don't have to mess with pointers. By avoiding the risks inherent with pointers, especially if you're allocating and freeing your own memory, both coding and debugging can be significantly simplified. In many cases, the advantages of passing the structure directly outweigh the downsides (time/memory) of copying the entire structure to the stack. Unless you know that optimization is necessary, no reason not to take the easier path. A: I see the following cases as the ones I would most commonly opt for the passing structs directly approach: * *"Functional programming" style code. Lots of stuff is passed around and having pointers would complicate the code a lot (and that is not even counting if you need to start using malloc+free) *Small structs, like for example struct Point{ int x, y; }; aren't worth the trouble of passing stuff around by reference. And lastly, lets not forget that pass-by-value and pass-by-reference are actually very different so some classes of programs will be more suited to one style and will end up looking ugly if the other style is used instead. A: These other answers are good, but I think missingno comes closest to "answering the question" by mentioning small structs. To be more concrete, if the struct itself is only a few machine words long, then both the "space" objection and the "time" objection are overcome. If a pointer is one word, and the struct is two words, how much slower is the struct copy operation vs the pointer copy? On a cached architecture, I suspect the answer is "none aat all". And as for space, 2 words on stack < 1 word on stack + 2 words (+overhead) on heap. But thes considerations are only appropriate for specific cases: THIS porion of THIS program on THIS architecture. For the level of writing C programs, you should use whichever is easier to read. A: If you're trying to make your function side-effect free, returning a struct directly would help, because it would effectively be pass-by-value. Is it more efficient? No, passing by reference is quicker. But having no side effects can really simplify working with threads (a notoriously difficult task). A: There are a few cases where returning a structure by value is contra-indicated: 1) A library function that returns 'token' data that is to be re-used later in other calls, eg. a file or socket stream descriptor. Returning a complete structure would break encapsulation of the library. 2) Structs containing data buffers of variable length where the struct has been sized to accommodate the absolute maximum size of the data but where the average data size is much less, eg. a network buffer struct that has a 'dataLen' int and a 'char data[65536]' at its end. 3) Large structs of any typedef where the cost of copying the data becomes significant, eg: a) When the struct has to be returned through several function calls - multiple copying of the same data. b) Where the struct is subsequently queued off to other threads - wide queues means longer lock times during the copy-in/copy-out and so increased chance of contention. That, and the size of the struct is inflicted on both producer and consumer thread stacks. c) Where the struct is often moved around between layers, eg. protocol stack. 4) Where structs of varying def. are to be stored in any array/list/queue/stack/whateverContainer. I suspect that I am so corrupted by c++ and other OO languages that I tend to malloc/new almost anything that cannot be stored in a native type Rgds, Martin
{ "language": "en", "url": "https://stackoverflow.com/questions/7550495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to compare encrypted password in sql I already got my password encrypted and store it in database but now I want to compare the encrypted value to the password that a user type upon loading a page. Consider this code: string userName = txtusername.Text; string password = txtpassword.Text; Encryptor en = new Encryptor(EncryptionAlgorithm.Rc2, CreateRandomPassword(7)); password = en.Encrypt(password); DataTable dt = uMManager.ValidateUser(userName, password); CreateRandomPassword Method private static string CreateRandomPassword(int passwordLength) { string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-"; char[] chars = new char[passwordLength]; Random rd = new Random(); for (int i = 0; i < passwordLength; i++) { chars[i] = allowedChars[rd.Next(0, allowedChars.Length)]; } return new string(chars); } Encryptor Class public class Encryptor { EncryptEngine engin; public byte[] IV; public Encryptor(EncryptionAlgorithm algID, string key) { engin = new EncryptEngine(algID, key); } public EncryptEngine EncryptEngine { get { return engin; } set { engin = value; } } public string Encrypt(string MainString) { MemoryStream memory = new MemoryStream(); CryptoStream stream = new CryptoStream(memory, engin.GetCryptTransform(), CryptoStreamMode.Write); StreamWriter streamwriter = new StreamWriter(stream); streamwriter.WriteLine(MainString); streamwriter.Close(); stream.Close(); IV = engin.Vector; byte[] buffer = memory.ToArray(); memory.Close(); return Convert.ToBase64String(buffer); } } I made a local method to generate random string for RC2 encryption. EncryptionAlgorithm is a Enums for the types of encryption. Now how can I compare 'password' to the password field in my database to check if the credential is correct A: You can't check if the credential is correct, since you've encrypted it with a key you've thrown away. If you store the key along with the password, the encryption serves no purpose. If you don't, you can't verify. Instead of trying to create a new way to store passwords, why not use one of the ways that's known to work? A: Don't encrypt passwords. Hash them. Encryption allows for retrieval of the plaintext password, which is a Bad Thing. Hashing still allows you to check if what the user inputs matches with what he did before. A: Here is the flow of the program: * *When user register new account -> You encrypt his password -> Save it in database *When user login -> Encrypt input password -> Get user with password in database -> If user not null -> Login successful -> Else -> Login fail A: it looks like you are using every time a random key to encrypt your password so if u encrypt "test" the first time and then u encrypt "test" a second time. the result of the two encryption is not the same. u should simply use a hash algorithm
{ "language": "en", "url": "https://stackoverflow.com/questions/7550496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Configure eclipse osgi log I am using eclipse osgi jar. How to redirect the log generated by osgi to a file? Whenever I start the osgi framework, it generates a log like 1317008078357.log. How to redirect this log to a custom file. Do I need to use log4j as a osgi bundle? what will be the log4j.xml configuration ? log file contains: !SESSION 2011-09-26 11:34:38.232 ----------------------------------------------- eclipse.buildId=unknown java.version=1.6.0_26 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US Command-line arguments: -configuration D:/CommonNBI/Trunck/release_structure/server/nbi/snmp/conf -console !ENTRY org.eclipse.osgi 2 0 2011-09-26 11:34:44.029 !MESSAGE While loading class .... may not be fully initialized. !STACK 0 org.osgi.framework.BundleException: State change in progress for bundle .. A: Eclipse (Equinox) uses his own logger. To configure it you can define the logger options in config.ini: * *osgi.logfile file name *eclipse.log.level sets the level used when logging messages to the eclipse log. *eclipse.log.backup.max the max number of backup log files to allow. *eclipse.log.size.max the max size in Kb that the log file is allowed to grow. more details in Eclipse Help (http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html) also here: Logging in Eclipse/OSGi plugins and here: http://www.eclipsezone.com/eclipse/forums/t99588.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7550503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Override Android Back Button A little info as to why I am attempting to do this: I am using ActivityGroups to open an activity from a tabHost activity and have that new activity stay under the tabs. That part i've got. But when in that new activity, if I use the back button it takes me right out of the tabs activity so I have to click a few times to get back to where I was. Is there a way to set the back button to go to a specific activity rather than killing the current activity window? A: I believe you should be able to do something like this: @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { // start new Activity here } return super.onKeyDown(keyCode, event); } But overriding the expected functionality of the back button is not advisable. A: In general, I would advise against that because it breaks the UX. The user expects the back button to kill the entire window, especially since you are using the tabhost. To the user, the entire bunch (tabs and all) is a single activity that he wants to exit when he hits the back button. If you still want to do it, refer to #onBackPressed(). It is called when the activity has detected the user's press of the back key. The default is to finish the activity, but you can make it do whatever you want. I advise care and caution. You might find some inspiration from here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Can I post a comment on a status programmatically? I've been reading up on the new documentation, and I've found out how to post a status as a user, and how to read a status and all it's comments, but I haven't found a way yet to post a comment. My goal is to have the backend of my application mirror exactly the interaction on Facebook, such that if a user (whose access token we have) comments on a post in our iOS app's custom UI, our server can update the mirrored post on Facebook by adding the comment as that user. It's sounds like it's possible from what I've read, but I can't figure out exactly how to do it from the documentation. Can someone explain more clearly how to post comments, and what access privileges I need to do so? A: You need to have publish_stream permissions from the user and then you just issue an HTTP POST to https://graph.facebook.com/postID/comments?access_token=... with a "message" post parameter equal to the comment you want to post. Its documented here under the section titled "comments".
{ "language": "en", "url": "https://stackoverflow.com/questions/7550506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple Nivo slider images not loading on IE I'm using this plugin: http://wordpress.org/extend/plugins/simple-nivo-slider/ and when viewed on firefox & chrome the images load but on ie only the navigational arrows and navigation bullets show. here's the site edit: solved it by adding width and height to #slider A: solved it by adding width and height to #slider
{ "language": "en", "url": "https://stackoverflow.com/questions/7550521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: That text area of nullness I have a strange problem and it's been frustrating me for the past few hours. I can't seem to find anything related; perhaps I'm not being specific enough, as I'm not sure how to word it correctly, or it's a strangely unique problem. There's a form a user fills in to update their account information, everything works as it should, except for one text area. This text areas' (which is bound to the property Comments of UserInfo) value becomes null once the form is POSTed. The Comments property is the only property which is null. When It Occurs A) No existing value, user inputs a value, property is null. B) Existing value, user does/doesn't change something/anything, property is null. I'll only include the relevant code to keep things clean and simple. Hopefully it's enough. Controller Actions public ActionResult Edit_Information(long id) { // Get user info from the database. // Return the view with the user info from the DB etc. } [HttpPost] public ActionResult Edit_Information(long id, UserInfo userInfo) { if (!this.ModelState.IsValid) { // Invalid return View(userInfo); } // Update the information in the DB. // Redirect the user back to their account. } Razor View HTML <div style="width: 700px; margin-left: auto; margin-right: auto; text-align: left"> @Html.ValidationMessageFor(x => x.Comments) </div> @Html.Partial("~/Views/Shared/_EditorSmiles.cshtml") @Html.TextAreaFor(x => x.Comments, new { @class = "EditorArea profile-comments" }) UserInfo Model [Validator(typeof(UserInfoValidator))] public class UserInfo { public string Comments { get;set; } } Yes, I do use FluentValidation on the model. I removed it to see if it was the cause, but it wasn't. Things I've Tried * *On the POST action, I've used FormCollection formCollection instead of UserInfo userInfo. *Threw an exception on the POST action to prove the value becomes null when posted. *Created a new property with a different name. *Manually gave the property a value before returning the view. The value became null when it was posted. *Manually gave the property a value in the POST action to prove it wasn't the DB or SQL. This worked. *Removed the Fluent Validation attribute from the model (as said above). *Used [Bind(Prefix = "")] before UserInfo userInfo. This didn't change anything. It's frustrated me to the point where I have to ask: What the hell is going? Am I doing something wrong? I must be overlooking something. There is another text area on the page which works as it should. It's just the text area for Comments which always returns null values regardless of the conditions. A: The form was being wrapped like so: Html.BeginWindow(); Html.BeginForm("edit_information", "user", FormMethod.Post, new { id = "profile" }); <!-- other stuff goes in between here --> Html.EndForm(); Html.EndWindow(); Html.BeginWindow() generates a table (a window) which is wrapped around the form. This had obviously caused parts of the form not to be POSTed properly. Changed to: Html.BeginForm("edit_information", "user", FormMethod.Post, new { id = "profile" }); Html.BeginWindow(); <!-- other stuff goes in between here --> Html.EndWindow(); Html.EndForm(); Bam! It worked again. This never occurred to me as I've done it before without any problems. I'm glad it's fixed. We all make mistakes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to make alarm initiate even after restart device? How to make my calendar events alarm wake up even after restarting the mobile? (i.e) if the current time is 10am; i'm setting alarm for 10.05am and now(10am) if i restart my device, the alarm should ring on 10.05am. How to achieve it? I have already created alarm for my calendar events. But if i restart my device, the alarm is ringing once i restarted itself. But all other queued alarms are cancelled. Any Help is appreciated and thanks in advance... A: Well you can use BroadCaste Reciever, becuase device gets a broadcaste when device switched on, so you can register for that broadcaste and in its reciever you can schedule your alarm.. here is an example how you can do it, http://www.androidcompetencycenter.com/2009/06/start-service-at-boot/ A: Put "android.intent.action.BOOT_COMPLETED" as an intent filter in a BroadcastReceiver, then you can receive the phone being powered on and schedule the alarm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Check if Tomcat and MySQL are already installed on machine How can I check using Java if Tomcat and MySQL are already installed on machine? If it is installed I have to disable those options in my installer. A: If Tomcat is installed as a service on Windows, you can check the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Apache Software Foundation\Tomcat\[version]\InstallPath. To read the registry from Java, you would need to use something like JNA, the methods Advapi32Util.registryGetKeys() and Advapi32Util.registryGetStringValue() can help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I send an email with autoGenerateEditButton set to True? We would like an email sent out when an update is made. How can I do this when autogenerateEditButton of gridview set to true? Here is an example: <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False" DataKeyNames="ID" AllowPaging="True" OnRowDataBound="gvRowDataBound" **onRowUpdated="btnSendEmail_Click"** AutoGenerateEditButton="True"> <Columns> <asp:BoundField DataField="date_stamp" HeaderText="Entry Date" ReadOnly = "true" SortExpression="date_stamp" /> </Columns> </asp:GridView> My email code is on codebehind called sub btnSendEmail_Click(). Protected Sub btnSendEmail_Click(ByVal sender As Object, ByVal e As GridViewUpdatedEventArgs) Dim cnn As SqlConnection 'Dim param As SqlParameter Dim cmd As SqlCommand Dim sqlStr As String = "" Dim sqlStrD As String = "" Dim connStr As String = ConfigurationManager.ConnectionStrings("Database_DBConnectionString").ConnectionString more - not posted more - not posted A: You will need to have btnSendEmail_Click() handle the GridView's RowEditing event. In your ASP code, you should have: <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" OnRowEditing="btnSendEmail_Click" ... AutoGenerateEditButton="True"> Then in your codebehind: Protected Sub btnSendEmail_Click(ByVal sender As Object, ByVal e As GridViewEditEventArgs) '...code to send email... A: Instead of having a 'Send Email' button and rely on the user to manually click it, why not create a hook to handle the Gridview's RowUpadated event? void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e) { // Indicate whether the update operation succeeded. if(e.Exception == null) { int index = GridView1.EditIndex; GridViewRow row = GridView1.Rows(index); //example to pull the data from a cell to send it to your function SendEmail(row.Cells(0).Text); Message.Text = "Row updated successfully. Email Sent!"; } else { e.ExceptionHandled = true; Message.Text = "An error occurred while attempting to update the row. No email sent."; } } VB code: Private Sub GridView1_RowUpdated(sender As Object, e As GridViewUpdatedEventArgs) ' Indicate whether the update operation succeeded. If e.Exception Is Nothing Then Dim index As Integer = GridView1.EditIndex Dim row As GridViewRow = GridView1.Rows(index) 'example to pull the data from a cell to send it to your function SendEmail(row.Cells(0).Text) Message.Text = "Row updated successfully. Email Sent!" Else e.ExceptionHandled = True Message.Text = "An error occurred while attempting to update the row. No email sent." End If End Sub EDIT to comment I used the parameter as an example to show you how to pull the value from the gridview if you wanted to pass it. Something like this: SendEmail Protected Sub SendEmail(ByVal RowNumber as Integer) Try Const ToAddress As String = "ThierEmail@domain.com" Const FromAddress As String = "YourEmail@domain.com" Dim Subject As String = "Row Updated" Dim mm As New MailMessage(FromAddress, ToAddress) mm.Subject = Subject mm.IsBodyHtml = False mm.Priority = MailPriority.High mm.Body = String.Format("Row ID {0} was updated.",RowNumber) 'Send the email Dim smtp As New SmtpClient() smtp.Send(mm) Catch ex As Exception 'You should catch your error here Throw ex End Try End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7550540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Symfony2 app/console --env throws no envirorment name I'm working with symfony2 and while migrating from Beta2 version to the current one I messed up with some environment configuration. My trouble here is when I run php app/console --env I get the following error [InvalidArgumentException] The file "MyWebRoute\symfony-standard\app/config/config_.yml" does not exist. How should I get this working? What should the proper configuration be? A: That is b/c you have to specify your environment. Available by default are "prod" and "dev". So if you want to have console do something regarding your development environment you do ./console --env=dev [...] The error message stems from console trying to load the appropriate configuration file, which is config_dev.yml for "dev" and config_prod.yml for "prod" and config_.yml for ""; but that one doesn't exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Query without Temporary Table I have written a query which works great on my local SQL Server 2005. I uploaded the query to my hosting server and somehow they say that temporary table creation is disabled on their server. My query looks like this create table #tmp ( srno int identity (1,1) , orderid int, orderdate datetime, product_code varchar(255), product_name varchar(255), shipping_cost decimal(18,2) ) insert into #tmp (orderid, orderdate, product_code, product_name, shipping_cost) (select distinct ord.orderid, ord.orderdate, odn.productcode, odn.productname, ord.totalshippingcost from OrderNew ord inner join order_detailsnew odn on ord.orderid = odn.orderid) declare @rowcount int, @flag int, @orderid int set @rowcount = (select @@ROWCOUNT) set @flag = 0 while (@flag <@rowcount) begin set @orderid = (select orderid from #tmp where srno = @flag + 1) if exists (select 1 from #tmp where orderid = @orderid ) begin update #tmp set shipping_cost = 0.0 where srno IN (select srno from #tmp where orderid = @orderid AND srno NOT IN (SELECT TOP 1 srno FROM #tmp where orderid = @orderid)) end set @flag = @flag+1 end select * from #tmp drop table #tmp So not sure if this query can be written without a temporary table, joins etc not sure if it will work ? Any advise ? A: I presume this query is to feed into a report which is why you only want the total shipping cost once, while you don't need a temp table for this for reference you can always do this instead if you need to: DECLARE @tmp TABLE ( srno int identity (1,1) , orderid int, orderdate datetime, product_code varchar(255), product_name varchar(255), shipping_cost decimal(18,2) ) and use @tmp rather than #tmp But you shouldn't need a temp table for this, see below: SELECT ord.orderid, ord.orderdate, odn.productcode, odn.productname, ord.totalshippingcost FROM OrderNew AS ord INNER JOIN order_detailsnew AS odn ON odn.orderid = ord.orderid WHERE odn.productcode = (SELECT MIN(productcode) FROM OrderNew AS odn2 WHERE odn2.orderid = ord.orderid) UNION ALL SELECT ord.orderid, ord.orderdate, odn.productcode, odn.productname, 0.0 AS totalshippingcost FROM OrderNew AS ord INNER JOIN order_detailsnew AS odn ON odn.orderid = ord.orderid WHERE odn.productcode > (SELECT MIN(productcode) FROM OrderNew AS odn2 WHERE odn2.orderid = ord.orderid) ORDER BY ord.orderid, ord.orderdate, odn.productcode Works fine for me with the following test script: DECLARE @ord TABLE ( orderid int, orderdate datetime, totalshippingcost decimal(18,2) ) DECLARE @odn TABLE ( orderid int, productcode varchar(255), productname varchar(255) ) INSERT INTO @ord VALUES(1, CAST('20110101' AS DATETIME), 50.25) INSERT INTO @ord VALUES(2, CAST('20110105' AS DATETIME), 78.15) INSERT INTO @ord VALUES(3, CAST('20110112' AS DATETIME), 65.50) INSERT INTO @ord VALUES(4, CAST('20110112' AS DATETIME), 128.00) INSERT INTO @odn VALUES(1, 'aa', 'AAA') INSERT INTO @odn VALUES(1, 'bb', 'BBB') INSERT INTO @odn VALUES(1, 'cc', 'CCC') INSERT INTO @odn VALUES(2, 'aa', 'AAA') INSERT INTO @odn VALUES(2, 'bb', 'BBB') INSERT INTO @odn VALUES(3, 'bb', 'BBB') INSERT INTO @odn VALUES(3, 'cc', 'CCC') INSERT INTO @odn VALUES(4, 'cc', 'CCC') And my results: Result Set (8 items) orderid | orderdate | productcode | productname | totalshippingcost 1 | 01/01/2011 00:00:00 | aa | AAA | 50.25 1 | 01/01/2011 00:00:00 | bb | BBB | 0.00 1 | 01/01/2011 00:00:00 | cc | CCC | 0.00 2 | 05/01/2011 00:00:00 | aa | AAA | 78.15 2 | 05/01/2011 00:00:00 | bb | BBB | 0.00 3 | 12/01/2011 00:00:00 | bb | BBB | 65.50 3 | 12/01/2011 00:00:00 | cc | CCC | 0.00 4 | 12/01/2011 00:00:00 | cc | CCC | 128.00 edit: I wasn't happy with the above solution, here's a uch faster and more elegant way of doing it: SELECT ord.orderid, ord.orderdate, ord.productcode, ord.productname, CASE WHEN row_no = 1 THEN ord.totalshippingcost ELSE 0.0 END AS totalshippingcost FROM ( SELECT ROW_NUMBER() OVER(PARTITION BY ord.orderid ORDER BY ord.orderid, ord.orderdate, odn.productcode) AS row_no, ord.orderid, ord.orderdate, odn.productcode, odn.productname, ord.totalshippingcost FROM OrderNew AS ord INNER JOIN order_detailsnew AS odn ON odn.orderid = ord.orderid ) ord ORDER BY ord.orderid, ord.orderdate, ord.productcode Results match perfectly. Edit for user580950, to insert nulls into every second row: You change the first SELECT line to be: SELECT CASE D.N WHEN 1 THEN ord.orderid END AS orderid, ... And you chance the ORDER BY line to be: CROSS JOIN (SELECT 1 UNION ALL SELECT 2) AS D(N) ORDER BY ord.orderid, ord.orderdate, ord.productcode, D.N But as the comments say said in your other question SQL Query Add an Alternate Blank Records, this is something that you should be doing at your presentation layer and not in the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to use sitemap_generator with paperclip upload to s3 in heroku I know sitemap_generator use CarrierWave to upload to s3. Can it support paperclip? If yes, Can anyone tell me how to upload sitemap files (generated by sitemap_generator in heroku) to s3 using paperclip? Thanks. A: I created a rake file to handle all that without loosing any of the current behavior of the gem, all you have to do is to download the code I created: https://gist.github.com/1693860
{ "language": "en", "url": "https://stackoverflow.com/questions/7550549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TSQL substitution of key words and code blocks I have blocks of TSQL that I want to create a MACRO for and then reuse in my SQL file. I want this to be a 'compile' time thing only. Eg: ?set? COMMON = "Field1 int, Field2 char(1),"; ?set? MAKEONE = "create table"; MAKEONE XXX ( COMMON Field3 int ); Please dont ask why I would want to ... :) ... it is for SQL Server. Ok, what about conditional execution of SQL: ?set? ISYES = true; ?if? ISYES create table AAA (...) ?else? create table BBB (...) A: What you are asking makes little sense in SQL terms Based on your examples: * *A CREATE TABLE is exactly that: a CREATE TABLE. Why Macro it? You aren't going to substitute "CREATE PROCEDURE". *Having "common" fields would indicate poor design You also have to consider: * *constraints, keys and indexes *permissions of using dynamic SQL *the cost of developing a "framework" to do what SQL already does *permissions of your objects Now, what is the business problem you are trying to solve? Instead of asking about your chosen solution... Edit: question updated as I typed above: IF (a condition) EXEC ('CREATE TABLE ...') ELSE IF (a condition) EXEC ('CREATE TABLE ...') ... Note that much of DDL in SQL must be in it's own batch or the first statement in a batch. Hence use of dynamic SQL again
{ "language": "en", "url": "https://stackoverflow.com/questions/7550551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to redirect to application page after installing application to one's page or app? Now I want to automatic redirect to facebook application's index page after user installing the application to his/her facebook page. My method is use the href tag as below: <a href='http://www.facebook.com/add.php?api_key=".$APPID."&pages&perms=publish_stream&page=".$paID."' target='_top'>Add APP</a> I have tried some ways such as add redirect_uri or next or post_authorize_redirect_url as parameter to the add.php link,but they all redirected to the facebook page or application after installing. Then how to realize it? Useful link http://developers.facebook.com/docs/authentication/ I know that it can redirect after authentication.Such as: https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token But what is after installing? A: You could just use the API to add the app to the page? https://developers.facebook.com/docs/reference/api/page/#tabs A: https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL Client ID is your app id Redirect uri is your callback page For more you can look at this page
{ "language": "en", "url": "https://stackoverflow.com/questions/7550552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error using for loop in C for ( int iIdx = 0; iIdx < argc; ++iIdx ) _tprintf( TEXT( "Arg %d: %s\n" ), iIdx, argv[ iIdx ] ); _tprintf( TEXT( "\n" ) ); Is this valid in C? Because I get an error when I try to compile it, if I remove the int from the initializer section of the for loop, it compiles fine... A: It is not valid in C before C99. In C89/90 and earlier, declarations need to be at the start of each block. You can't interleave declarations and normal code. A declaration inside the for does not count as being at the start of a block. A: Yes. Microsoft's C compiler (cl) does not support modern C (C99). For loop initializers like that are new in C99.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to import IBActions from other .h file? I have many view controllers on my iOS app and in most of them I need the exact same IBAction. So instead of writing the same code in all view controllers, is it possible to create a separated .h file with the IBActions and then import on the viewcontroller.h? I tried that creating a Actions.h file and importing it with the command "#import Actions.h" on the ViewController.h file, but when I go to the Interface Builder the actions doesn't show up. Is there any way to do this??? A: Define the method in the superclass: @interface MyActionViewController: UIViewController { } - (IBAction)theAction:(id)sender; @end Subclass your view controllers from it: @interface FirstViewController: MyActionViewController { } @end A: Not import, you need to inherit. Create a viewController with that IBAction and inherit that in every viewControllers that you would like to use. A: You can actually do it all in Interface Builder as well. You can do it with the option to add an "Object" to your nib file. In the palette with all of the interface objects, there is one with an orange-colored cube labelled "Object". Put that one on the root-level of your view hierarchy. Change the custom class to the name of your class (sounds like it is "Actions"). Once you have changed the name from Object to the name of the class, Interface Builder will let you access any of the IBAction on that class. Connect the button to this custom class's IBAction. You can do the same thing for any of the other nib files which need to use this button code, and it saves you from having to subclass. A: If anyone is trying to do this on Swift 2, this is how: import UIKit class Actions: UIViewController { @IBAction func button1(sender: AnyObject) { } } Now the ViewController: import UIKit class ViewController: Menu_Swipes { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7550557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Heroku Crashes App on .sass File My rails app runs fine on my local Ubuntu machine, but when I push it to heroku and access the website, the app crashes with the following errors. 2011-09-26T03:45:52+00:00 heroku[web.1]: State changed from created to starting 2011-09-26T03:45:54+00:00 heroku[web.1]: Starting process with command `thin -p 7208 -e production -R /home/heroku_rack/heroku.ru start` 2011-09-26T03:46:00+00:00 app[web.1]: WARNING on line 640 of /app/app/stylesheets/simpla/style.sass: 2011-09-26T03:46:00+00:00 app[web.1]: This selector doesn't have any properties and will not be rendered. 2011-09-26T03:46:03+00:00 app[web.1]: WARNING: 'ui-ui-bg_flat_0_000000_40x100.png' was not found (or cannot be read) in /app/public/images 2011-09-26T03:46:03+00:00 app[web.1]: WARNING on line 122 of /app/app/stylesheets/calendar/jquery.weekcalendar.sass: 2011-09-26T03:46:03+00:00 app[web.1]: This selector doesn't have any properties and will not be rendered. 2011-09-26T03:46:03+00:00 app[web.1]: WARNING on line 214 of /app/app/stylesheets/calendar/jquery.weekcalendar.sass: 2011-09-26T03:46:03+00:00 app[web.1]: This selector doesn't have any properties and will not be rendered. 2011-09-26T03:46:03+00:00 app[web.1]: WARNING on line 122 of /app/app/stylesheets/calendar/jquery.weekcalendar.sass: 2011-09-26T03:46:03+00:00 app[web.1]: This selector doesn't have any properties and will not be rendered. 2011-09-26T03:46:03+00:00 app[web.1]: WARNING on line 214 of /app/app/stylesheets/calendar/jquery.weekcalendar.sass: 2011-09-26T03:46:03+00:00 app[web.1]: This selector doesn't have any properties and will not be rendered. 2011-09-26T03:46:03+00:00 app[web.1]: /app/app/stylesheets/calendar/jquery.weekcalendar.sass:6:in `linear-gradient': Undefined mixin 'linear-gradient'. (Sass::SyntaxError) 2011-09-26T03:46:03+00:00 app[web.1]: from /app/app/stylesheets/calendar/jquery.weekcalendar.sass:6 2011-09-26T03:46:03+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.8/gems/sass-3.1.7/lib/sass/../sass/tree/visitors/perform.rb:169:in `visit_mixin' 2011-09-26T03:46:03+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.8/gems/sass-3.1.7/lib/sass/../sass/tree/visitors/base.rb:37:in `send' 2011-09-26T03:46:03+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.8/gems/sass-3.1.7/lib/sass/../sass/tree/visitors/base.rb:37:in `visit' 2011-09-26T03:46:03+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.8/gems/sass-3.1.7/lib/sass/../sass/tree/visitors/perform.rb:18:in `visit' 2011-09-26T03:46:03+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.8/gems/sass-3.1.7/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children' 2011-09-26T03:46:03+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.8/gems/sass-3.1.7/lib/sass/../sass/tree/visitors/base.rb:53:in `map' . . 2011-09-26T03:46:04+00:00 heroku[web.1]: Process exited 2011-09-26T03:46:04+00:00 heroku[web.1]: State changed from starting to crashed 2011-09-26T03:47:27+00:00 heroku[slugc]: Slug compilation started My app/stylesheets/calendar/jquery.weekcalendar.sass has the following at the beginning: .wc-container font-size: 14px font-family: arial, helvetica .wc-toolbar +linear-gradient(color-stops(#EFEFEF, #D5D5D5)) border: 1px solid #DADADA padding: 1em font-size: 0.8em .wc-nav float: left .wc-display float: right button margin-top: 0 margin-bottom: 0 .wc-title text-align: center padding: 0 margin: 0 Line 6 is the one with "+linear-gradient(color-stops(#EFEFEF, #D5D5D5))". My local machine does not complain about this line, I wonder why heroku is complaining about it. A: Since linear-gradient mixin is defined in ./vendor/bundle/ruby/1.8/gems/compass-0.10.6/frameworks/compass/stylesheets/compass/css3/_gradient.scss, I had to add @import "compass" to app/stylesheets/calendar/jquery.weekcalendar.sass
{ "language": "en", "url": "https://stackoverflow.com/questions/7550560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Request object in a validate method STRUTS Is it possible to set an attribute in a request or session scope in a HttpServletRequest object of a validate method in Struts. Example: @Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){ ActionErrors ae = new ActionErrors(); request.getSession().setAttribute("unit", request.getParameter("unit")); } Because ive been trying this and it is not working in my jsp. If it is not working then what is the purpose of this object in this method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting role in SiteMapNode Sub Node These Site Map Node is in Web.Config <siteMapNode title="Hotel Setup" roles="Administrator,Hotel Admin"> <siteMapNode url="~/Page/HotelSetup/RoomTypeManagement.aspx" title="Room Types" /> <siteMapNode url="~/Page/HotelSetup/AddOns/AddOnCategoryProperties.aspx" title="Add On Categories" /> <siteMapNode url="~/Page/HotelSetup/AddOn.aspx" title="Add Ons" /> <siteMapNode url="~/Page/HotelSetup/Package.aspx" title="Packages" /> <siteMapNode url="~/Page/PriceTools/Promotion.aspx" title="Promotions" /> <siteMapNode url="~/Page/PriceTools/PromotionAddOn.aspx" title="AddOns Incentive" /> <siteMapNode url="~/Page/SupportAdmin/TranslationProperty.aspx" title="Translations" /> </siteMapNode> Is there anyway to made some sub sitemapnode in hotel setup can be accessed only by administrator but not hotel admin ? A: Problem solved, it need to be set in location path
{ "language": "en", "url": "https://stackoverflow.com/questions/7550563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magento Check the ID of the client if he already bought the product I have a product that can only be purchased once only for each customer .. If I put in the admin, only one item in the shopping cart, Elee can buy one at a time, and so buy more than one time. How do I check if the "ID" of the customer has already bought, so if they bought the message that he has already purchased this product.? I think you have to do the buy button A: Best thing you could do is write your own observer that is called before/after the add_to_cart event. (Read more about that here) Inside that observer file it's best that you get all the previous orders of that particular customer: $orderCollection = Mage::getModel('sales/order')->getCollection(); $customer_orders = $orderCollection->getSelect()->where('e.customer_id =CUSTOMER_ID_GOES_HERE'); Foreach order of this customer you iterate over all the orderded items, and if one of them matches the product: $order = Mage::getModel('sales/order')->load($order_id); $items = $order->getAllItems(); foreach ($items as $itemId => $item) { if($item->getProductId() == ordered_product_id_goes_here){ //Show output message here that customer can only buy this once } break; } Good luck ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7550566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why F# core library does not offer a generic sequence slicing function? Cutting sequence into batches of fixed length, making overlapping sliding data windows, getting each n-th item from a sequence - all these tasks can be solved using a single generic slicing function. For example, Clojure offers for such purposes partition size skiplibrary function. F# core library offers Seq.windowed function that implements sliding windows overlapping by 1. Seq.windowed width would be simply equivalent to partition width 1; varying partition arguments allows solving other problems: partition size size slices sequence into non-overlapping batches, partition 1 n gets each n-th sequence item, etc. It is not that hard to implement such functionality in F#. I once posted a naive prototype that suffers from redundant sequence evaluations; however making it into truly lazy production quality F# implementation is definitely doable. I wonder if it was any particular reason for limiting out-of-the-box F# core library offering for sequence slicing to Seq.windowed function only? A: I don't think there is any good answer to your question. There are certainly no technical difficulties that would make it impossible to implement a more general sliding window function. It can be implemented and it would be useful. Why is it not included in the F# core library? Probably because the F# team didn't try to include every possible useful function as it would make the core library too big, too difficult to maintain and harder to use (finding the right function would be difficult if there were too many of them).
{ "language": "en", "url": "https://stackoverflow.com/questions/7550569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mercurial: Converting existing folders into sub-repos I have a Mercurial repository that looks like this: SWClients/ SWCommon SWB SWNS ...where SWCommon is a a library common to the other two projects. Now, I want to convert SWCommon into a sub-repository of SWClients, so I followed the instructions here and here. However, in contrast to the example in the first link I want my sub-repository to have the same name as the folder had at the beginning. In detail, this is what I have done: Create a file map.txt as follows include SWCommon rename SWCommon . Create a file .hgsub as follows SWCommon = SWCommon Then run $ hg --config extensions.hgext.convert= convert --filemap map.txt . SWCommon-temp ...lots of stuff happens... Then $ cd SWCommon-temp $ hg update 101 files updated, 0 files merged, 0 files removed, 0 files unresolved $ cd .. $ mv SWCommon SWCommon-old $ mv SWCommon-temp SWCommon $ hg status abort: path 'SWCommon/SWCommon.xcodeproj/xcuserdata/malte.xcuserdatad/xcschemes/SWCommon.xcscheme' is inside nested repo 'SWCommon' ...which is indeed the case, but why is that a reason to abort? The other strange thing is that if I do not do that last 'mv' above and I execute an 'hg status' then, I end up with lots of 'missing' files in SWCommon as you would expect. The example in the link never makes it this far and basically stops on the hg update above? How do you make it work in practice? A: Not currently possible. You could create a new repo converting the original one like: $ hg --filemap excludemap.txt SWClients SWClients-without-SWCommon With a excludemap.txt like: exclude "SWCommon" And then add the subrepo there. $ hg --filemap map.txt SWCommon SWClients-without-SWCommon/SWCommon $ cd SWClients-without-SWCommon $ hg add SWCommon $ hg ci -m "Created subrepo" See the mailing list thread that discusses this problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to read bz2 file as an array with PHP There is a function you may know gzfile which "Read entire gz-file into an array", how can you do the same with bz2? Thanks! A: There's no built in function. You could do something like this (add some sanity checks, etc): function bzfile($filename){ $p = popen('bunzip2 -c ' . $filename, 'r'); $a = array(); while($a[] = fgets($p); return $a; } This assumes a unix-like os with a bunzip2 binary installed. It runs buznip2 on your file. The -c option means "send uncompressed data to stdout instead of affecting the file on disk). That output behaves like a file handle, so you can fgets on it to read lines. EDIT: There is an extension that provides some built-in bz2 functionality, though sadly, no bzfile(). If the bzip2 extension is available in your environment, you could rewrite the above like: function bzfile($file){ $fp = bzopen('foo.bz2','r'); $a = array(); while ($a[] = fgets($fp)); return $a; } This will not require a unix environment or installed bunzip2 binary. (NOTE: this all assumes the bzipped file is text and doesn't contain binary data, since you wanted a replacement for file())
{ "language": "en", "url": "https://stackoverflow.com/questions/7550571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trouble Building a Simpletest Suite From Working Unit Test Cases I've started using unit testing for my PHP programs, and figured Simpletest was as good a place to dive in as any other. I added the Simpletest files to my testing server, and ran the following tests on my custom PDO classes: <?php require_once('../simpletest/autorun.php'); require_once('../includes/inc_sql.php'); class TestOfSQL extends UnitTestCase{ function testRead(){ ... } function testWriteAndDelete(){ ... } } ?> That all works out smashingly. I try to build a test suite involving (so far) just that testing file, as follows: <?php require_once('../simpletest/autorun.php'); class AllTests extends TestSuite { function __construct(){ parent::__construct(); $this->addFile('inc_sql_test.php'); } } This crashes and burns, and I get the following readout: Warning: include_once(inc_sql_test.php) [function.include-once]: failed to open stream: No such file or directory in E:\xampp\htdocs\historicMuncie\simpletest\test_case.php on line 382 Warning: include_once() [function.include]: Failed opening 'inc_sql_test.php' for inclusion (include_path='.;E:\xampp\php\PEAR') in E:\xampp\htdocs\historicMuncie\simpletest\test_case.php on line 382 Warning: file_get_contents(inc_sql_test.php) [function.file-get-contents]: failed to open stream: No such file or directory in E:\xampp\htdocs\historicMuncie\simpletest\test_case.php on line 418 all_tests.php Fail: AllTests -> inc_sql_test.php -> Bad TestSuite [inc_sql_test.php] with error [No runnable test cases in [inc_sql_test.php]] 0/0 test cases complete: 0 passes, 1 fails and 0 exceptions. I've played around with include paths, web root vs. server root notation - anything that came to mind, but nothing is allowing that test suite to run properly. Any ideas? A: I always cringe when I see relative paths in PHP scripts. It's much easier to implement and maintain when using "semi-absolute" paths based on a common root. Try: $this->addFile( $_SERVER['DOCUMENT_ROOT'] . '/inc_sql_test.php' ); A: You can also do this: $this->addFile(dirname(__FILE__) . '/inc_sql_test.php'); Regards!
{ "language": "en", "url": "https://stackoverflow.com/questions/7550574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is it possible to have a form submit a comma separated list via GET? Let's say I have a form that contains a whole bunch of check boxes with the same name, c. Each checkbox has an integer value assigned to it. When the form is submitted, via GET, I'd like the url to look like www.url.com/?c=1,2,3,4,5 and not www.url.com/?c=1&c=2&c=3&c=4&c=5 Possible? or will I have to capture the form submit via jQuery, loop through each checked box, and tack on my own url var? A: You'll have to resort to Javascript to accomplish this. In jQuery, this is how you might go about it: $('form').submit(function() { var values = []; $(this).find('input[type="checkbox"][name="c"]:checked').each(function() { values.push(this.value); }); window.location = 'www.url.com/?c=' + values.join(','); }); A: function form_to_submit() { var form_to_submit = $('#form'); var queryArray = form_to_submit.serializeArray(); const queryArrayReduced = queryArray.reduce((acc, {name, value}) => { if(name in acc) { acc[name] = acc[name].concat(','+value); } else { acc[name] ??= value; } return acc; }, {}); var queryString = decodeURIComponent($.param(queryArrayReduced)); window.location.href = '?' + queryString; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7550580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: my own long polling implementation compared to facebook and gmail For days I have been experimenting with long polling/comet implementation for my site. I got the basic idea of how it works, this is where i run some tests. On the other hand, I have been observing(firebug) how gmail and facebook implement long polling. What I noticed with gmail is that the ajax request does not continuously follow right after the current request expires, but it waits for several seconds/minutes before it fires the next one. I played with it some more. I tried to login with gmail account A in firefox and gmail account B in chrome. I waited when the current ajax poll finishes and then I sent an email from account B to A. I was expecting that account A won't receive it until the next poll, but to my surprise Account A directly received it right after I hit the submit button. How does gmail do this with long polling ? If you try to visit my site and click on the Run button and open firebug, you can see that ajax spinner is always running. when the server responds with data, it requests the server again. A: Take a look at WebSync from Frozenmountain or SignalIR which take the work out of the backed pieces. I can vouch for websync as I use it everyday, but been hearing good things about signalir. A: I think your assumption that Gmail uses (only) long polling is incorrect. According to this question (and the answer) it uses forever frame, and forever XHR. See also BrowserChannel, which they use for Gmail Chat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: When to choose nls() over loess()? If I have some (x,y) data, I can easily draw straight-line through it, e.g. f=glm(y~x) plot(x,y) lines(x,f$fitted.values) But for curvy data I want a curvy line. It seems loess() can be used: f=loess(y~x) plot(x,y) lines(x,f$fitted) This question has evolved as I've typed and researched it. I started off with wanting to a simple function to fit curvy data (where I know nothing about the data), and wanting to understand how to use nls() or optim() to do that. That was what everyone seemed to be suggesting in similar questions I found. But now I stumbled upon loess() I'm happy. So, now my question is why would someone choose to use nls or optim instead of loess (or smooth.spline)? Using the toolbox analogy, is nls a screwdriver and loess is a power-screwdriver (meaning I'd almost always choose the latter as it does the same thing but with less of my effort)? Or is nls a flat-head screwdriver and loess a cross-head screwdriver (meaning loess is a better fit for some problems, but for others it simply won't do the job)? For reference, here is the play data I was using that loess gives satisfactory results for: x=1:40 y=(sin(x/5)*3)+runif(x) And: x=1:40 y=exp(jitter(x,factor=30)^0.5) Sadly, it does less well on this: x=1:400 y=(sin(x/20)*3)+runif(x) Can nls(), or any other function or library, cope with both this and the previous exp example, without being given a hint (i.e. without being told it is a sine wave)? UPDATE: Some useful pages on the same theme on stackoverflow: Goodness of fit functions in R How to fit a smooth curve to my data in R? smooth.spline "out of the box" gives good results on my 1st and 3rd examples, but terrible (it just joins the dots) on the 2nd example. However f=smooth.spline(x,y,spar=0.5) is good on all three. UPDATE #2: gam() (from mgcv package) is great so far: it gives a similar result to loess() when that was better, and a similar result to smooth.spline() when that was better. And all without hints or extra parameters. The docs were so far over my head I felt like I was squinting at a plane flying overhead; but a bit of trial and error found: #f=gam(y~x) #Works just like glm(). I.e. pointless f=gam(y~s(x)) #This is what you want plot(x,y) lines(x,f$fitted) A: loess() is non-parametric, meaning you don't get a set of coefficients you can use later - it's not a model, just a fit line. nls() will give you coefficients you could use to build an equation and predict values with a different but similar data set - you can create a model with nls(). A: Nonlinear-least squares is a means of fitting a model that is non-linear in the parameters. By fitting a model, I mean there is some a priori specified form for the relationship between the response and the covariates, with some unknown parameters that are to be estimated. As the model is non-linear in these parameters NLS is a means to estimate values for those coefficients by minimising a least-squares criterion in an iterative fashion. LOESS was developed as a means of smoothing scatterplots. It has a very less well defined concept of a "model" that is fitted (IIRC there is no "model"). LOESS works by trying to identify pattern in the relationship between response and covariates without the user having to specify what form that relationship is. LOESS works out the relationship from the data themselves. These are two fundamentally different ideas. If you know the data should follow a particular model then you should fit that model using NLS. You could always compare the two fits (NLS vs LOESS) to see if there is systematic variation from the presumed model etc - but that would show up in the NLS residuals. Instead of LOESS, you might consider Generalized Additive Models (GAMs) fitted via gam() in recommended package mgcv. These models can be viewed as a penalised regression problem but allow for the fitted smooth functions to be estimated from the data like they are in LOESS. GAM extends GLM to allow smooth, arbitrary functions of covariates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to avoid data loss on server failure with MongoDB on a single machine? I have read that mongoDB don't write data to disk right away, it does this periodically. Any thoughts on how to deal with this? A: You can enable journaling with --journal. Check out http://www.adathedev.co.uk/2011/03/mongodb-journaling-performance-single.html and http://www.mongodb.org/display/DOCS/Durability+and+Repair A: Besides --journal that is enabled by default since MongoDB 2.0 (only on 64 bit machines), there is a flag that you can set when persisting data: * *safe => false: do not wait for a db response *safe => true: wait for a db response *safe => num: wait for that many servers to have the write before returning *fsync => true: fsync the write to disk before returning. fsync => true implies safe=>true, but not visa versa. If fsync=>false and safe=>true and the write could be in successfully applied to a mmapped file but not yet written to disk
{ "language": "en", "url": "https://stackoverflow.com/questions/7550583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Unable to display SQL database data on Visual basic form I am facing a problem displaying the records of my table on the visual basic form I have created. This is my code : Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click myconnection = New SqlConnection("server=HOME-PC\SQLEXPRESS;uid=sa;pwd=123;database=college") myconnection.Open() mycommand = New SqlCommand("SELECT * from demo3)", myconnection) Dim mySqlDataAdapter As New SqlDataAdapter(mycommand) Dim mydsStudent As New DataSet() mySqlDataAdapter.Fill(mydsStudent, "Student") ra = mycommand.ExecuteNonQuery() MessageBox.Show("Data Displayed" & ra) myconnection.Close() End Sub End Class Note: my database name is "college" , table name is "demo3" . Table contains 2 columns namely name and roll no. How to display the data in those columns on the visual basic form that I have created ? A: You don't need to call execute non query. You can bind the dataset to a DataGridView. Like this Dim DataGridView1 as new DataGridView() DataGridView1.DataSource = mydsStudent 'Your table goes here, not sure about the exact propety name, hope it works. DataGridView1.DisplayMember = "demo3" Me.Controls.Add(DataGridView1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7550585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Include a variable inside a NSString? This works fine, we all know that: NSString *textoutput = @"Hello"; outLabel.text = textoutput; However, what if you want to include a variable inside that NSString statement like the following: NSString *textoutput =@"Hello" Variable; In C++ I know when I cout something and I wanted to include a variable all I did was soemthing like this: cout << "Hello" << variableName << endl; So I'm trying to accomplish that with Objective-C but I don't see how. A: I have The Cure you're looking for, Robert Smith: if your variable is an object, use this: NSString *textOutput = [NSString stringWithFormat:@"Hello %@", Variable]; The '%@' will only work for objects. For integers, it's '%i'. For other types, or if you want more specificity over the string it produces, use this guide A: You can do some fancy formatting using the following function: NSString *textoutput = [NSString stringWithFormat:@"Hello %@", variable]; Note that %@ assumes that variable is an Objective-C object. If it's a C string, use %s, and if it's any other C type, check out the printf reference. Alternatively, you can create a new string by appending a string to an existing string: NSString *hello = @"Hello"; NSString *whatever = [hello stringByAppendingString:@", world!"]; Note that NSString is immutable -- once you assign a value, you can't change it, only derive new objects. If you are going to be appending a lot to a string, you should probably use NSMutableString instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: CSS Background Image Not Showing in IE Please help, The background image is not showing in IE, but everything is perfectly fine in safari. I have checked with W3C CSS validation and html validation, everything is ok. What is the problem? http://www.applezone.com.hk/newrx/ body { /*background-color:#eee;*/ font-family:Arial, Helvetica, sans-serif; margin: 0px 0px 0px 0px; background:url(images/bg_line.JPG); background-repeat:repeat-x; } p { font-size:12px; color:#999999; line-height:160%; } #container { width:1050px; background:url(images/bg.JPG) no-repeat; margin-top:0px; margin-left: auto; margin-right: auto; padding-left:150px; padding-top:220px; } A: There's something wrong with the jpg files. IE8 is not able to render them. Maybe you are using a JPEG2000 format? If you try to load "http://www.applezone.com.hk/newrx/images/bg.JPG" in IE8 you will get a broken picture icon only. I downloaded the file and opened it from the hard drive too, got the same result. Try loading the pictures in an editor, like GIMP or PhotoFiltre and re-saving them (using save as) I tried in PhotoFiltre and re-saved it using a 90% quality setting. The size went down dramatically (to about 8% of the original without visible loss of quality) and IE8 is able to open it now! You should try to make image files as small as possible on the site because that largely affects the visitors experience. A: It'd be help to know what version of IE you're using. Your code works fine for me in IE7. Anyway... background:url(images/bg_line.JPG); Try this instead: background-image:url('images/bg_line.JPG'); You're using the background shorthand which is valid according to the standard, but it's possible whatever version of IE you're using doesn't support the way you're using it. IE may also expect the filename to be quoted, as I did for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Objective-C &JSONKit POST issue I'm trying to post to a rails backend from Objective-C and JSONKit and am having difficulty getting my results published. I keep getting back a null recordset from my server. [dictionary setValue:(@"bar") forKey:@"foo"]; NSString *JSON = [dictionary JSONString]; NSData *theData = [JSON dataUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString: myUrl]; NSString *postLength = [NSString stringWithFormat:@"%d", [theData length]]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; NSError *error = NULL; NSURLResponse *response = nil; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:theData]; NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]; NSLog(resultString); Is there something I'm missing? the JSON seems to be serializing correctly {"foo":"bar"} Any help would be greatly appreciated. Thanks! A: Just changed the setValue from json-rpc to json and it worked like a champ. [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; **[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];** [request setCachePolicy:NSURLRequestReloadIgnoringCacheData]; [request setHTTPBody:theData];
{ "language": "en", "url": "https://stackoverflow.com/questions/7550605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery - How to fix mouseover and mouseleave auto loop a lot of times? When I faster to mouseover and leave #go in a short time, it will auto loop a lot of times. How to fix it?? $("#go").mouseover(function(){ $("#block").animate({ width: "900px" }, 300 ); }); $("#go").mouseleave(function(){ $("#block").animate({ width: "0px" }, 300 ); }); A: use stop() $("#go").mouseover(function(){ $("#block").stop(true,true).animate({ width: "900px" }, 300 ); }); $("#go").mouseleave(function(){ $("#block").animate({ width: "0px" }, 300 ); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7550608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perform webview action from another listview activity I have a webview as the main activity and I want refresh the webview from the "Preference" (listview) that is from another activity. Is it possible to do that? I don't want to have the "refresh" button on the apps menu. But the activity will crash after i pressed "refresh" on my preference activity , i assume that is "R.id.web_engine" , that is from the MainActivity layout , that causes the crash (look at the code below). How can I perform a webview action from the external activity ? Example : In my MainActivity will have //Webview final WebView engine = (WebView) findViewById(R.id.web_engine); engine.loadUrl("file:///android_asset/www/index.html"); engine.getSettings().setJavaScriptEnabled(true); and Preferences //Get the custom preference Preference refreshPref = (Preference) findPreference("refreshPref"); refreshPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Toast.makeText(getBaseContext(), "Loading...",Toast.LENGTH_SHORT).show(); WebView engine = (WebView) findViewById(R.id.web_engine); engine.loadUrl("javascript:window.location.reload();"); return true; } }); A: This line is causing the crash WebView engine = (WebView) findViewById(R.id.web_engine); engine.loadUrl("javascript:window.location.reload();"); It should be a null pointer crash if I understand correctly since this Preference activity will never be able to find a WebView which is main activity using this method. The better way to do this would be to broadcast an intent to refresh and handle that intent in main activity and perform the action. See details about broadcast receivers here http://thinkandroid.wordpress.com/2010/02/02/custom-intents-and-broadcasting-with-receivers/ A: I agree with Rahul Choudhary. Your webview is only visible from your main activity. You have to pass it a message that it should refresh next time it is visible. The right place for this code is on the main activity onResume() method. You can use intents to launch it again (it will be recreated and loose its history) or use SharedPreferences that are accessible by both activities. EDIT: added some code below. MainActivity //onCreate final WebView engine = (WebView) findViewById(R.id.web_engine); engine.loadUrl("file:///android_asset/www/index.html"); engine.getSettings().setJavaScriptEnabled(true); //onResume boolean refresh = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("SHOULD_REFRESH", false) if (refresh) { engine.loadUrl("javascript:window.location.reload();"); //remove the shared preference here or set it to false to prevent reloading next time } and Preferences //Get the custom preference Preference refreshPref = (Preference) findPreference("refreshPref"); refreshPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("SHOULD_REFRESH", true).commit(); return true; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7550609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pre-fill input text box Does anyone know of a good small piece of code that will prefill my user and pass input box with the text username and password. I've seen so jscript that will do it but i'm looking for something that is a few lines a code. similar to how the search text is in the search box up top on the right A: For browsers that support HTML5, adding placeholder="search" will add the prefill text automatically. The search text box at the top of the page has: <input type="text" placeholder="search" > You can use an HTML5 shim to make this backwards compatible. Example: http://kamikazemusic.com/web-development/revisiting-html5-placeholder-fixes/ A: You can use the following: <input type="text" style="color:#ccc;" value="username" onfocus="this.value = this.value=='username' ? '' : this.value; this.style.color='#000';" onfocusout="this.value = this.value == '' ? this.value = 'username' : this.value; this.value=='username' ? this.style.color='#ccc' : this.style.color='#000'"/> <input type="text" style="color:#ccc;" value="password" onfocus="this.value = this.value=='password' ? '' : this.value; this.style.color='#000';" onfocusout="this.value = this.value == '' ? this.value = 'password' : this.value; this.value=='password' ? this.style.color='#ccc' : this.style.color='#000'"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7550610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In simplest terms, what is a factory? What is a factory and why would I want to use one? A: What is a factory ? Wikipedia explains in detail Also see answer from legendary BalusC over here about many GoF patterns examples In simple words Factory creates\initialize\allocate the objects that you can use in the code. e.g if you have a person abstract class or interface or even a concrete class and you declare it in an other class e.g. private person; that is just that object has been declared but not created. You will either use new or some dependency injection or a factory to create this object (there are other options as well e.g Locator etc). Why would I want to use one? Now you might need to a have specific type of person e.g teacher or even person might have different implantation based of different configurations etc .Factory pattern takes care of this.It allows you or should I say frees you from worrying about what implementation or initialization of particular class should be used. A: Are you familiar with JDBC? It's one and all (abstract) factory. It's a good real world example. // Factory method. Loads the driver by given classname. It actually returns a // concrete Class<Driver>. However, we don't need it here, so we just ignore it. // It can be any driver class name. The MySQL one here is just an example. // Under the covers, it will do DriverManager.registerDriver(new Driver()). Class.forName("com.mysql.jdbc.Driver"); // Abstract factory. This lets the driver return a concrete connection for the // given URL. You can just declare it against java.sql.Connection interface. // Under the covers, the DriverManager will find the MySQL driver by URL and call // driver.connect() which in turn will return new ConnectionImpl(). Connection connection = DriverManager.getConnection(url); // Abstract factory. This lets the driver return a concrete statement from the // connection. You can just declare it against java.sql.Statement interface. // Under the covers, the MySQL ConnectionImpl will return new StatementImpl(). Statement statement = connection.createStatement(); // Abstract factory. This lets the driver return a concrete result set from the // statement. You can just declare it against java.sql.ResultSet interface. // Under the covers, the MySQL StatementImpl will return new ResultSetImpl(). ResultSet resultSet = statement.executeQuery(sql); You do not need to have a single line of JDBC driver specific import in your code. You do not need to do import com.mysql.jdbc.ConnectionImpl or something. You just have to declare everything against java.sql.*. You do not need to do connection = new ConnectionImpl(); yourself. You just have to get it from an abstract factory as part of a standard API. If you make the JDBC driver class name a variable which can be configured externally (e.g. properties file) and write ANSI compatible SQL queries, then you do not ever need to rewrite, recompile, rebuild and redistribute your Java application for every single database vendor and/or JDBC driver which the world is aware of. You just have to drop the desired JDBC driver JAR file in the runtime classpath and provide configuration by some (properties) file without the need to change any line of Java code whenever you want to switch of DB or reuse the app on a different DB. That's the power of interfaces and abstract factories. Another known real world example is Java EE. Substitute "JDBC" with "Java EE" and "JDBC driver" with "Java EE application server" (WildFly, TomEE, GlassFish, Liberty, etc). See also: * *How exactly do Class#forName() and DriverManager#getConnection() work? *What exactly is Java EE? *Wikipedia: Factory method pattern *Wikipedia: Abstract factory pattern A: Factory is an object for creating other objects. It creates objects without exposing the instantiation logic to the client. Use this pattern when you don't want to expose object instantiation logic to the client/caller Related posts: Design Patterns: Factory vs Factory method vs Abstract Factory What is the basic difference between the Factory and Abstract Factory Patterns? A: The Factory design pattern is ideal in circumstances when you need to create multiple instances of an object at run time. Rather than explicitly creating each instance you can initialize many instances. Additionally, you can encapsulate complex creation code that can be reused multiple times. Example: public class Person { int ID; String gender; public Person(int ID,String gender){ this.ID=ID; this.gender=gender; } public int getID() { return ID; } public String getGender() { return gender; } } public class PersonFactory{ public static Person createMale(int id){ return new Person(id,"M"); } public static Person createFemale(int id){ return new Person(id,"F"); } } public class factorytest{ public static void main(String[]args){ Person[] pList= new Person[100]; for(int x=0;x<100;x++){ pList[x]=PersonFactory.createMale(x); } } } In this example we encapsulate the details of the gender initialization parameter and can simply ask the PersonFactory to createMale or createFemale Person objects. A: The factory is an object, that creates objects. The common usage includes two cases: * *When you want to delegate the choice of the concrete object to the factory - e.g. it may return an already existing object (see Integer.valueOf(), which is a so-called factory method) or choose a concrete implementation depending on some conditions - e.g. supplied argument or pre-defined options (see XPathFactory class in Java API for XML Processing) *When you want more flexibility for some universal job. You cannot pass a method or a constructor as an argument (well, you can, but reflection sucks), so you use a concrete factory as an object source (e.g. SomeFactory<T> in a generic method). A: In simple terms, Factory is an OO design pattern that deals with creating objects without specifying the exact class of object that is to be created. A good reason to use it is well defined in wikipedia: The creation of an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: NSURLRequest odd behaivor I'm having such an odd problem. I'm running iOS 4.3.2 on my device. Compiling in Xcode 4 but I am not using the iOS 5 beta SDK. My app fetches a plist file from a server, the plist file is set of strings I use in my app. I get the data via a request and connection like so NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:pathAndFile] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0]; NSURLConnection *con =[[NSURLConnection alloc] initWithRequest:req delegate:self]; When running on wifi - if I go up and make a change on the server side, the app will see the new data and use it each time the app is launched. If I switch my phone over to 3G it goes and grabs the data correctly the FIRST TIME. If I then go back and change the file on the server, and rerun the app - it is only loading the OLD data, not the new data. The app IS hitting the code where the connection is established and loaded. Ok, so now I'm in this state where the app is using old data. I switch the phone to wifi and BAM, the new data is there. But if I now close the app. Turn off wifi. Launch the app, the app is using the OLD DATA again. I did implement - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { return nil; } as suggested in another stackoverflow thread. Anybody have any thoughts why this could be happening and how I could make it work correctly? A: I am just throwing this out there as something to check: I have a hard time believing this but perhaps your 3G carrier is caching? Can you check your server logs to see if you are receiving the actual calls from the device? If not, try concatenating an random querystring value on the end of the URL on every request and then check the server logs again. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP For Loop Printing An Array This might seem like a really easy question but it has got me stumped lol. I am trying to print the rows received from the database. I want to store the rows inside an array and then print them using a for loop. I know that the query works however when I try to print the array elements it only prints the word array. I have tired doing it with a foreach loop and a simple for loop. If anyone can point me in the right direction would be a life saver. Printing Php Code <?php $type = "FREE"; $free = getTerms($type); echo "<p>"; for($j = 0; $j < count($free); $j++) { echo "start".$free[$j]."end"; } echo "</p>"; ?> geting the rows from the database function getTerms($type) { $terms = array(); $connection = mysql_open(); $query = "select terms from terms_and_con where accountType='$type' && currentTerms='YES'"; $results = mysql_query($query, $connection) or show_error("signUp.php", "", ""); while($row = mysql_fetch_array($results)) { $terms[] = $row; } mysql_close($connection) or show_error("signUp.php", "", ""); return $terms; } A: Each entry in the $free array is itself an array (from $row). Try echo 'start', $free[$j]['terms'], 'end'; Alternatively, you may find a foreach loop more semantically appropriate foreach ($free as $row) { echo 'start', $row['terms'], 'end'; } Edit: I'd advise using mysql_fetch_assoc() instead of mysql_fetch_array() if you're only going to use associative entries from $row. A: the thing is function mysql_fetch_array ( as the name suggests) returns an ( in your case both associative and number) array. so $row is actually array(0 => VALUE, 'terms' => 'VALUE') So what you are trying to echo is actually an array. Simple fix: replace: $terms[] = $row; with: $terms[] = $row[0];
{ "language": "en", "url": "https://stackoverflow.com/questions/7550615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to read and write a virtual hard disk when it is opened by another application How to read and write a "virtual hard disk" when it is opened by "another application"? virtual hard disk - referring to hard disk that are created by a virtualization application (e.g. Virtual PC, Virtual Box, VMware Player) another application - referring to virtualization application (e.g. Virtual PC, Virtual Box, VMware Player) A: This would seem to be a staggeringly bad idea. Imagine if something in your computer started fiddling with the data on your disk as you were using it - things would end very poorly. And that's what you're asking here - the virtual machine is in operation, presumably, and you'd like to do something to its disk while it's in use. You'd be pulling the rug out from under the virtualized OS. Read-only access, even, has many pitfalls - you'd need to assume that the data will be inconsistent, as the writes take time and are often spread out between sectors. If you read a sector as it's being written, it'll be useless data. This is a tricky, but useful, thing to do if the VM isn't running. But it is, so can you communicate with it over the network? All three products you list have special host-to-guest file I/O capabilities that allow the guest to access files on the host, and vice-versa. Let the guest OS get or write your data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C program which adds two integers as fractions I am writing a C program which adds two nonzero integers which are given as fractions. The integers are input as n1 d1 n2 d2. There seems to be an error when certain negative numbers are input, such as in the following combination ( 1 2 -1 2). This should state that the numbers being added are 1/2 and -1/2, and then state that the sum is 0. Instead, the program just shows a blank line and does not accept any further input. The second problem I have is that when the sentinel value is input the program is supposed to display a termination message and then end, instead it displays "floating point exception". int main( void ) { int n1; int d1; int n2; int d2; int g; int p; int q; int again; int sumn; int sumd; again = 1; while ( again == 1 ) { printf( "Please enter 4 nonzero integers representing the fractions: " ); scanf( "%d%d%d%d", &n1, &d1, &n2, &d2 ); if ( n1 == 0 && n2 == 0 && d1 == 0 && d2 == 0 ) { again = 0; } else { again = 1; } if ( ( n1 == 0 || n2 == 0 || d1 == 0 || d2 == 0 ) && ( n1 != 0 || n2 != 0 || d1 != 0 || d2 != 0 ) ) { printf( "One or more of the integers is zero\n" ); again = 1; } else { g = gcd( d1, d2 ); p = ( ( n1 * ( d2 / g ) ) + ( n2 * ( d1 / g ) ) ); q = ( d1 * ( d2 / g ) ); sumn = ( p / ( gcd( p, q ) ) ); sumd = ( q / ( gcd( p, q ) ) ); printf( "The fractions are: %d/%d and %d/%d\n", n1, d1, n2, d2 ); if ( sumn == sumd ) { printf( "Their sum is: 1\n" ); } else { if ( sumd == 1 ) { printf( "Their sum is: %d\n", sumn ); } else { printf( "Their sum is: %d/%d\n", sumn, sumd ); } } } } printf( "***** Program Terminated *****\n" ); return (EXIT_SUCCESS); } int gcd( int a, int b ) { while ( a != b ) { if ( a > b ) { a = ( a - b ); } else { b = ( b - a ); } } return a; } A: You have an error in the gcd function. When a is negative, it's an infinite loop. Therefore the console hangs and won't take any more input. int gcd( int a, int b ) { while ( a != b ) { cout << a << " " << b << endl; if ( a > b ) { a = ( a - b ); } else { b = ( b - a ); } } return a; } Output: gcd(-1,2) -1 2 -1 3 -1 4 -1 5 -1 6 -1 7 -1 8 -1 9 -1 10 -1 11 -1 12 -1 13 -1 14 ... p.s. Yes I know the question is tagged C, but I'm just printing out data in C++. EDIT: The fix is to make a and b positive: int gcd( int a, int b ) { if (a < 0) a = -a; if (b < 0) b = -b; while ( a != b ){ if ( a > b ){ a = ( a - b ); } else{ b = ( b - a ); } } return a; } A: When you enter sentinel value ( I assume all equal to zero) it executes your first if case inside while and then goes on to execute 2nd else case i.e. this part else { g = gcd( d1, d2 ); p = ( ( n1 * ( d2 / g ) ) + ( n2 * ( d1 / g ) ) ); .... and goes on to calculate gcd which I guess is triggering floating point exception A: GCD should be taken care of by providing only positive values. As mystical pointed, you should make the numbers positive. Moreover you should also check if any number coming in is not zero. So, edit the GCD function as follows: int gcd( int a, int b ) { if (a==0 || b==0) return 1; if (a < 0) a = -a; if (b < 0) b = -b; while ( a != b ) { if ( a > b ) { a = ( a - b ); } else { b = ( b - a ); } } return a; } You can now see you get correct result results for even the combination like (1 2 -1 2) or even (-1 -1 -2 -2). And to solve the sentinel problem, edit the while loop as: while ( again == 1 ) { printf( "Please enter 4 nonzero integers representing the fractions: " ); scanf( "%d%d%d%d", &n1, &d1, &n2, &d2 ); if ( n1 == 0 && n2 == 0 && d1 == 0 && d2 == 0 ) { again = 0; } else { if ( ( n1 == 0 || n2 == 0 || d1 == 0 || d2 == 0 ) && ( n1 != 0 || n2 != 0 || d1 != 0 || d2 != 0 ) ) { printf( "One or more of the integers is zero\n" ); again = 1; } else { g = gcd( d1, d2 ); p = ( ( n1 * ( d2 / g ) ) + ( n2 * ( d1 / g ) ) ); q = ( d1 * ( d2 / g ) ); sumn = ( p / ( gcd( p, q ) ) ); sumd = ( q / ( gcd( p, q ) ) ); printf( "The fractions are: %d/%d and %d/%d\n", n1, d1, n2, d2 ); if ( sumn == sumd ) { printf( "Their sum is: 1\n" ); } else { if ( sumd == 1 ) { printf( "Their sum is: %d\n", sumn ); } else { printf( "Their sum is: %d/%d\n", sumn, sumd ); } } } } } -Sandip
{ "language": "en", "url": "https://stackoverflow.com/questions/7550619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery/Javascript custom email validation not working I didn't want to us a plugin for simple email validations so i tried to create my own but it doesn't work. Its always returning false. Here is my code: var regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i; if(regex.test($("#email").val())) { //pass } What am I doing wrong? Thank you! A: I would assume that \A is supposed to be ^ and \z is supposed to be $. A: Here is the regx i am using in my project.It works fine var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; if (emailReg.test($('#Email').val())) { //pass } A: may be this will solve the problem var regex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if(rege.test($('#email').val())) { //do something } A: try this regular expression : var regex= /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; A: Try this code.. <script language="javascript" type="text/javascript"> function EmailValidation(email) { var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(email.value)) { alert('Please provide a valid email address'); email.focus; return false; } } and the HTML.. <div> <asp:TextBox ID="TextBox1" runat="server" onchange="EmailValidation(this)"></asp:TextBox> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7550627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to understand findbugs multithreaded bugs http://findbugs.sourceforge.net/bugDescriptions.html#SP_SPIN_ON_FIELD is only a problem is the field is not volatile, right? http://findbugs.sourceforge.net/bugDescriptions.html#MDM_WAIT_WITHOUT_TIMEOUT is confusing - what does it mean? A: http://findbugs.sourceforge.net/bugDescriptions.html#SP_SPIN_ON_FIELD is only a problem is the field is not volatile, right? Correct. http://findbugs.sourceforge.net/bugDescriptions.html#MDM_WAIT_WITHOUT_TIMEOUT is confusing - what does it mean? I don't see it in the list anymore. A: Giving answer to your first ques :- No SP_SPIN_ON_FIELD is not only related to non volatile instance fields even a volatile field can also lead to this bug. Plz refer to the code below it has a volatile field and still shows this bug(SP_SPIN_ON_FIELD):- public class FindBugSP { private volatile int mCountOne = 0; /** * DEFAULT CONSTRUCTOR * */ private FindBugSP() { //DO NOTHING super(); } /** * Method implementing actual scenario of FindBugs bug code - SP */ void problem() { while(true) { if(mCountOne == 0) { break; } } } /** * Method implementing solution for actual scenario of FindBugs bug code - SP */ void solution() { while(true) { if(mCountOne ==5) { break; } mCountOne++; } } } Now answering your second ques:- MDM_WAIT_WITHOUT_TIMEOUT has been removed from the list of bugcodes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting numeric type vector into a vector of strings I'm trying to convert this: > j[1:5] NA06985 NA06991 NA06993 NA06994 NA07000 Into this: c("NA06985","NA06991","NA06993", "NA06994", "NA07000") I've tried using as.character but it gives me: > as.character(j[1:5]) [1] "10" "10" "10" "10" "10" Help please! -Josh EDIT: Okay so I think I figured it out. After doing class(j) I found that it was of type data.frame. So I converted to as.matrix and it worked..hooray! A: paste(j[1:5]) This works for strings, factors, numerics, pretty much anything that can be displayed. A: Okay so I think I figured it out. After doing class(j) I found that it was of type data.frame. So I converted to as.matrix and it worked..hooray! A: Assumming that j is a factor > j <- factor(c("NA06985","NA06991","NA06993", "NA06994", "NA07000", "extra level")) > j [1] NA06985 NA06991 NA06993 NA06994 NA07000 extra level Levels: extra level NA06985 NA06991 NA06993 NA06994 NA07000 > levels(j)[j[1:5]] [1] "NA06985" "NA06991" "NA06993" "NA06994" "NA07000"
{ "language": "en", "url": "https://stackoverflow.com/questions/7550631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Which way has better accuracy to compute the matrix matrix vector product, A B u? I want to compute the vector, s = A B u, where s and u are N-dimensional complex vector, A is a N-by-M complex matrix, B is M-by-N complex matrix. Which of the following two ways has better accuracy (more significant digits) when the elements of A, B, and u are represented as floating-point numbers? (1) Computing B u first. First do the matrix-vector multiplication, y = B u Then, another matrix-vector multiplication s = A y (2) Computing A B first. First do the matrix-matrix multiplication, C = A B Then, matrix-vector multiplication s = C u Is there any known general rule? By the way, I understand that the method (1) is much more efficient than method (2). A: Matrix-vector multiplication has better numerical stability properties than matrix-matrix multiplication, so I would expect method (1) to be the more accurate one. In more detail, matrix-vector multiplication has nice forward and backward error bounds. If we take for instance the matrix-vector multiplication y = B u, then the error in y is bounded by 2n times the unit round-off (1e-16 when using standard double precision numbers) times the largest number in the matrix B times the largest number in the vector u. This is the forward error bound. The backward error bound is that the computed y is not precisely the product of B and u, but it is precisely the product of a slightly different matrix B' and the vector u. The difference between B and B' is bounded by 2n times the unit round-off times the largest number in the matrix B. For matrix-matrix multiplication, there is a forward error bound similar to the one for matrix-vector multiplication, but there is no nice backward error bound. This is a general principle: a computation with fewer outputs (such as matrix-vector multiplication) is more likely to be backward stable than a computation with more outputs (such as matrix-matrix computation). However, whether this makes any difference is another matrix. It may be that method (2) recovers backward stability because of the matrix-vector product which follows the matrix-matrix product. It may also be that for your particular application, there is not much difference, or even that method (2) is in fact more accurate. But, given that method (1) is certainly the faster one, and also possibly the more accurate one, I would definitely go for that option. Added 29 September 2011: My favorite source on this topic is Nicholas J. Higham, Accuracy and Stability of Numerical Algorithms, SIAM, 2002. But many textbooks on numerical analysis have a discussion about forward and backward error analysis, especially those books that concentrate on linear algebra. The forward error is fairly intuitive. If you know that B and u is correct, then what you are interested in is the difference between the product B u as computed and the exact product; this is what the forward error analysis tells you. Backward error comes into play when the matrix B is not correct (it may be the result from earlier computations that commit an error, or it comes ultimately from measurements that suffer from experimental or modelling errors). Suppose the error in B is 1e-10 and the backward error in the multiplication is smaller than this, say 1e-11. This means that although the result of the multiplication is not correct for the B that you gave to the algorithm, it is correct for another matrix B which is so close to the original B that it is just as likely to be the correct B as the B you gave to the algorithm. So in some sense this is as good as you can hope for. Forward and backward error analysis have different strengths: sometimes one applies, sometimes the other, sometimes a mixture. Ideally, an algorithm should have good forward and backward error bounds, but this does not happen very often. A: Except in cases where an algorithm is specifically designed to do extra work to compensate for numerical inaccuracy, an excellent rule of thumb is that given two ways to compute the same thing, the algorithm that does less work has better accuracy (after all, there are fewer opportunities to incur rounding). This is not universally true, so it doesn't remove the obligation to think about these things, but it's a good starting point. In your case, it happens to be exactly correct. Without knowing anything a priori about the specific values in your matrices, method (1) should be preferred. (It is possible to construct specific cases in which method (2) would be more accurate, but they are generally highly contrived).
{ "language": "en", "url": "https://stackoverflow.com/questions/7550632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ERR_TOO_MANY_REDIRECTS error u Fact: I am requesting root application on my browser http://localhost:8080/myapp and my browser throws this error: Error 310 (net::ERR_TOO_MANY_REDIRECTS): many redirects. Environment: I'm using Java 6, Glassfish 2.1, Struts2, Spring and Hibernate. Check: Then I look into web.xml and in welcome-list-files I have this: <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> So, let's check index.jsp and there is this redirection: ... <head> <meta http-equiv="refresh" content="0;url=<%=request.getContextPath()%>/portal/home.do"> ... <link rel="shortcut icon" href="<%=request.getContextPath()%>/img/icono.png" /> </head> ... Then we can go to struts.xml and we can see this chunk: ... <package name="portal-action" extends="portal-base" namespace="/portal"> <action name="home" method="home" class="beginAction"> <result type="tiles">begin.home</result> </action> ... Let's check beginAction class: ... public String home(){ return SUCCESS; } ... And we can check tiles.xml: ... <definition name="begin.welcome" extends=".baseHome"> <put-attribute name="working.region" value="/jsp/common/welcome.jsp" /> </definition> ... And finally we can view entire welcome.jsp file which only contains: <%@ taglib prefix="s" uri="/struts-tags"%> <br /> That's all! Do you have some idea about this issue? A: Just to state the obvious, it looks like your app is caught in a redirect loop. Looking at your configuration, I have no idea what the issue could be. I would try opening up a network monitor like Fiddler, or the "Network" tab in Chrome's developer tools and look at the response headers to see where it is trying to redirect you to ... that might help reveal what is going wrong here. A: I had this case in SharePoint 2013 REST API when calling /_api/web/lists/.... it returned no rows and just shows this error at error WFE error logs there were some errors with below details System.ServiceModel 4.0.0.0 3 WebHost Exception: System.ServiceModel.ServiceActivationException: The service '/_vti_bin/cellstorage.https.svc' cannot be activated due to an exception during compilation. The exception message is: Security settings for this service require 'Anonymous' Authentication but it is not enabled** for the IIS application that hosts this service.. it is said in the error and i remembered that we disabled 'Anonymous' Authentication for some reason last night in the SharePoint 8 via IIS re-enabling 'Anonymous' Authentication in IIS for Sharepoint app on port 80 fixed the problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7550635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android - onTabChanged not being invoked upon selecting a different tab Thanks for checking out my inquiry! I have implemented a tab environment as illustrated below. It seems to work as I expected except that it never executes the onTabChanged method. I have found several posts about this type of situation but have not been able to get my code to work the way I expected. Advice? Thanks, Chip public class TestTabActivity extends TabActivity implements OnTabChangeListener { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Resusable TabSpec for each tab Intent intent; // Reusable Intent for each tab intent = new Intent().setClass(this, Page1Activity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); spec = tabHost.newTabSpec("page1").setIndicator("Page 1", res.getDrawable(R.drawable.ic_tab_page1)) .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, Page2Activity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); spec = tabHost.newTabSpec("page2").setIndicator("Page 2", res.getDrawable(R.drawable.ic_tab_page2)) .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, Page2Activity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); spec = tabHost.newTabSpec("page3").setIndicator("Page 3", res.getDrawable(R.drawable.ic_tab_page3)) .setContent(intent); tabHost.addTab(spec); tabHost.setCurrentTab(0); } public void onTabChanged(String tabId) { Log.d("Tab Changed", "Changed a Tab"); } } A: I don't see that you register your class for a tab change with tabHost.setOnTabChangeListener(this). I would suggest to do that before tabHost.setCurrentTab(0). Even if it's not called on the first set of the tab you can manually call onTabChanged("page1") at the end of onCreate. Or did I missunderstood your problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/7550636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Should F# functions be placed in modules, classes, or another structure? I'm starting to code in F# and am calling functions from functions with functions as parameters - there are plenty of learning resources online. Now I am trying to put together the pieces into something more than just a collection of functions. Unfortunately I'm not finding many resources dealing with structure, design, or even how the 'bits' tie together. I've found the namespace keyword (e.g. namespace MyOnlyNamespace) but I get a compiler error on the functions that I've placed inside the namespace: Namespaces cannot contain values. Consider using a module to hold your value declarations. When I add module CoolFunctions I get Unexpected start of structured construct in definition. Expected '=' or other token So I have a multi-part question (but please answer any part that you can) * *What is a module? *Is it like a class (something like a VB.NET module) or is it something else altogether? *If something else, then are there classes in F#? *Are there other structures that I should be using instead? *How do I declare a module? A: concerning the design of F# components there is a very good draft online. JPalmer allready pointed you to the syntay problems but I think some other questions deserve more: What is a module? Yes JPalmer is right - modules are compiled into static classes but do we really care inside F#? IMHO you should use more modules than classes when programming in F#. In OOP you define your classes and the methods within. In FP you define simple types (without behaviour) and a bunch of functions to transform them. And the natural place to collect those functions is the module. Is it like a class (something like a VB.NET module) or is it something else altogether? A VB module is indeed a good comparision. If something else, then are there classes in F#? Yes you can use classes in F# - it's a complete .net languague and .net is OOP. You can do practically everything in F# you could do in C# of VB.net (only certain cases generic constraints can be a pain) Are there other structures that I should be using instead? No - collect your functions into modules but of course use records and abstract data-types for your data. How do I declare a module? Have a look at the online docs: Modules (F#) - there you will find everything you need. A: What is a module: A module is compiled down to a static class. But I think of modules as being analogous to namespaces in C# there are classes in F# - use type SomeType(constructor,args) = .... If you have namespace Name module Mod .... this won't compile - as you know, you can use a few alternatives module Namespace.Module as the first line in the file or namespace Name module Mod = .... A: To give some specific recommendations about choosing between namespaces, modules abd classes in F#: * *If you're writing functions using let that are expected to be used from F#, then putting them inside a module is the best choice. This gives you API similar to List.map and other basic F# functions. Regarding naming, you should use camelCase unless you expect C# users to call the functions too. In that case, you should use PascalCase (and note that module will be compiled to a static class). *If you're writing type delcarations, then these should generally be placed in a namespace. They are allowed inside modules too, but then they'll be compiled as nested classes. *If you're writing F# classes, then they should be placed in namespaces too. In generall, if you're writing F# code that will be called by C#, then using classes is the best mechanism as you get full control of what the user will see (F# class is compiled to just a class). If you have a file, it can either start with namespace Foo.Bar or module Foo.Bar, which places all code in the file inside a namespace or a module. You can always nest more modules inside this top-level declaration. A common pattern is to start with a single namespace and then include some type and module declarations in the file: namespace MyLibrary type SomeType = // ... module SomeFuncs = let operation (st:SomeType) = // ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7550638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How to add a tooltip for horizontal LED fusion chart I am using the following horizontal LED fusion chart in application http://www.fusioncharts.com/widgets/Gallery/HLED4.html how can i add a tooltip to indicate the current value A: The Horizontal LED gauge of the FusionWidgets pack does not support tool-tip, as of now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DirectShow: webcam preview and image capture After looking at a very similar question and seeing almost identical code, I've decided to ask this question separately. I want to show a video preview of the webcam's video stream to the default window DirectShow uses, and I also want the ability to "take a picture" of the video stream at any given moment. I started with the DirectShow examples on MSDN, as well as the AMCap sample code, and have something I believe should should the preview part, but does not. I've found no examples of grabbing an image from the video stream except using SampleGrabber, which is deprecated and therefore I am trying not to use it. Below is my code, line for line. Note that most of the code in EnumerateCameras is commented out. That code would've been for attaching to another window, which I don't want to do. In the MSDN documentation, it explicitly states that the VMR_7 creates its own window to display the video stream. I get no errors in my app, but this window never appears. My question then is this: What am I doing wrong? Alternatively, if you know of a simple example of what I am trying to do, link me to it. AMCap is not a simple example, for reference. NOTE: InitalizeVMR is for running in windowless state, which is my ultimate goal (integrating into a DirectX game). For now, however, i just want it to run in the simplest mode possible. EDIT: The first portion of this question, that is previewing the camera stream, is solved. I am now just looking for an alternative to the deprecated SampleGrabber class so I can snap a photo at any moment and save it to a file. EDIT: After looking for almost an hour on google, the general concensus seems to be that you HAVE to use ISampleGrabber. Please let me know if you find anything different. Testing code (main.cpp): CWebcam* camera = new CWebcam(); HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); MessageBox(NULL, L"text", L"caption", NULL); if (SUCCEEDED(hr)) { camera->Create(); camera->EnumerateCameras(); camera->StartCamera(); } int d; cin >> d; Webcam.cpp: #include "Webcam.h" CWebcam::CWebcam() { HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); //m_pTexInst = nullptr; //m_pTexRes = nullptr; } CWebcam::~CWebcam() { CoUninitialize(); m_pDeviceMonikers->Release(); m_pMediaController->Release(); } BOOL CWebcam::Create() { InitCaptureGraphBuilder(&m_pFilterGraph, &m_pCaptureGraph); hr = m_pFilterGraph->QueryInterface(IID_IMediaControl, (void **)&m_pMediaController); return TRUE; } void CWebcam::Destroy() { } void CWebcam::EnumerateCameras() { HRESULT hr = EnumerateDevices(CLSID_VideoInputDeviceCategory, &m_pDeviceMonikers); if (SUCCEEDED(hr)) { //DisplayDeviceInformation(m_pDeviceMonikers); //m_pDeviceMonikers->Release(); IMoniker *pMoniker = NULL; if(m_pDeviceMonikers->Next(1, &pMoniker, NULL) == S_OK) { hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&m_pCameraFilter); if (SUCCEEDED(hr)) { hr = m_pFilterGraph->AddFilter(m_pCameraFilter, L"Capture Filter"); } } // connect the output pin to the video renderer if(SUCCEEDED(hr)) { hr = m_pCaptureGraph->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video, m_pCameraFilter, NULL, NULL); } //InitializeVMR(hwnd, m_pFilterGraph, &m_pVMRControl, 1, FALSE); //get the video window that will be displayed from the filter graph IVideoWindow *pVideoWindow = NULL; hr = m_pFilterGraph->QueryInterface(IID_IVideoWindow, (void **)&pVideoWindow); /*if(hr != NOERROR) { printf("This graph cannot preview properly"); } else { //get the video stream configurations hr = m_pCaptureGraph->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, m_pCameraFilter, IID_IAMStreamConfig, (void **)&m_pVideoStreamConfig); //Find out if this is a DV stream AM_MEDIA_TYPE *pMediaTypeDV; //fake window handle HWND window = NULL; if(m_pVideoStreamConfig && SUCCEEDED(m_pVideoStreamConfig->GetFormat(&pMediaTypeDV))) { if(pMediaTypeDV->formattype == FORMAT_DvInfo) { // in this case we want to set the size of the parent window to that of // current DV resolution. // We get that resolution from the IVideoWindow. IBasicVideo* pBasivVideo; // If we got here, gcap.pVW is not NULL //ASSERT(pVideoWindow != NULL); hr = pVideoWindow->QueryInterface(IID_IBasicVideo, (void**)&pBasivVideo); /*if(SUCCEEDED(hr)) { HRESULT hr1, hr2; long lWidth, lHeight; hr1 = pBasivVideo->get_VideoHeight(&lHeight); hr2 = pBasivVideo->get_VideoWidth(&lWidth); if(SUCCEEDED(hr1) && SUCCEEDED(hr2)) { ResizeWindow(lWidth, abs(lHeight)); } } } } RECT rc; pVideoWindow->put_Owner((OAHWND)window); // We own the window now pVideoWindow->put_WindowStyle(WS_CHILD); // you are now a child GetClientRect(window, &rc); pVideoWindow->SetWindowPosition(0, 0, rc.right, rc.bottom); // be this big pVideoWindow->put_Visible(OATRUE); }*/ } } BOOL CWebcam::StartCamera() { if(m_bIsStreaming == FALSE) { m_bIsStreaming = TRUE; hr = m_pMediaController->Run(); if(FAILED(hr)) { // stop parts that ran m_pMediaController->Stop(); return FALSE; } return TRUE; } return FALSE; } void CWebcam::EndCamera() { if(m_bIsStreaming) { hr = m_pMediaController->Stop(); m_bIsStreaming = FALSE; //invalidate client rect as well so that it must redraw } } BOOL CWebcam::CaptureToTexture() { return TRUE; } HRESULT CWebcam::InitCaptureGraphBuilder( IGraphBuilder **ppGraph, // Receives the pointer. ICaptureGraphBuilder2 **ppBuild // Receives the pointer. ) { if (!ppGraph || !ppBuild) { return E_POINTER; } IGraphBuilder *pGraph = NULL; ICaptureGraphBuilder2 *pBuild = NULL; // Create the Capture Graph Builder. HRESULT hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder2, (void**)&pBuild ); if (SUCCEEDED(hr)) { // Create the Filter Graph Manager. hr = CoCreateInstance(CLSID_FilterGraph, 0, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void**)&pGraph); if (SUCCEEDED(hr)) { // Initialize the Capture Graph Builder. pBuild->SetFiltergraph(pGraph); // Return both interface pointers to the caller. *ppBuild = pBuild; *ppGraph = pGraph; // The caller must release both interfaces. return S_OK; } else { pBuild->Release(); } } return hr; // Failed } HRESULT CWebcam::EnumerateDevices(REFGUID category, IEnumMoniker **ppEnum) { // Create the System Device Enumerator. ICreateDevEnum *pSystemDeviceEnumerator; HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pSystemDeviceEnumerator)); if (SUCCEEDED(hr)) { // Create an enumerator for the category. hr = pSystemDeviceEnumerator->CreateClassEnumerator(category, ppEnum, 0); if (hr == S_FALSE) { hr = VFW_E_NOT_FOUND; // The category is empty. Treat as an error. } pSystemDeviceEnumerator->Release(); } return hr; } void CWebcam::DisplayDeviceInformation(IEnumMoniker *pEnum) { IMoniker *pMoniker = NULL; int counter = 0; while (pEnum->Next(1, &pMoniker, NULL) == S_OK) { IPropertyBag *pPropBag; HRESULT hr = pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag)); if (FAILED(hr)) { pMoniker->Release(); continue; } VARIANT var; VariantInit(&var); // Get description or friendly name. hr = pPropBag->Read(L"Description", &var, 0); if (FAILED(hr)) { hr = pPropBag->Read(L"FriendlyName", &var, 0); } if (SUCCEEDED(hr)) { printf("%d: %S\n", counter, var.bstrVal); VariantClear(&var); } hr = pPropBag->Write(L"FriendlyName", &var); // WaveInID applies only to audio capture devices. hr = pPropBag->Read(L"WaveInID", &var, 0); if (SUCCEEDED(hr)) { printf("%d: WaveIn ID: %d\n", counter, var.lVal); VariantClear(&var); } hr = pPropBag->Read(L"DevicePath", &var, 0); if (SUCCEEDED(hr)) { // The device path is not intended for display. printf("%d: Device path: %S\n", counter, var.bstrVal); VariantClear(&var); } pPropBag->Release(); pMoniker->Release(); counter++; } } HRESULT CWebcam::InitializeVMR( HWND hwndApp, // Application window. IGraphBuilder* pFG, // Pointer to the Filter Graph Manager. IVMRWindowlessControl** ppWc, // Receives the interface. DWORD dwNumStreams, // Number of streams to use. BOOL fBlendAppImage // Are we alpha-blending a bitmap? ) { IBaseFilter* pVmr = NULL; IVMRWindowlessControl* pWc = NULL; *ppWc = NULL; // Create the VMR and add it to the filter graph. HRESULT hr = CoCreateInstance(CLSID_VideoMixingRenderer, NULL, CLSCTX_INPROC, IID_IBaseFilter, (void**)&pVmr); if (FAILED(hr)) { return hr; } hr = pFG->AddFilter(pVmr, L"Video Mixing Renderer"); if (FAILED(hr)) { pVmr->Release(); return hr; } // Set the rendering mode and number of streams. IVMRFilterConfig* pConfig; hr = pVmr->QueryInterface(IID_IVMRFilterConfig, (void**)&pConfig); if (SUCCEEDED(hr)) { pConfig->SetRenderingMode(VMRMode_Windowless); // Set the VMR-7 to mixing mode if you want more than one video // stream, or you want to mix a static bitmap over the video. // (The VMR-9 defaults to mixing mode with four inputs.) if (dwNumStreams > 1 || fBlendAppImage) { pConfig->SetNumberOfStreams(dwNumStreams); } pConfig->Release(); hr = pVmr->QueryInterface(IID_IVMRWindowlessControl, (void**)&pWc); if (SUCCEEDED(hr)) { pWc->SetVideoClippingWindow(hwndApp); *ppWc = pWc; // The caller must release this interface. } } pVmr->Release(); // Now the VMR can be connected to other filters. return hr; } A: In windowless mode VMR would not create separate window. Since you started initialization for widnowless mode, you have to follow SetVideoClippingWindow with IVMRWindowlessControl::SetVideoPosition call to provide position within the window, see VMR Windowless Mode on MSDN. Another sample code snippet for you: http://www.assembla.com/code/roatl-utilities/subversion/nodes/trunk/FullScreenWindowlessVmrSample01/MainDialog.h#ln188
{ "language": "en", "url": "https://stackoverflow.com/questions/7550643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How does nerdinner show map? I want to show few countries marked with "pin" much like what the nerddinner has: http://nerddinner.com/ How can I achieve this functionality? Any details? A: For detail you can check out this article : Show Your Data on Google Map using C# and JavaScript which provide little info about google map api which help you to achieve your task.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How call customview on action of button? I have create a demo project in which i have add button. On button action i am calling a custom view. On that custom view i have add a picker view, a toolbar and bar button. On action of button i am calling that custom view. I have used this code... -(IBAction)Picker{ mpv_object = [[MyPickerView alloc] initWithNibName:@"MyPickerView" bundle:nil]; [self.view addSubview:mpv_object]; [mpv_object release]; } But i give error which i given below... 2011-09-26 09:49:00.236 Web[440:207] -[MyPickerView initWithNibName:bundle:]: unrecognized selector sent to instance 0x4b4dcb0 2011-09-26 09:49:00.287 Web[440:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyPickerView initWithNibName:bundle:]: unrecognized selector sent to instance 0x4b4dcb0' * Call stack at first throw: ( 0 CoreFoundation 0x00daebe9 exceptionPreprocess + 185 1 libobjc.A.dylib 0x00f035c2 objc_exception_throw + 47 2 CoreFoundation 0x00db06fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187 3 CoreFoundation 0x00d20366 __forwarding + 966 4 CoreFoundation 0x00d1ff22 _CF_forwarding_prep_0 + 50 5 Web 0x0000223a -[WebViewController Picker] + 102 6 UIKit 0x002b7a6e -[UIApplication sendAction:to:from:forEvent:] + 119 7 UIKit 0x003461b5 -[UIControl sendAction:to:forEvent:] + 67 8 UIKit 0x00348647 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527 9 UIKit 0x003471f4 -[UIControl touchesEnded:withEvent:] + 458 10 UIKit 0x002dc0d1 -[UIWindow _sendTouchesForEvent:] + 567 11 UIKit 0x002bd37a -[UIApplication sendEvent:] + 447 12 UIKit 0x002c2732 _UIApplicationHandleEvent + 7576 13 GraphicsServices 0x016e4a36 PurpleEventCallback + 1550 14 CoreFoundation 0x00d90064 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION + 52 15 CoreFoundation 0x00cf06f7 __CFRunLoopDoSource1 + 215 16 CoreFoundation 0x00ced983 __CFRunLoopRun + 979 17 CoreFoundation 0x00ced240 CFRunLoopRunSpecific + 208 18 CoreFoundation 0x00ced161 CFRunLoopRunInMode + 97 19 GraphicsServices 0x016e3268 GSEventRunModal + 217 20 GraphicsServices 0x016e332d GSEventRun + 115 21 UIKit 0x002c642e UIApplicationMain + 1160 22 Web 0x00001f80 main + 102 23 Web 0x00001f11 start + 53 ) terminate called after throwing an instance of 'NSException' What is error in this? A: It sounds like MyPickerView is a UIView subclass. initWithNibName:bundle is not a method that exists on UIView subclasses. It is a method that exists on UIViewController subclasses. That is what the error message means. A: unrecognized selector sent to instance suggests that MyPickerView's superclass doesn't know what initWithNibName:bundle is, which is because UIView doesn't know that method (it exists in UIViewController). A: Right way to do this would be something like this UIView *dpView; NSArray *nibViews; nibViews = [[NSBundle mainBundle] loadNibNamed:@"DatePickerSliderViewNew" owner:self options:nil]; dpView = [ nibViews objectAtIndex: 0]; int outside = CGRectGetMaxY(self.view.bounds); dpView.frame = CGRectMake(0, outside, 320, 260); [self.view addSubview:dpView]; [UIView beginAnimations:nil context:nil]; dpView.frame = CGRectMake(0, outside - 260, 320, 260); [UIView commitAnimations];
{ "language": "en", "url": "https://stackoverflow.com/questions/7550650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Representing an integer as the sum of four squares Given a positive integer m, find four integers a, b, c, d such that a^2 + b^2 + c^2 + d^2 = m in O(m^2 log m). Extra space can be used. I can think of an O(m^3) solution, but I am confused about the O(m^2 logm) solution.. A: First hint: What is the complexity of sorting squared elemnt from 1 to m^2 Second hint: Have a look at this post for some help : Break time, find any triple which matches pythagoras equation in O(n^2) Third Hint: If you need more help : (from yi_H response on the previous post): I guess O(n^2 log n) would be to sort the numbers, take any two pairs (O(n^2)) and see whether there is c in the number for which c^2 = a^2 + b^2. You can do the lookup for c with binary search, that's O(log(n)). author: yi_H Now compare n and sqrt(m) Hope you can figure out a solution with this. A: There is a classical theorem of Lagrange that says that every natural number is the sum of four squares. The Wikipedia page on this topic mentions that there is a randomized algorithm for computing the representation that runs in O(\lg^2 m) time (all the suggestions above are polynomial in m, i.e., they are exponential in the size of the problem instance (since the number m can be encoded in \lg m bits). As an aside, Lagrange's theorem proves the undecidability of the integers with plus and times (since the naturals are undecidable, and can be defined in the integers with plus and times, by virtue of the theorem).
{ "language": "en", "url": "https://stackoverflow.com/questions/7550651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: multiple string() results for an xpath? string() works great on a certain webpage I am trying to extract text from. http://www.bing.com/search?q=lemons&first=111&FORM=PERE has similar structure. For bing, the xpath I have tried is string(//h3/a) which works great to get the search results, even with strong tags etc, but only returns the first result. Is there something like strings(), so I can get the full text of each //h3/a result? A: Is there something like strings(), so I can get the full text of each //h3/a result? No, Not in XPath 1.0. From the W3C XPath 1.0 Specification (the only normative document about XPath 1.0): "Function: string string(object?) The string function converts an object to a string as follows: A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order." So, if you only have an XPath 1.0 engine available, you need to select the node-set of all //h3/a elements and then in your programming language that is hosting XPath, to iterate on each node and get its string value separately. In XPath 2.0 use: //h3/a/string() The result of evaluating this XPath 2.0 expression is a sequence of strings, each of which is the string value of one of the//h3/a elements. A: The MSDN documentation of string remarks that: The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results. This sounds like what you are experiencing. Why are you using string() at all? Use //h3/a/text()
{ "language": "en", "url": "https://stackoverflow.com/questions/7550652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: not getting response from url in android application I am developing an android application in which I have 5 items in a listview. I am not able to fetch my data in the listview,...I have tried all things,,,but nothing is dere in the listview My url is http://harpreetvir.web708.discountasp.net/PMevents/XmlRecord/AddEvent.xml My ddms logcat is http://pastebin.com/YH0JWiRJ Can anyone do the help? A: Kindly go through the following code posted. try { HttpClient client = new DefaultHttpClient(); String postURL = "http://harpreetvir.web708.discountasp.net/PMevents/XmlRecord/AddEvent.xml"; HttpGet post = new HttpGet(postURL); HttpResponse responsePOST = client.execute(post); HttpEntity resEntity = responsePOST.getEntity(); String str1=EntityUtils.toString(resEntity); str1=str1.trim(); parsing(str1); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } public void parsing(String str1) throws XmlPullParserException, IOException{ XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput( new StringReader (str1)); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String str; if(eventType == XmlPullParser.START_DOCUMENT) { System.out.println("Start document"); } else if(eventType == XmlPullParser.START_TAG) { str = xpp.getName(); System.out.println("Start tag "+str); } else if(eventType == XmlPullParser.END_TAG) { System.out.println("End tag "+xpp.getName()); } else if(eventType == XmlPullParser.TEXT) { System.out.println("Value= "+xpp.getText()); } eventType = xpp.next(); } System.out.println("End document"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7550665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: How safe is database packed with application I want to know how safe it is to pack the database with the application in android. Can the database be easily accessed by the users? As the database that I have will have data which I dont want to be hacked by users for misuse, what is the best way to protect the database in mobile apps? Also my application would use web service(contacting my own website) e.g. http:\www.mysite.com/services/xxx My site will in turn return some data to the mobile app. If someone decompiles the java code(in apk), he will easily get access to the URL i am using for web service. How can i protect my data on website to be attacked by malicious users. If anyone gets to know the URL, he can simply type that URL in browser and get all data in json format which i dont want as that data can be quite sensitive. Even if I keep it encoded, then the user can get to know the encoding from the java code(which he gets after decompiling apk). How to keep my DB safe from being misused? If my application is to show the local places like restaurants, bars etc on mobile should i always fetch them from the website using web service or provide a local database with these details so that information can be fetched quickly. In this case , I can provide a UPDATE web servcie which will update the local database. But security of local DB is of great concern to me. Can anyone please suggest where to keep the DB and how to safeguard it? Rgds, Sapan A: Local databases and your apk file can be read by any rooted device easily. This tool can even decompile your resources as explained in this youtube tutorial (I never tried that myself actually). So you would have to store your data encrypted in your database and decrypt it form your application code to be sure that noone can access it by simply getting the database form the data directory of his device. You shouldn't put your sensitive data (like passwords etc) in the resource folder, because it can be decompiled, put it in your code. Now some words to your JSON API. Hiding the URL is not enough, since the user can track your requests easily by a sniffer and get that anyway. You should provide a authentication mechanism to protect unauthorized access and also protect your communication by SSL. (E.g. using HTTP authentication - makes only sense when your server provides SSL.) This are the things you should think about and decide yourself how sensitive your data actually is. A: As far as I understand you're going to: * *Pack initial DB in your APK file (say with res/asset folder) *During first run explode DB file from res/asset to application data folder *Then from to time fetch data into DB from website/webservice In this case there are basically 2 vulnerabilities (stored data I mean): * *Initial DB image, since it's packed with APK (which is in real life just ZIP archive), so anyone can unpack and see what's packed in your DB *DB file stored in application data folder (usually /data/data/MY_APPLICATION_PACKAGE/databases). This folder is accessible on rooted device, so again your data can easily be screened The only option to be secured is to encrypt your database content. Easiest way to do it to store sensitive data in BLOBs (in form of XML of JSON) and encrypt/decrypt those BLOBs after/before actual usage of certain records. Myself personally did it in my app - and it works well. A: check this links for protecting your apk file for decompile How to make apk Secure. Protecting from Decompile Protecting Android apk to prevent decompilation, network sniffing etc decompiling DEX into Java sourcecode
{ "language": "en", "url": "https://stackoverflow.com/questions/7550672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Marking rows in NSTableView as dirty I subclassed NSTextFieldCell to do custom drawing and highlighting. I am essentially making a table with cells similar to the one found in Lion Mail, but my code is targeting Snow Leopard. The problem that I'm running into is this: * *user selects a cell (my cell draws a custom highlight) *user scrolls the selected cell and all previously visible cells so that they are no longer visible in the table *user selects an unselected cell (the new cell is highlighted) *user scrolls the table such that the initially selected cell is visible again in the table The last step is where the problem occurs; the initially selected cell is not being redrawn even though it is no longer selected. The consequence is that the cell appears to be selected. What do I have to do to signal that unselected cells must be marked as dirty? A: Use the selector setNeedsDisplay:.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Highlighted color keep on the table cell when I click back to the table in Objective-c I have a table view in my program, (1)when I click on a row, (2)it will be changed to a view, (3)If I click back button, it will go back to the table list. My problem is when I go back to the table list and the highlighted color still keep on the row, how can I erase the highlighted color after clicked on the row? Thanks (1) (2) (3) A: You can do this in you tableView:didSelectRowAtIndexPath: [tableView deselectRowAtIndexPath:indexPath animated:NO];
{ "language": "en", "url": "https://stackoverflow.com/questions/7550678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to merge multiple columns values into a single column? I have a source report which looks like Name Q1 Q2 Q3 Q4 A 1 2 3 4 B 5 6 7 8 C 9 0 1 2 It has to be converted into the following format Name Quarter Value A Q1 1 A Q2 2 A Q3 3 A Q4 4 and so on... I'm using SSIS for ETL. Any pointers without using hard-coded values in the T-SQL script? A: This would be a good match for UNPIVOT but unless you are willing to make this a dynamic sql statement, I don't see any way around hardcoding the Quarters in the statement. SQL Statement SELECT Name , Quarter , Value FROM q UNPIVOT ( Value FOR Quarter IN (Q1, Q2, Q3, Q4) ) u Test script ;WITH q (Name, Q1, Q2, Q3, Q4) AS ( SELECT 'A', 1, 2, 3, 4 UNION ALL SELECT 'B', 5, 6, 7, 8 UNION ALL SELECT 'C', 9, 0, 1, 2 ) SELECT Name , Quarter , Value FROM q UNPIVOT ( Value FOR Quarter IN (Q1, Q2, Q3, Q4) ) u
{ "language": "en", "url": "https://stackoverflow.com/questions/7550682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rename webstore products directory and redirect all its contents I want to rename our webstore products directory, and redirect all its contents, from /products/ to /Product/ using htaccess. The problem is that we have several individual domain names (mysite.com, mysite.co.uk) accessing this directory so the resultant htaccess code cannot specify a single destination domain such as .com A: As long as all domains/vhosts use the same namespace, you can use the same RewriteRule in all vhosts/.htaccess files: RewriteEngine On RewriteRule ^products/([^/\.]+.*) /Product/$1 [L] Good luck! Alex.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pinch Zoom/Multitouch functionality on Android GridView I am looking for an optimized way of implementing Pinch Zoom feature on my GirdView containing images. Why optimized? Because playing with Bitmaps any day gifts me with Out of Memory exception. Till date I have implemented the handling of Multitouch on screen by using switch (event.getAction() & MotionEvent.ACTION_MASK) in my onTouch event and getting to the case of "MotionEvent.ACTION_MOVE". Further I have been rebuilding the grid by calling the Adapter again and again on every case of pinch zoom in or out but one or the other moment I get out of memory exception. Also I have tracked the intensity of pinch by taking the difference of coordinates between the old touch point and new touch point (using the trigonometry formulae: [(x2-x1)^2 +(y2-y2)^2]^1/2 ). To summarize I am looking for help/suggestions on two points: 1) The way I have been tracking the intensity of Pinch Zoom in/out, is this a correct way? 2) What will be an optimized way of rebuilding the grid after the detection of pinch zoom in/out. Thanks. A: Extend the grid view and make your own class, make a custom grid view and set the gesturelistener in that gridview and it will work out(if u need it in version > android 2.1) , i think...!!!!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7550685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way of PHP with Oracle? I'm just new with Oracle. But i wanna test with PHP. Which way or method should i use is the best? I've found following various ways by googling yet, * *The oci8 extension *The oracle extension *PEAR DB library *ADOdb library *Zend *or otherelse? Actually i don't know know about these and which one is best. A: Unfortunately PDO support is still considered experimental. I've not read it, since I have no interest in oracle these days, but you might check out this oracle publication which I have not read.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CakePHP - Custom Route Controller Is there anyway for me to create dynamic custom routes? The goal is to allow users to specify any URL they want to route to any controllers/view/ structure. If user want to create something as below: /a_quick_brown_fox => foxes/view/42 /jumps_over => actions/view/42 /lazy_dog => dogs/view/42 And many others in the future without the need to edit routes.php I am unsure of a possible solution. I wish to allow user to input something like below Custom URL => [ ] Controller => [ ] ID for View => [ ] I will store it in a table to allow for unique URL checking, and what not. To allow scalability for new controllers I am okay with having prefix to slugs such as /l/<slug> I would then wish to insert some code that will retrieve the custom URL from table and allow the routing. Is it at all possible? Has anyone ever done it? A: I'm not sure whether you can define it directly into the routing system as you propose, however you could do something like this. First define all your applications controller/actions explicitly so that your users won't overwrite them. Then define a catch all route that will route to a controller of your choosing //default routes Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); //other //custom route Router::connect('/*', array('controller' => 'routes', 'action' => 'custom')); Your routes_controller/custom_action will receive whatever parameters the url contains, simply do a lookup on your DB from there and redirect to the correct route defined in your database. function custom() { //get values via $this->params } A: You can create custom route class, but I don't think you have access to POST data in it (you can access GET data and Cache, if that's enough). Probably the easiest way is redirect in the controller. A: The easiest way to do this is to have the routes controller do the saving of new routes and to cache saved routes. Each time a new route is added flush the cache and save it again. Then create a custom Route class that will pull the cache entries out and process them in the routes.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7550704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Umbraco and Telerik MVC Is this possible to install and use Telerik Extension for ASP.NET MVC in Umbraco project? If "yes", what is a best way to do this. I try to install but have some errors, eg: 'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'Telerik' and the best extension method overload 'Telerik.Web.Mvc.UI.HtmlHelperExtension.Telerik(System.Web.Mvc.HtmlHelper)' has some invalid arguments A: I assume your using Umbraco 4.7.1 or below, which is based on ASP.NET Web Forms (not MVC). If this is the case you wont be able to use any of the Telerik MVC Extensions. You may be able to use some of the Telerik controls for ASP.NET AJAX, but I've never tried that myself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the language of this deterministic finite automata? Given: I have no idea what the accepted language is. From looking at it you can get several end results: 1.) bb 2.) ab(a,b) 3.) bbab(a, b) 4.) bbaaa A: I guess this question isn't relevant anymore :) and it's probably better to guide you through it then just stating the answer, but I think I got a basic expression that covers it (it's probably minimizable), so i'll just write it down for future searchers (aa)*b(b)* // for stoping at 2 U (aa)*b(b)*a(aa)* // for stoping at 3 U (aa)*b(b)*a(aa)*b((a)*(b)*)* // for stoping at 5 via 3 U a(aa)*b((a)*(b)*)* // for stoping at 5 via 4 A: How to write regular expression for a DFA In any automata, the purpose of state is like memory element. A state stores some information in automate like ON-OFF fan switch. A Deterministic-Finite-Automata(DFA) called finite automata because finite amount of memory present in the form of states. For any Regular Language(RL) a DFA is always possible. Let's see what information stored in the DFA (refer my colorful figure). (note: In my explanation any number means zero or more times and Λ is null symbol) State-1: is START state and information stored in it is even number of a has been come. And ZERO b. Regular Expression(RE) for this state is = (aa)*. State-4: Odd number of a has been come. And ZERO b. Regular Expression for this state is = (aa)*a. Figure: a BLUE states = EVEN number of a, and RED states = ODD number of a has been come. NOTICE: Once first b has been come, move can't back to state-1 and state-4. State-5: comes after Yellow b. Yellow b means b after odd numbers of a. Once you gets b after odd numbers of a(at state-5) every thing is acceptable because there is self a loop for (b,a) at state-5. You can write for state-5 : Yellow-b followed-by any string of a, b that is = Yellow-b (a + b)* State-6: Just to differentiate whether odd a or even. State-2: comes after even a then b then any number of b. = (aa)* bb* State-3: comes after state-2 then first a then there is a loop via state-6. We can write for state-3 comes = state-2 a (aa)* = (aa)*bb* a (aa)* Because in our DFA, we have three final states so language accepted by DFA is union (+ in RE) of three RL (or three RE). So the language accepted by the DFA is corresponding to three accepting states-2,3,5, And we can write like: State-2 + state-3 + state-5 (aa)*bb* + (aa)*bb* a (aa)* + Yellow-b (a + b)* I forgot to explain how Yellow-b comes? ANSWER: Yellow-b is a b after state-4 or state-3. And we can write like: Yellow-b = ( state-4 + state-3 ) b = ( (aa)*a + (aa)*bb* a (aa)* ) b [ANSWER] (aa)*bb* + (aa)*bb* a (aa)* + ( (aa)*a + (aa)*bb* a (aa)* ) b (a + b)* English Description of Language: DFA accepts union of three languages * *EVEN NUMBERs OF a's, FOLLOWED BY ONE OR MORE b's, *EVEN NUMBERs OF a's, FOLLOWED BY ONE OR MORE b's, FOLLOWED BY ODD NUMBERs OF a's. *A PREFIX STRING OF a AND b WITH ODD NUMBER OF a's, FOLLOWED BY b, FOLLOWED BY ANY STRING OF a AND b AND Λ. English Description is complex but this the only way to describe the language. You can improve it by first convert given DFA into minimized DFA then write RE and description. Also, there is a Derivative Method to find RE from a given Transition Graph using Arden's Theorem. I have explained here how to write a regular expression for a DFA using Arden's theorem. The transition graph must first be converted into a standard form without the null-move and single start state. But I prefer to learn Theory of computation by analysis instead of using the Mathematical derivation approach. A: The examples (1 - 4) that you give there are not the language accepted by the DFA. They are merely strings that belong to the language that the DFA accepts. Therefore, they all fall in the same language. If you want to figure out the regular expression that defines that DFA, you will need to do something called k-path induction, and you can read up on it here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Scrolling problem with UITableView !I have a UITableviewController with a navigation bar as header. there are 4 sections in the table, Number of rows in the table are more than that can be fit in the iphone screen. while scrolling whole view is getting scrolled!!. I want the header to be stationary and only table to be moved. Also the last section is appearing twice! like this. Table view controller snapshot please help Thanks in advance A: First don't use Navigation bar as the header of TableView. You should use a navigation controller and push this viewcontroller which contains tableview. This will allow you to get rid of first problem i.e. to keep the bar steady and not scroll with the tableview. Second problem looks really weird, it seems to be that you have laid out two UITableView in your nib. Check again and remove one. A: You have two options: 1) add a base UIView on which your header view and your table view are siblings. 2) set the header view as the table view's viewForHeader of the first section A: You have only one option: 1)create a UIView lets say headerView and add control or whatever you want to have and put that custom UIView on top of your UITableView 2)Do not implement viewForHeaderInsection 3)Change the y position of your UITableView to place your tableView below your headerView
{ "language": "en", "url": "https://stackoverflow.com/questions/7550715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to develop an application similar to producer consumer in java? I have to develop an application that is similar to the producer-consumer problem in java. However I do not know a lot about java, and I have a couple of questions. Both the producer and consumer that are different threads and they both need to access the same buffer. If they are both different classes (that either extends thread class or implement the runnable interface) how do I code them to use the exact same buffer (this supposed buffer is an array of a certain object)? I also would like to read some suggestions about how the overall architecture and how should I implement them. I need to code them so that two threads don't consume the same buffer position at the same time, that two producer threads don't insert at the exact same value at the same time, producer can't insert a new item in an already filled buffer, and that no consumer should consume when the buffer is empty. In this example there must be several consumers and several producers working at the same time. I looked for some examples in java but they are all different of what I need. A: You can pass in a same instance of array or list to both consumer and producer by passing it through their constructor. Array a = new Array(); Consumer c = new Consumer(a); Producer p = new Producer(a); For the second question, you would like to learn about (google it!) for synchronization in Java. You can again pass in the same private Object lock1 = new Object(); to both consumer and producer and they can use it as a shared lock. http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html Whenever a consumer or a producer access the shared array, they would need to acquire lock first. Other conditional requirements such as 'not inserting elements when the array is full' or 'not consuming elements when the array is empty' can be implemented inside the synchronized block. public void add(Object someObject){ synchronized (lock1) { if(a.size()>limit) { System.out.println("Array is full"); } else { a.add(someObject) } } } A: Indeed in the java core library(version 1.5 or above),there are already data structures to meet your needs.Under the java.util.concurrent package,BlockedQueue,LinkedBlockedQueue..etc are all for concurrent using.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to move browser's scrollbar to a class? This script loads 10 more posts from peoples.php in index.php every time the button is pressed (through the loadfeed function). $("#loadmore").click(function() { cap += 10; loadfeed(); $(this).addClass("loading"); that = this setTimeout(function() { $(that).removeClass('loading'); }, 3000) }); My posts are in this format and the class in number ASC, using $i for every post. The class has nothing to do with my CSS, I added it now to explain my thought. <div id="post" class="p1"></div> <div id="post" class="p2"></div> <div id="post" class="p3"></div> . . . Every click on "load more" loads +10 posts. When a user enters in the page there is a default of 20 posts. This is how I add 10 posts. ... .load('people.php?cap='+cap, function () { ... When I click on "load more" I want the scrollbar to be in a predefined position and not at the end of the page as it does now. I tried to use in some places of the index.php but it is not ideal, not working as I want it. So when a user clicks "load more" at first, the posts loaded are 30 from the default 20. On second click are made 40. For now, the last post shown is the 20th, 30th, 40th.... How can I take the browser to the 21st, 31st, 41st post when the use clicks on #loadmore ? A: Use jQuery plugin scrollTo(). A: From memory, something like: window.scrollTo(0, $('#id-of-21st-element').offset()[1]) The key bits are window.scrollTo() and jquery's offset() A: Firstly each my must appear only once in each document. But classes can be affected to multiple elements and each element can own multiple classes. And theire is two solutions : 1 - pure html <a href="#anchorid">go to title</a> <!-- html code --> <h1 id="anchorid">title</h1> 2 - jquery $(document).ready(function() { $("a").click(function() { // here using jquery scroll plugin }); }); <a href="">go to title</a> <!-- html code --> <h1 id="anchorid">title</h1>
{ "language": "en", "url": "https://stackoverflow.com/questions/7550718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }