text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Could not find the main class, program will exit I made an executable jar with the command prompt in Windows 7 using the
jar cvfm MyJarName.jar manifest.txt *.class
which created the .jar file. But when I attempt to open it, I get a pop-up window that says
Could not find the main class: <ClassName>. Program will exit.
Yet, when I use
java -jar jarName.jar
in the command prompt, it works fine. What's the deal? I want to be able to just double-click it.
A: Ha, I found what the problem was. I made my program using jdk1.7, but I had jre6 installed. I went and upgraded to jre7, and now it works fine :)
The
java -jar jarname.jar
line was working in the command prompt because my java path was set to the jdk folder.
A: If you are using JDK 1.6 or higher then you can override the manifest attribute via e flag of Jar tool. (Read - Setting an Entry Point with the JAR Tool):
Example:
package pack;
public class Test
{
public static void main(String []args)
{
System.out.println("Hello World");
}
}
Compile and run Jar tool,
c:\>jar cfe app.jar pack.Test pack/Test.class
Invoke app
c:>java -jar app.jar
A: The Manifest text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.
A: I was facing the same problem. What I did is I right clicked the project->properties and from "Select/Binary Format" combo box, I selected JDK 6. Then I did clean and built and now when I click the Jar, It works just fine.
A: if you build the source files with lower version of Java (example Java1.5) and trying to run that program/application with higher version of Java (example java 1.6) you will get this problem.
for better explanation see this link. click here
A: I got this issue in opening JMeter 4.0. I fixed as below.
I have JRE 7 installed in Program Files (x86) folder and JDK 8 installed in Program files folder. So I just uninstalled JRE7 from machine. I just kept latest version of JDK. It fixed the problem.
A: Extract the jar and compare the contents of the manifest inside the jar with your external manifest.txt. It is quite possible that you will locate the problem.
A: Check out doing this way (works on my machine):
let the file be x.java
*
*compile the file javac x.java
*jar cfe k.jar x x.class //k.jar is jar file
*java -jar k.jar
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: I'm having trouble with the Node data structure -- trying to make it more efficient with loops So I'm having a bit of an issue with my code. My objective is to take an adjacency matrix from a file and input it into a 2d array. I was able to do that. Now I'm using the data structure for Breadth First Search and Nodes to work with that array.
Right now, I'm trying to simply create new Nodes, but I cannot make nodes due to being a char. Here let me post my full code. I'll post the error below.
package javaapplication1;
import java.io.*;
import java.util.*;
import tio.*;
import java.lang.*;
public class JavaApplication1 {
private static int row = 0;
private static int col = 0;
private static int n = 20;
private static int[][]adjMatrix = new int[n][n];
public static int[][] adjMatrix() throws FileNotFoundException, IOException{
//int n = 20;
//int row = 0;
//int col = 0;
//int[][]adjMatrix = new int[n][n];
String file = ("C:\\Users\\David\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\adjmatrix.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
//System.out.println(in.readLine());
int k = 0;
while ((line = in.readLine()) != null){
//System.out.println(row);
String[] temp = line.split("\\s+");
for(col = 0; col < adjMatrix[row].length; col++){
adjMatrix[row][col] = Integer.parseInt(temp[col]);
// System.out.println(" " + temp[col] + " " + col);
}
row++;
} //end while
//System.out.print(array[4][1]);
in.close();
return adjMatrix;
} // endclass
public static void main(String[] args)
throws IOException{
adjMatrix();
// Create the nodes (20 based off adj matrix given
Node nA =new Node('1');
Node nB =new Node('2');
Node nC = new Node('3');
Node nD = new Node('4');
Node nE = new Node('5');
Node nF=new Node('6');
Node nG=new Node('7');
Node nH=new Node('8');
Node nI=new Node('9');
Node nJ=new Node('10');
Node nK=new Node('11');
Node nL=new Node('12');
Node nM=new Node('13');
Node nN=new Node('14');
Node nO=new Node('15');
Node nP=new Node('16');
Node nQ=new Node('17');
Node nR=new Node('18');
Node nS=new Node('19');
Node nT=new Node('20');
// Create a graph, adding the nodes, and creating edges
Graph g = new Graph();
for (int i=1;i<=20;i++){
String aString = Integer.toString(i);
aString = n+aString;
g.addNode(aString);
}
// g.addNode(nA);
// g.addNode(nB);
// g.addNode(nC);
// g.addNode(nD);
// g.addNode(nE);
// g.addNode(nF);
// g.addNode(nG);
// g.addNode(nH);
// g.addNode(nI);
// g.addNode(nJ);
// g.addNode(nK);
// g.addNode(nL);
// g.addNode(nM);
// g.addNode(nN);
// g.addNode(nO);
// g.addNode(nP);
// g.addNode(nQ);
// g.addNode(nR);
// g.addNode(nS);
// g.addNode(nT);
// g.addNode(nU);
// g.setRootNode(nA);
// g.connectNode(nA,nB);
// g.connectNode(nA,nD);
// g.connectNode(nA,nE);
// g.connectNode(nA,nF);
// g.connectNode(nA,nG);
//
// g.connectNode(nB,nE);
// g.connectNode(nB,nF);
// g.connectNode(nB,nG);
//
// g.connectNode(nC, nD);
// g.connectNode(nC,nE);
// g.connectNode(nC,nF);
// g.connectNode(nC,nG);
//
// g.connectNode(nD,nE);
// g.connectNode(nD,nF);
//
// g.connectNode(nE, nF);
// g.connectNode(nE,nG);
//
// g.connectNode(nF,nG);
//
// g.connectNode(nH, nI);
// g.connectNode(nH,nJ);
// g.connectNode(nH,nK);
// g.connectNode(nI,nJ);
// g.connectNode(nI,nK);
// g.connectNode(nI,nL);
g.bfs();
} // end main
} // end class
I know that is a lot of code, but that is the reason why I would really like to not brute force the g.connectNode and the g.addNode. Anyways I can implement a loop for this?
Also, when I start doing "Node nJ=new Node('10');" it gives me errors since my Node is a char, any suggestions on bypassing that without breaking everything? The error is an unclosed character literal.
Here is the code for node.
public class Node {
public char label;
public boolean visited=false;
public Node(char l)
{
this.label=l;
}
}
Thank you for your help, and let me know if I need to edit or add anything.
A: First suggestion: put your nodes in an array or list, don't repeat the same thing 20 times.
Change your label's data type to String, and everything will be fine.
I am not sure how you define your Graph class. But you should really define your addNode method as
bool addNode(Node n) or something like that.
Another thing is to keep your data field private and provide getters and setters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Can't make tomcat-maven-plugin create a log file? I am running the mvn tomcat:run-war target, and get a directory structure that has a logs directory. But alas, no log. I would just replace this with log4j logging, but this has proven difficult for a variety of reasons.
I have tried explicitly setting the log file configuration. My pom.xml definition currently looks like:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
<port>8084</port>
<systemProperties>
<java.util.logging.config.file>${basedir}/src/main/webapp/WEB-INF/logging.properties</java.util.logging.config.file>
</systemProperties>
</configuration>
<version>1.1</version>
</plugin>
I see during startup that the property is being read. My properties file is below; I am dumping things to /tmp just to be sure I know where to look.
handlers = 1catalina.org.apache.juli.FileHandler, \
2localhost.org.apache.juli.FileHandler, \
3manager.org.apache.juli.FileHandler, \
java.util.logging.ConsoleHandler
.handlers = 1catalina.org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################
1catalina.org.apache.juli.FileHandler.level = FINE
1catalina.org.apache.juli.FileHandler.directory = /tmp/logs
1catalina.org.apache.juli.FileHandler.prefix = catalina.
2localhost.org.apache.juli.FileHandler.level = FINE
2localhost.org.apache.juli.FileHandler.directory = /tmp/logs
2localhost.org.apache.juli.FileHandler.prefix = localhost.
3manager.org.apache.juli.FileHandler.level = FINE
3manager.org.apache.juli.FileHandler.directory = /tmp/logs
3manager.org.apache.juli.FileHandler.prefix = manager.
3manager.org.apache.juli.FileHandler.bufferSize = 16384
java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = \
2localhost.org.apache.juli.FileHandler
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = \
3manager.org.apache.juli.FileHandler
I would be really grateful if anyone had any thoughts.
A: I've just been through a similar process, not entirely successfully...
The first thing to note is that you need to be clear if you want to change the logging configuration for your web application, or for Tomcat itself. See logging documentation on the Tomcat website for some details - in particular:
This means that logging can be configured at the following layers:
*
*Globally. That is usually done in the ${catalina.base}/conf/logging.properties file. The file is specified by the java.util.logging.config.file System property which is set by the startup scripts. If it is not readable or is not configured, the default is to use the ${java.home}/lib/logging.properties file in the JRE.
*In the web application. The file will be WEB-INF/classes/logging.properties
Having done this I am able reconfigure my application's logging, when deployed to a standalone Tomcat server. However I was unable to get this to work with the Maven Tomcat plugin - I then discovered that somebody had filed bug MTOMCAT-127 which at the time of writing is unresolved, and would seem to describe what I've been seeing.
So not entirely successful - but I hope I can come back and update this answer once the MTOMCAT-127 issue has progressed...
A: It's not really a tomcat plugin bug, what happens is if you choose the java api logging for the tomcat maven plugin you should know that there is a maven core library that also uses the java api logging called sisu-guice- 3.2.3-no_aop.jar (class is com.google.inject.internal.util.Stopwatch). This library instantiates the LogManager with the default values of the VM (INFO, etc) but not with the class that Tomcat needs to write its logs org.apache.juli.ClassLoaderLogManager. This class has an attribute called manager which is of type class, not instance. If we want to modify it, we must restart the VM but the Maven library sisu-guice-3.2.3-no_aop.jar will overwrite the LogManager and the RootLogger again.
Regarding the comment:
mvn tomcat7: run -Djava.util.logging.config.file = src / main / webapp / WEB-INF / classes / logging.properties
This is incorrect since this property is going to be set when the LogManager has already been instantiated.
One solution is to copy the mvn.bat to your working directory, but you have to edit it, adding to the classpath the dependency tomcat-embed-logging-juli-7.0.47.jar and the directory where you will keep your logging.properties with this already works that the SystemClassLoader will start it sooner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Basic jquery how to combine current slide/fade elements and fix opacity? Notice #element2, I have two functions but only the slide function works. I would like when you hover over it you start at 50% opacity and fade into 100%
Here's the code:
$("#element2").hover(function() {
$("#next").show("slide", { direction: "right" }, 300);
$("#next").fadeIn(300);
},
function() {
$("#next").hide("slide", { direction: "right" }, 300);
$("#next").fadeOut(300);
});
Here's the code in action:
http://jsfiddle.net/pQzWp/9/
A: There is an excellent answer here:
http://css-tricks.com/snippets/jquery/combine-slide-and-fade-functions/
You should use animate. In your particular case, I believe the following should work:
$("#next").animate({opacity: 'toggle', width: 'toggle'}, 300);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should I use self. when releasing I have a whole bunch of @property (nonatomic, retain) stuff going on when I'm defining my variables and i want to know:
In my dealloc method, should i release them [myGreatVariable release]; or [self.myGreatVariable release];. They are currently done in the former way. And how much does this really matter? Is it just good to get in the habit of doing this from now on, or should I go back and change all of them in all of my classes because things aren't actually getting released.
A: Don't use [self.myGreatVariable release]. As Daniel notes, it will work in this context, but it is the most "bastardized" version, and would do the wrong thing anywhere outside -dealloc by likely leaving around a garbage reference in a property.
You should choose one of, and standardize on, either:
*
*[myGreatVariable release];
*self.myGreatVariable = nil;
(The choice is largely a personal preference. I only use the first form in dealloc, because setters are sometimes nontrivial and have side-effects, and the goal of dealloc is to get efficiently and clearly get rid of all the resources, not to get tripped up with accidental state changes.)
A: If you're in dealloc it doesn't matter, though the former is an itty bit more efficient. But you have the 3rd option of doing self.myFairlyGoodVariable = nil;, which relies on the setter method to do the release (though two or three itty bits less efficiently).
I suspect you'll find different arguments for what you should do. Some folks argue you should use the instance variable (sans self.) for all read accesses. Others will argue that you should use the property access (ie, with self.) pretty much everywhere. I tend to fall into the latter camp, but I could accept arguments from the other side.
It's important to be reasonably consistent, though. And if you work with others it's good if you can have a team "standard" for this.
(One thing I like to do is to put the dealloc method at the top of the .m file, vs at the bottom where it usually ends up. This way you will be more likely to remember to update the dealloc method when you add/change a property and the associated @synthesize statement.)
A: The one problem with using "self.variable = nil" in dealloc is that it can trigger additional actions if you have overridden "setVariable". For example, some classes will signal a delegate whenever a variable changes values but you probably don't want to do that once you are in dealloc. It's a bit safer to use "[variable release]".
Hopefully ARC will make all of this go away soon.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gamma-curve experiment -- convert 2.2 to opposite of 1.8? The Motorola Photon is infamous for exhibiting what others have called "black crush" -- when viewing pictures, most of the detail in dark parts of the image is flattened out to black. Up to now, pretty much everyone has blamed it on the Pentile display. HOWEVER, the first time I ever saw the effect, a different thought occurred to me... "Wow, that looks the same (bad) way that pictures encoded for Windows used to look on Linux and Macintosh back when they used gamma of 1.8 instead of Windows' norm of 2.2". My theory is that somewhere along the line, Motorola built the Photon's Android using an old library written back when Motorola was a pre-iPhone Apple partner (or possibly, grabbed old open-source code that assumed 1.8 gamma instead of 2.2).
Why am I so sure? A few days ago, I did a screen capture of the same web page using both my old Epic 4G (Samsung Galaxy S) and my new Photon. Unexpectedly, the Epic's screen capture .png looked normal, but the Photon's screen capture .png had exactly the same bad appearance when viewed on my PC as it did when viewed on the Photon's screen. The moment I saw it, I remembered my earlier thought about a possible gamma-mapping 1.8-vs-2.2 bug, and decided to try and write a demonstration app to show Motorola and convince them that this is a real bug that CAN be fixed.
One experiment I'd like to do would be to take a JPEG image with high dynamic range and detail in both bright and dark areas, and re-encode it to a nonstandard gamma that's basically double the difference between 1.8 and 2.2. The idea is that if I intentionally mis-encode it to the opposite extreme (2.6?), then lie in the metadata and say it's 2.2, it will look normal when viewed on the photon (because the same error that crushes 2.2 down to 1.8 will crush 2.6 down to the proper 2.2).
So, two questions:
*
*What gamma would be equal and opposite the error you'd get if a 2.2 gamma image were decoded as though it were 1.8? 2.6?
*Is there any easy way (free Photoshop/gimp plug-in, JPEG encoding library, etc) to intentionally mis-encode a source image to that nonstandard gamma?
A: When gamma is applied to an image, you start with linear values in the [0.0-1.0] range and raise them to the power of 1/gamma, which gives a result that is also in the [0.0-1.0] range. For a gamma of 1.8 you raise it by 0.56, and for a gamma of 2.2 you raise it by 0.45.
If you've applied a standard 2.2 gamma and you need a 1.8 gamma instead, you raise it again by the ratios of the two correction factors: 0.56/0.45 = 1.22.
Since pixel values are usually in the range of [0-255], you need to divide by 255 before the conversion and multiply by 255 when finished.
I'm not sure if Photoshop or Gimp can do this simply; I know Paint Shop Pro has a command for it.
The definitive resource for anything gamma related is Charles Poynton's Gamma FAQ.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is there a way or technology to implement database resource allocation based on user? Typically, when platforms want to provide database resource to user (developer) for applications development, they use limit database access APIs to restrict behaviors of the application, in order to enforce some constraints on resources occupied, an example is social API.
Is there a same way that we can implement and use in database layer, nor application layer. If then, we just need to assign database quota for specific user and let database handle the resource usage. Furthermore, it's better to have some programming APIs from database server to support this.
I found some similar questions, as follow:
*
*Oracle [might has]: Is there a way to throttle or limit resources used by a user in Oracle?
*MySQL [no]: https://serverfault.com/questions/124158/throttle-or-limit-resources-used-by-a-user-in-a-database
*SQL Server [not sure]: Databases with utilization constraints
Since i am focus on open source solutions, how about PostgreSQL or NoSQL? As open source database, I think PostgreSQL compares better favourably with Oracle.
A: With MySQL (which is currently released under the open source GPL license), you can impose the following resource limits inside the database:
The number of queries that an account can issue per hour
The number of updates that an account can issue per hour
The number of times an account can connect to the server per hour
The number of simultaneous connections to the server by an account
For postgres, their wiki states:
PostgreSQL has no facilities to limit what resources a particular user, query, or database consumes, or correspondingly to set priorities such that one user/query/database gets more resources than others. It's necessary to use operating system facilities to achieve what limited prioritization is possible.
But the question to me really is -- no matter which database is used -- what is the expectation when a user exceeds their limits? If the database enforces limits, should queries beyond those limits simply return an error and cause the application to fail? I'd suspect that this might have unexpected negative impacts on the applications. It's hard to say what will happen when suddenly the database starts returning errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Modify the query that generates the exposed form element in Drupal I would like to change the dropdown filter in a view, by modifying the query that generates it. I do not want to modify the form values after they got pouplated with data already, because it is huge list.
Is there a hook like this view-query modifier for the exposed filter generation query?
function MYMODULE_views_query_alter(&$view, &$query)
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: byte[] to File Type in MVC 3 In my MVC application, I recently have configured a page to allow an arbitrary file type to be uploaded(with certain restrictions that dont apply to this question).
I am storing the file as data type byte[] in the database, with the stored file type based off of the file extension(Please dont try to give me a better option for storing these files, I am well aware that storing files in the database is not a good practice, but we have a constraint that requires that we persist these files using SQL Server.)
As I was saying, to make this even worse, I am storing the byte[] array of the file in a column in the database which is of type text. This is only done so I dont have to worry about restrictions with the varbinary type.
What I want to know is, when a file is requested, what is the best way in MVC to return these files to the user with a specified file extension?
I have been able to do this before with excel files and an AJAX call to a "GET" action on my controller, but I want to know if there is a better way to do it.
Any suggestions?
Example: If I have the following code
string fileExtension = /*Some File Extension*/
byte[] data = MyDataContext.DocumentTable.First(p => p.DocumentUID == id);
How can I then return this data to the user in the specified file format using the fileExtension that was originally persisted.
EDIT I am guessing that FileResult will be one of the easiest ways to accomplish this.
A: You would return a FileContentResult.
In you controller, something like this:
byte[] data = MyDataContext.DocumentTable.First(p => p.DocumentUID == id);
return File(data, "text/plain", "myfile.txt");
In addition to the extension of the file, you need to specify a name for it as well. The 2nd parameter is the MIME type. This is important for some browsers (like FireFox) to determine which application to open your file with. Firefox will prefer the MIME type over the extension.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Scala XML Marshaling using combinator from Scala GData This questions is related to this thread regarding the use of XML combinator which is part of the Google's Scala gdata client library found here
*
*In the code posted, there was no parameter for elem("segment"...) Wouldn't this cause compiler to complain something like "could not find implicit value for parameter ns: (String, String)"
*How do you generate XML elements without each tag having a name space prefix added. For example, the code I generated looks like:
<yt:entry xmlns:yt="http://gdata.youtube.com/schemas/2007">
<yt:title type="TextType">MyTitle</yt:title>
<yt:summary>My Summary</yt:summary>
</yt:entry>
But I don't want each tag to have the namespace prefix!! How do I use the combinator to generate such XML.
Here is what my pickler looks like:
def pickler: Pickler[YtPlaylist] = {
(wrap (elem("entry",
elem("title", text ~ attr("type", text))
~ elem("summary", text))(Uris.ytNs))
(YtPlaylist.apply)
({p => new ~(p.title, p.titleType) ~ p.summary}))
}
case class YtPlaylist(title: String, titleType: String, summary: String)
The example I found on the web doesn't specify the namespace, but without it I always gets compilation error. How do I generate XML elements without namespace??
A: Yes, you will need to define a namespace. Use the null prefix to define the default namespace:
implicit val ns = (null: String, "http://gdata.youtube.com/schemas/2007")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Plotting and Saving as File in MATLAB I need to plot and save to image file in MATLAB. Here is the code that I am calling inside a 'for' loop:
figure
scatter(data_x_pos,data_y_pos,'r*')
hold on
scatter(data_x_neg,data_y_neg,'b')
t = linspace(-80,80);
y = -model.w(1)*t/model.w(2);
plot(t,y,'k');
% need to save this plot to image to a file here
Now, this is starter code that I am using for some work and I don't understand it completely (example - the command 'figure'). There have been suggestions to use saveas or print but I believe I need handles for them. Could someone help me out here?
Thanks.
A: An alternative solution that may aid some is to take advantage of the fact that Matlab updates a variable called gcf "get current figure handles" each time a figure is created. Even if a handle is not expressly created with the f = figure(); handle declaration command, you can still use commands such as print() and saveas() by calling the gcf handle variable. For example, this block of code might also function for others who do not have the OP's requirement to operate within a large for loop with uniquely identified figures:
scatter(data_x_pos,data_y_pos,'r*')
hold on
scatter(data_x_neg,data_y_neg,'b')
t = linspace(-80,80);
y = -model.w(1)*t/model.w(2);
plot(t,y,'k');
hold off;
saveas(gcf,'filename','png')
A: figure() is a function which returns a handle to the figure:
f = figure()
scatter(data_x_pos,data_y_pos,'r*')
...
You can then use this handle to save the figure:
saveas(f, 'image.png');
Take a look at the tutorials on Handle Graphics to learn more.
scatter, and plot also return handles to the collection of points, or the lines, or whatever, they've plotted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: NTLM Security - how long before it times-out and is not valid A user on a mobile device navigates to a web site/page protected by windows ntlm security. The user provides their credentials and uses the site. They walk away and return later and they are not required to re=enter their credentials..
Question: What determines how long the authentication is valid? How best can we limit the time that it is valid before they have to re=enter their windows credentials?
thx
A:
What determines how long the authentication is valid?
Simply put, your application. Any request aimed at a protected resource is going to force the whole SPNEGO process.
SPNEGO works by essentially by the server sending a HTTP 401 response to the initial request with a header indicating that it will support Negotiate or NTLM, etc. authentication. Remember HTTP is stateless. Of course, the SPEGNO protocol somewhat works around this by maintaining server-side state on a per-connection basis; nevertheless, this can always be controlled by the server by either 1) closing the connection or 2) Sending the initial 401 response to the client forcing a SPNEGO handshake.
How best can we limit the time that it is valid before they have to re-enter their windows credentials?
The important thing to realize here is that many user-agents (i.e., browsers) are going to cache the user's credentials once they've been entered and simply use those to reply to any negotiate challenges (this is similar to how they handle Basic authentication). Any way of "forcing" the user to re-enter their credentials is going to have to be a little tricky, since the user-agent is essentially tricking the server into believing that the user has re-entered their password (technically, SPNEGO only provides verification that the user-agent knows the user's id and password -- the protocol itself has no way of verifying that anyone actually typed anything on the device keypad).
Off the top of my head, what might work (and I don't know how you can do something like this without writing your own SPNEGO handler server-side) is to trick the user-agent into invalidating is credential cache. To do this, your server would need to send the initial HTTP 401 to start the SPNEGO negotiation and then, when the client has responded with the first step of the handshake, resend an initial 401 error. The problem here is that how this is handled is going to be heavily dependent on the user-agent in question. Some will likely prompt the user to verify their credentials (since, from the client's perspective, the server is saying that the credentials are wrong), but other's may just show the error page, which is probably undesirable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use Image.ANTIALIAS with resize() in GAE? I am using the script below to resize images. But I noticed that the resized image looses sharpness. According to this page Image.ANTIALIAS is the best "downsizing filter". But when I add the filter to the code
images.resize(homepage.original_image, 200, 200, Image.ANTIALIAS)
I get
AttributeError: type object 'Image' has no attribute 'ANTIALIAS'
Is there a way around this? Thanks
class ImageResize(webapp.RequestHandler):
def get(self):
q = HomePage.all()
result = q.fetch(3)
for item in result:
firm = item.firm_name
id = item.key().id()
if id:
homepage = HomePage.get_by_id(id)
if homepage:
thumbnail = images.resize(homepage.original_image, 200, 200)
homepage.thumbnail = db.Blob(thumbnail)
homepage.put()
A: The documentation you linked is for PIL but you're using the Google App Engine images API, the documentation for which is here: http://code.google.com/appengine/docs/python/images/functions.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the difference between Carp/Croak, Cluck/Confess, and verbose options? I haven't used Carp all that much because I've generally rolled my own. However, in the spirit of keeping with Core modules, I'm using it now. However, it seems like it's barely better than warn/die.
Furthermore, what does cluck/confess/verbose even do? I've ran this short script to get an idea of the output looks like (because the Carp docs don't do it). It looks exactly the same on any run (besides the random strings).
#!/usr/bin/perl
package Warning;
sub warning {
warn "warn";
}
package CWarn;
use Carp qw(carp cluck);
sub cwarn {
int(rand(2)) ? carp "carp" : cluck "cluck";
}
package Fatal;
use Carp qw(confess croak);
sub fatal {
int(rand(2)) ? confess "confess" : croak "croak";
}
package Loop;
use v5.10;
sub loop {
say '=' x 80;
Warning::warning();
CWarn::cwarn();
loop() unless ($c++ > 10);
Fatal::fatal();
}
package main;
Warning::warning();
CWarn::cwarn();
Loop::loop();
UPDATE: Updated the script with package names and it does make a difference. However, Carp still seems to be very basic in terms of logging information, and it doesn't support web output. I guess I'll look at other ones like CGI::Carp, Log::Output, and Log::Log4Perl.
A: Carp is better than warn/die in that it will display the file and line of what called the function throwing an error, rather than simply where the error was thrown. This can often be useful for libraries. (For instance, a database library should probably throw errors indicating where the erroneous database call is, rather than indicating a line within itself.)
carp, cluck, croak, and confess give you four combinations of options:
*
*carp: not fatal, no backtrace
*cluck: not fatal, with backtrace
*croak: fatal, no backtrace
*confess: fatal, with backtrace
A: The problem with your example is that all your subs are in the same package (the default package: main). That's not the use case that Carp was designed for.
Carp is intended to be used in modules. The reason is that when a module encounters a problem, it's often because the module's caller passed it bad data. Therefore, instead of reporting the line where the module discovered the problem, it's usually more useful to report the line where the module was called (from code outside the module). That's what the functions exported by Carp do.
There are 2 sets of yes/no options. The function can be fatal (like die) or nonfatal (like warn). It can report just the line where the function was called, or it can report a full backtrace.
Fatal Backtrace
carp N N
cluck N Y
croak Y N
confess Y Y
The verbose option forces backtraces on. That is, it makes carp act like cluck, and croak act like confess. You can use that when you realize that you need more debugging information, but don't want to change the code to use confess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "61"
} |
Q: Iterating in two extremely large files simultaneously in Java I need to merge two very large files (>1G each) by writing 4 lines from the first into an output file, than write 4 from the second. And so on till the end. Both files have same number of lines and this number is divisible by four. What's the most efficient way to do it in Java?
A: I love to use Decorator pattern. Create two classes, each class represents a BufferedReader instance.
For instance,
class First
{
BufferedReader br;
...
public String getLine()
{
return br.readLine();
}
}
class Second
{
BufferedReader br;
...
public String [] getLines()
{
//read four lines and return it
}
}
A: try this and see how long it takes. adjust n accordingly. if it's too slow try using nio.
import java.io.*;
class Time {
Time() {}
long dt() {
return System.currentTimeMillis() - t0;
}
final long t0 = System.currentTimeMillis();
}
public class Main {
public static void create(File file1, File file2, int n) throws Exception {
BufferedWriter bw1 = new BufferedWriter(new FileWriter(file1));
write(bw1, n, "foo");
bw1.close();
BufferedWriter bw2 = new BufferedWriter(new FileWriter(file2));
write(bw2, n, "bar");
bw2.close();
}
private static void write(BufferedWriter bw, int n, String line) throws IOException {
for (int i = 0; i < n; i++) {
bw.write(line);
bw.write(lineSeparator);
}
}
private static void write4(BufferedReader br1, BufferedWriter bw, String line) throws IOException {
bw.write(line);
bw.write(lineSeparator);
for (int i = 0; i < 3; i++) {
line = br1.readLine();
bw.write(line);
bw.write(lineSeparator);
}
}
public static void main(String[] args) throws Exception {
File file1 = new File("file1");
File file2 = new File("file2");
if (!file1.exists()) {
create(file1, file2, 10000000);
}
File file3 = new File("file3");
Time time=new Time();
BufferedReader br1 = new BufferedReader(new FileReader(file1));
BufferedReader br2 = new BufferedReader(new FileReader(file2));
BufferedWriter bw = new BufferedWriter(new FileWriter(file3));
String line1, line2;
while ((line1 = br1.readLine()) != null) {
write4(br1, bw, line1);
line2 = br2.readLine();
write4(br2, bw, line2);
}
br1.close();
br2.close();
bw.close();
System.out.println(time.dt()/1000.+" s.");
}
static final String lineSeparator = System.getProperty("line.separator");
}
A: Sorry if this idea was already given :)
I think the fastest way to do this is by creating 3 threads. t1 & t2 will be reading from the two input files, each thread will have its own queue (which is thread safe) and the thread will read 4 lines and put them in its queue. t3 will be the writing thread, it will interchangeably read nodes from the two queues and put them in the new merged file. I think this is a good solution because it allows parallel i\o to all three files (and i\o is the bottle neck here..) and minimum interaction between the threads.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is causing a SIGSEGV using blocks? I have the following code. I get a SIGSEGV occasionally. I have a feeling I'm missing something regarding memory management using blocks. Is it safe to pass the replacedUrls, which is autoreleased to this block? What about modifying the instance variable formattedText?
NSMutableSet* replacedUrls = [[[NSMutableSet alloc] init] autorelease];
NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:
(NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber)
error:&error];
if (error) {
return;
}
[detector enumerateMatchesInString:self.formattedText
options:0
range:NSMakeRange(0, [self.formattedText length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
@try {
if (result.resultType == NSTextCheckingTypePhoneNumber) {
if (!result.phoneNumber) {
// not sure if this is possible
return;
}
self.formattedText = [self.formattedText stringByReplacingOccurrencesOfString:result.phoneNumber
withString:[NSString stringWithFormat:@"<a href=\"tel://%@\">%@</a>", result.phoneNumber, result.phoneNumber]];
}
else if (result.resultType == NSTextCheckingTypeLink) {
if (!result.URL) {
// not sure if this is possible
return;
}
NSString* fullUrl = [result.URL absoluteString];
if (!fullUrl) {
return;
}
if ([replacedUrls containsObject:fullUrl]) {
return;
}
// not sure if this is possible
if ([result.URL host] && [result.URL path]) {
NSString* urlWithNoScheme = [NSString stringWithFormat:@"%@%@", [result.URL host], [result.URL path]];
// replace all http://www.google.com to www.google.com
self.formattedText = [self.formattedText stringByReplacingOccurrencesOfString:fullUrl
withString:urlWithNoScheme];
// replace all www.google.com with http://www.google.com
NSString* replaceText = [NSString stringWithFormat:@"<a href=\"%@\">%@</a>", fullUrl, fullUrl];
self.formattedText = [self.formattedText stringByReplacingOccurrencesOfString:urlWithNoScheme
withString:replaceText];
[replacedUrls addObject:fullUrl];
}
}
}
@catch (NSException* ignore) {
// ignore any issues
}
}];
A: It seems that the issue you are experiencing is one related to memory management. You begin by searching through the string self.formattedText. This means that, while this search takes place, your NSDataDetector instance probably needs to access the string to read characters, etc. This works all fine and nice, as long as self.formattedText doesn't get deallocated. Usually, even for block methods like this, it is the caller's responsibility to retain the arguments until the end of the function call.
When, inside of your match found block, you change the value of self.formattedText, the old value is automatically released (assuming that this is a retain property). I am not aware of caching that NSDataDetector might do, or issues pertaining to autorelease pools, etc., but I am pretty certain that this could cause an issue.
my suggestion is that you pass [NSString stringWithString:self.formattedText] as the enumerateMatchesInString: argument, rather than the plain self.formattedText. This way, you pass the NSDataDetector an instance that won't be released until the autorelease pool is drained.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: CSS hover image link not working in Internet Explorer Please refer http://solarisdutamas.com/fb/KonzeptGarden/sample.php, mouse over to "Pebbles Wash" and click the image. It working fine in Chrome and Firefox, but the link not working in IE.
Here's my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Konzept Garden</title>
<style type="text/css">
* {margin: 0; padding: 0;}
#main {
width: 520px;
height: 228px;
background-image: url(stone.jpg);
background-repeat: no-repeat;
position: relative;
margin: 0 auto;}
#main ul li {
list-style: none;
display: inline;}
#main ul li:hover {
visibility: visible;}
#main ul li a {
position: absolute;
z-index: 1;}
#main ul li a:hover {
z-index: 100;}
#main ul li img {
position: absolute;
top: 300px;
right: 999em;}
#submain1 .butt1 a {
left: 8px;
top: 80px;
width: 90px;
height: 32px;}
#main ul .butt1:hover img {
left: 8px;
top: 80px;}
</style>
</head>
<body style="margin: 0px; width: 520px;">
<div id="main">
<ul id="submain1">
<li class="butt1"><a href="http://konzeptstone.com/p_pebbles.html" target="_blank"></a><img src="p1.png"></li>
</ul>
</body>
</html>
Does anyone have any idea why this doesn't work in IE?
A: If you are using earlier versions of IE, it has issues with :hover.
http://reference.sitepoint.com/css/pseudoclass-hover
A: I know this is an overkill but this will ensure it works even on I.E. 6:
#submain1 .butt1 a:link, a:active, a:visited {
left: 8px;
top: 80px;
width: 90px;
height: 32px;
display:block;
overflow: hidden;
}
then:
<li class="butt1"><a href="http://konzeptstone.com/p_pebbles.html" target="_blank"> </a><img src="p1.png"></li>
.
A: One option is to use jQuery if you have it installed. Like Jason said, :hover doesn't work in IE6 and below, for anything OTHER than anchors.
Assuming you can use jQuery, the solution would be:
$('#main ul li').hover(function(){
$(this).show();
});
Another option using jQuery would be adding a class dynamically on Hover.
$('#main ul li').hover(function(){
$(this).addClass('hoverState');
});
And then the CSS would be:
#main ul li.hoverState {
visibility: visible;}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Emacs doesn't recognize C-/ in shell over ssh I am using Emacs in shell mode through Bash in Mac Terminal, and Emacs doesn't recognize C-/ as the undo key. It seems not to recognize C-/ at all actually, as nothing happens when I use C-hkC-/ (i.e. describe-key then C-/). Any ideas? Undoing with C-xu is intolerable.
Thanks.
A: The problem here is that Emacs believes any modifier key (control, shift, meta etc) can be applied to any regular key. This is true when Emacs is talking directly to the OS, but not when it's running inside a traditional (pseudo-)terminal, which is what you've got when you're using emacs inside ssh. In that case, only the modified keys that map to traditional ASCII control characters can be used. C-/ is not one of those keys.
The good news is, because Emacs dates back to the days when ASCII terminals were the only game in town, there's another binding for undo that is an ASCII control character: C-_ (control-underscore, aka control-shift-minus, aka U+001F UNIT SEPARATOR).
Yr hmbl crspdt was in fact not aware C-/ did anything; he also dates back to those days, and C-_ is what is wired into his fingers. He cannot say whether you will find this keystroke tolerable -- it does involve the use of both Control and Shift -- but he suspects it's less bad than C-x u.
A: The terminal cannot send C-/. All you need is a way to send an undo alias like C-_ when C-/ is typed. There are two relatively easy ways to do this:
*
*Use iTerm 2 instead of Mac Terminal. It remaps the key out of the box.
*Use KeyRemap4MacBook to remap C-/ to C-_ in Mac Terminal.
*
*Install KeyRemap4MacBook.
*Reboot.
*Open System Preferences > KeyRemap4MapBook
*Enable the following Change Key option (search for "control+slash"):
For Applications > Enable at only Terminal > Change Slash(/) Key
A: emacs keybindings get wonky in terminals/consoles. it's a royal pain, but it is usually fixable. as @Zach already mentioned, the keys are sent differently when working in terminals. the trick is figuring what is actually sent to emacs, and then binding that to the command you wish to execute. this is a pretty good (although old) tutorial which walks you through trying to resolve these types of issues (3.0 is where it starts to get into what you need to do).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: How can I add an image thumbnail to my listview automatically? My goal is to add a thumbnail image in each of the listview entries. When the program opens, it downloads the images to the sd card. How can I make it so that the first entry on the listview has the thumbnail of image1 and the second entry automatically gets thumbnail image2, etc etc. I need this to be programmatically done since I have a menu of 1200+ options all with corresonding images. I have modified the R.layout.itemlayout file so that it has an imageview, I'm just not sure how to programmatically change the source of the imageview based on its position within the listview. Thanks in advance!
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Chapter0Menu extends ListActivity {
private static final String TAG = null;
public static String url;
public static String[] fileArray;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
String[] chapter0Array = getResources().getStringArray(R.array.chapter0);
setListAdapter(new ArrayAdapter<String>(Chapter0Menu.this, R.layout.itemlayout, chapter0Array));
}
A: You should have to use the customListAdapter to done this List view for display the multiple Images and what ever you want.
See this example. in this example there are multiple textview. Here instead of the text view you can take the Image view to show the Image you want.
Hope it will help you.
Thanks.
A: I just shared my personal class to dowload images in a download queue to you sd-card. Please try to use it and tell me if it's what you're looking for:
http://code.google.com/p/imagemanager/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trailing slash in URL is considered a different page with different Like count? I've noticed that I get different Like numbers when I check a URL with or without a trailing slash. It's logging them as separate URLS.
for example WITH a slash:
https://api.facebook.com/method/fql.query?query=select%20total_count%20from%20link_stat%20where%20url=%22jonahgoldstein.com/ahoy/%22
returns:
<fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true">
<link_stat>
<total_count>53</total_count>
</link_stat>
</fql_query_response>
and WITHOUT the slash:
https://api.facebook.com/method/fql.query?query=select%20total_count%20from%20link_stat%20where%20url=%22jonahgoldstein.com/ahoy%22
returns
<fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true">
<link_stat>
<total_count>68</total_count>
</link_stat>
</fql_query_response>
It would be wonderful if these pages weren't thought of as separate since my numbers will appear to people as half of what they should be. I've noticed that Twitter's API doesn't have a similar issue.
A: You can log this as a feature request here. But url's with or without slashes are technically separate url's according to the http spec. There is no way to fix this for existing share counts, but I would recommend setting up URL re-write on your web server to do a 301 redirect either to a url with or without a slash so this is avoided in the future.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Autocomplete for addresses using Lucene .NET I have not been able to get this nailed down. I have tried several different analyzers and they all get me close, but not exactly what I want. Using SOLR is not an option at the moment.
An examples of what I would like:
Input: 200
Matches: 200 E Dragon Dr.
200 W Paragon Rd.
200 Lick Skillet Dr.
Input: 200 E
Matches: 200 E Dragon Dr.
200 E Toll Rd.
Input: 200 E D
Matches: 200 E Dragon Dr.
If I use the simple analyzer then it will not match on the number. The whitespace analyzer gets the desired effect with just the number, but once I add the E it does not return as I expect. What would be the best analyzer or am I using the wrong queries?
Thanks,
EDIT:
I have taken the below answer and did a ton of googling and I am getting close just using the query parser and the whitespaceanalyzer. I am just letting the query parser determine the best query and it seems to work.
A: try using a keyword analyzer and a query parser to search an address field in Lucene. I am using a MultiFieldQueryParser, but you could use a regular query parser too:
public StartsWithQuery Prefix(string prefix, string[] fields, Dictionary<string,string> filterFields = null )
{
if(!string.IsNullOrEmpty(prefix))
{
var parser = new MultiFieldQueryParser(Version.LUCENE_29, fields, new KeywordAnalyzer());
var boolQuery = new BooleanQuery();
boolQuery.Add(parser.Parse(prefix + "*"), BooleanClause.Occur.MUST);
if (filterFields != null)
{
foreach (var field in filterFields)
{
boolQuery.Add(new TermQuery(new Term(field.Key, field.Value)), BooleanClause.Occur.MUST);
}
}
}
return this;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What method gets called before a WebView is closed by owner window? I'm working with a webview within a window of a Cocoa application. I would like to retrieve some values using stringByEvaluatingJavaScriptFromString on the webview and save them before the application shuts down. I tried using the applicationWillTerminate but by the time I reach this method, it is too late. I was wondering if there's something built into webview that I've missed or if anyone has an elegant solution to share.
A: If you want to save this information, why are you waiting until the app is about to terminate?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MVVM UserControl binding not getting pushed back to parent control I'm working on making a WPF app and I have a UserControl for data editing with a couple more UserControls inside it (super-simplified version):
<UserControl x:Name="ParentControlView">
<DockPanel>
<!-- other various controls, textblocks, etc. -->
<Controls:DatePickerView DataContext="{Binding Path=EndDate, Mode=TwoWay}" />
<!-- other various controls, textblocks, etc. -->
</DockPanel>
</UserControl>
In the parent control's ViewModel, it has a child DatePickerViewModel called EndDate which is bound to the DatePickerView control:
public class ParentControlViewModel : ViewModelBase
{
private DatePickerViewModel _endDate;
public DatePickerViewModel EndDate
{
get { return _endDate; }
set
{
_endDate = value;
RaisePropertyChanged(() => EndDate);
RaisePropertyChanged(() => SomeProperty);
}
}
}
The DatePickerView control is a few comboboxes that are bound to properties in a DatePickerViewModel, nothing special.
When I run my app, the DatePickerView is initialized properly and is set to the current value, like it should be. So the get method is working fine. But when I change the controls on the DatePickerView and its ViewModel gets updated, the value bound to the parent view doesn't get set in the parent view model (i.e. the set method never runs).
Obviously I am missing some sort of databinding hookups but for the life of me I cannot figure out what that is and I have searched all over and found nothing.
Update
Minimal working sample. Includes most of the proprietary date class I'm using, and probably some poor MVVM implementations. I'm still new at MVVM. I ripped a lot of the unnecessary code out so the date picker doesn't work quite right, but it does what it needs to do for the purposes of this question.
You will need to get and reference MvvmFoundation.Wpf.dll (at codeplex).
A: The only things that would make sense (based on just the code shown) is (1) the ViewModelBase doesn't implement INotifyPropertyChanged or (2) your DatePickerView control is doing something wrong with Dependency Properies.
I would suggest posting a full repro, including DataPickerView and ViewModelBase.
Edit
Ok, took a look, and see the problem. The reason why your setter never gets called is that your EndDate (DatePickerViewModel) never changes. That sounds somewhat self-evident, but that's the bottom line--there is no code that replaces the EndDate property completely, which is what would cause the setter code to run.
Your drop down lists change the properties of EndDate/DatePickerViewModel, but keep in mind that changing its properties (Date, SelectedYear, etc.) does not set the instance of DatePickerViewModel, which means the setter code will not run.
Since this is a stripped-down version, I am kind of guessing at what you ultimately want to achieve, but I think what you want is to create a DependencyProperty on the DatePickerViewModel (probably of type DateTime) that can be bound to and can notifies when the date inside the control changes.
As a fast workaround, add the code below to make the the setter code fire. Note this is not a recommended solution--it will cause your parent and child to have references to each other, which is (at least) odd:
//in ParentControlViewModel, change your EndDate to:
public DatePickerViewModel EndDate
{
get { return _endDate; }
set
{
_endDate = value;
if (_endDate.ParentControlViewModel == null)
{
_endDate.ParentControlViewModel = this;
}
RaisePropertyChanged(() => EndDate);
}
}
//Add to DatePickerViewModel
public ParentControlViewModel ParentControlViewModel { get; set; }
//Change Date property in DatePickerViewModel to:
public GDate Date
{
get { return _date; }
set
{
_date = value;
RaisePropertyChanged(() => Date);
if (ParentControlViewModel != null)
{
ParentControlViewModel.EndDate = this;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Way to make Windows Phone 7 Panorama Items Text gather up? How would I allow panorama items text to gather up like in the picture below? (By the way the image is not mine).
Notice how the Panorama Item titles are like "Contacts Chats" not spaced out like regular Microsoft panorama has it? How would I do that?
Thanks.
A: I'm pretty sure that is a Pivot Control, which looks similar to a Panorama Control.
There's a good video at Channel 9 on the two controls: Windows Phone Design Days - Pivot and Pano
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 403 Forbidden Error for Python-Suds contacting Sharepoint I'm using Python's SUDs lib to access Sharepoint web services.
I followed the standard doc from Suds's website.
For the past 2 days, no matter which service I access, the remote service always returns 403 Forbidden.
I'm using Suds 0.4 so it has built-in support for accessing Python NTLM.
Let me know if anyone has a clue about this.
from suds import transport
from suds import client
from suds.transport.https import WindowsHttpAuthenticated
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
ntlm = WindowsHttpAuthenticated(username='USER_ID', password='PASS')
c_lists = client.Client(url='https://SHAREPOINT_URL/_vti_bin/Lists.asmx?WSDL', transport=ntlm)
#c_lists = client.Client(url='https://SHAREPOINT_URL/_vti_bin/spsearch.asmx?WSDL')
#print c_lists
listsCollection = c_lists.service.GetListCollection()
A: Are you specifying the username as DOMAIN\USER_ID as indicated in examples for the python-ntlm library? (Also see this answer).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Create a recursion function with Java that prints all possible sequences of items contained within the list. I am supposed to be creating a recursive function within Java that prints out all possible colors from a list of colors. E.G.{r, b, g ; r, g, b ; g, r, b ; g, b, r} etc...
I believe I had it figured out and my code is below. Unfortunatly I continue to recieve a null pointer exception within the base case of the recursion function and it never runs. I've included a test within my application test class to show that the list of colors is in fact created. I am unsure as to what is causing my error, or where I have erred in my code.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SequentialPrint {
private List colors;
private List prefix;
public SequentialPrint(List colors) {
this.colors = colors;
}
public void printAllSequences(List colors) {
int prefixCount = 0;
int colorCount = 0;
List prefix = new ArrayList();
if (colors.isEmpty() || prefixCount == colors.size()) { //Base Case
System.out.print("All Sequences Printed");
}
else {
Object color = colors.remove(0);
prefix.add(color); //add first color from colors list.
prefixCount++; //increases prefix counter
while (prefixCount <= colors.size() + 1) { //prints first rotation of colors
System.out.println(prefix);
System.out.print(colors);
while (colorCount < colors.size() - 1) { //rotates list and prints colors, until entire list has been rotated once.
Collections.rotate(colors, 1);
System.out.println(prefix);
System.out.print(colors);
}
}
}
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Cash
*
*/
public class SequentialPrintDemonstration {
private SequentialPrint colorSequence;
private List colorsList;
private List prefixList;
/**
* @param args
*/
public SequentialPrintDemonstration() {
List colorsList = new ArrayList();
colorsList.add("blue");
colorsList.add("green");
colorsList.add("red");
colorsList.add("yellow");
colorSequence = new SequentialPrint(colorsList);
System.out.println(colorsList);
}
public void execute() {
this.colorSequence.printAllSequences(colorsList);
}
}
A: Your class has a private data member named prefix, which you don't initialize in the constructor:
public class SequentialPrint {
private List colors;
private List prefix;
public SequentialPrint(List colors){
this.colors = colors; // what if the array you pass in is null?
// why not initialize prefix here? it's null if you don't.
}
Then you have a method that declares a local variable List named prefix:
public void printAllSequences(List colors){
int prefixCount = 0;
int colorCount = 0;
List prefix = new ArrayList(); // this one shadows the private data member
Do you mean to use the private data member here?
Why do you pass in colors? How is that related to the private data member?
I don't understand this code after a quick glance. Do you?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MongoDb - How can I update multiple elements of a nested object using $set? Lets say I have the following document:
{name: 'myDoc', nestedDoc: {a: 1, b: 2, c: 3}}
And I would like to merge with the nestedDoc a new object:
{b: 20, c:30, d:40}
So the resulting object would be:
{name: 'myDoc', nestedDoc: {a: 1, b: 20, c: 30, d: 40}}
How can I go about doing this in a single query? I feel like I need multiple $set calls however object property names must be unique. In other words, I wish I could do the following:
db.myCollection.update({name: 'myDoc', nestedDoc: {$set: {b: 20}, $set: {c: 30}, $set: {d: 40}});
Some extra details are that the MongoDB version is 1.8.2 and I am using the NodeJS node-native driver.
A: You can update by using the following:
db.myCollection.update({
name: 'mydoc'
}, {
$set: {
'nestedDoc.b': 20,
'nestedDoc.c': 30,
'nestedDoc.d': 40
}
})
Here is more information about update command:
*
*Update Documents
A: update: this answer is not a correct update!
this works too in my app, and easy to read
db.myCollection.update({
name: 'mydoc'
},
{
$set: {
nestedDoc:{
b: 20,
c: 30,
d: 40,
}
}
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How would you find the min depth of a tree? I know how to find the max depth of a tree using a stack and inorder traversal, but I cannot figure out how to find the min depth of a tree (not necessarily a BST) using a stack or queue instead of recursive calls.
A: One thing to note here is that when you perform recursion you are using your process execution stack. This generally has some limit set by OS. So with each recursion the process state is pushed onto this stack. So at some point stackoverflow occurs.
If you end up doing a iterative version as apposed to recursive, note that the difference here is that this stack implementation is maintained by you. There is lot more work involved but stackoverflow is averted...
We could do something like the following (recursive version)-
MIN-VALUE
int min = INT_MAX;
void getMin(struct node* node)
{
if (node == NULL)
return;
if(node->data < min)
min = node->data;
getMin(node->left);
getMin(node->right);
return min;
}
Alternatively you could use min-heap which gives you minimum value in constant time.
UPDATE: Since you changed your question to min-depth
MIN-DEPTH
#define min(a, b) (a) < (b) ? (a) : (b)
typedef struct Node
{
int data;
struct Node *left, *right;
}Node;
typedef Node * Tree;
int mindepth(Tree t)
{
if(t == NULL || t->left == NULL || t->right == NULL)
return 0;
return min( 1 + mindepth(t->left), 1 + mindepth(t->right) );
}
PS: Code is typed freehand, there might be syntactical errors but I believe logic is fine...
A: I know this was asked long time ago but for those who stumbled upon here and would rather not use recursion, here's my pseudo (My apology for not providing C++ code because I'm not verse in C++). This leverage BFS traversal.
return 0 if root is empty
queue a tuple (that stores depth as 1 and a root node) onto a queue
while queue is not empty
depth, node = dequeue queue
// Just return the depth of first leaf it encounters
if node is a leaf then : return depth
if node has right child: queue (depth+1, node.right)
if node has left child : queue (depth+1, node.left)
Time complexity of this one is linear.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Post photos to wall issue I can login to Facebook within my application and can also retrieve the information of the Facebook account of my application users.
However, when I post a photo to my users' Facebook wall, it always return NULL. Why?
A: You need to prompt the user for publish_stream extended permission. Facebook has a post that walks you through this step by step.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Diagnosing an autorelease error (EXC_BAD_ACCESS) I've been playing around with core data and started writing some methods to query different date ranges of data. My core data model is very simple (Entity named Smoke with one field - timestamp (of type date).
When I execute my code, the proper count gets returned, but I get an autorelease error - I used NSZombies to track it to the below method:
- (NSUInteger)retrieveSmokesForUnit:(NSCalendarUnit)unit
{
NSDate *beginDate = [[NSDate alloc] init];
NSDate *endDate = [[NSDate alloc] init];
[self rangeForUnit:unit containingDate:[NSDate date] startsAt:&beginDate andEndsAt:&endDate];
NSInteger count = [self numberOfSmokes:beginDate toDate:endDate];
[beginDate release];
[endDate release];
return count;
}
So I get the concept - I am releasing the NSDate objects beginDate and endDate too many times - but why does that happen? I thought the rule was when you instantiate with alloc, you use release? I don't release them explicitly anywhere else in the code, so there must be something going on behind the scenes. If someone could point me in the right direction, that would be great!
Here are the other methods involved, since the issue must be somewhere in these. I assume it has to do with how I'm passing pointers to the dates around?
The initial call, called in the view controller
- (IBAction)cigButtonPressed
{
NSUInteger smokes = [[DataManager sharedDataManager] retrieveSmokesForUnit:NSWeekCalendarUnit];
NSLog(@"Count test = %i", smokes);
}
This calles the method posted a the beginning of the question, which in turn calls:
- (NSUInteger)numberOfSmokes:(NSDate *)beginDate toDate:(NSDate *)endDate {
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Smoke" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//Create predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(timeStamp >= %@) AND (timeStamp < %@)", beginDate, endDate];
//Setup request
[request setEntity:entity];
[request setPredicate:predicate];
NSError *error;
NSUInteger smokes = [self.managedObjectContext countForFetchRequest:request error:&error];
NSLog(@"Number of smokes retrieved: %d", smokes);
[request release];
return smokes;
}
Thanks!
Edit - left out a related method:
- (void)rangeForUnit:(NSCalendarUnit)unit containingDate:(NSDate *)currentDate startsAt:(NSDate **)startDate andEndsAt:(NSDate **)endDate {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar rangeOfUnit:unit startDate:&*startDate interval:0 forDate:currentDate];
*endDate = [calendar dateByAddingComponents:[self offsetComponentOfUnit:unit] toDate:*startDate options:0];
[calendar release];
}
A: In:
- (void)rangeForUnit:(NSCalendarUnit)unit containingDate:(NSDate *)currentDate startsAt:(NSDate **)startDate andEndsAt:(NSDate **)endDate {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar rangeOfUnit:unit startDate:&*startDate interval:0 forDate:currentDate];
*endDate = [calendar dateByAddingComponents:[self offsetComponentOfUnit:unit] toDate:*startDate options:0];
[calendar release];
}
startDate and endDate are output parameters. They are not owned by the caller, hence they should not be released.
Then, in:
- (NSUInteger)retrieveSmokesForUnit:(NSCalendarUnit)unit
{
NSDate *beginDate = [[NSDate alloc] init];
NSDate *endDate = [[NSDate alloc] init];
[self rangeForUnit:unit containingDate:[NSDate date] startsAt:&beginDate andEndsAt:&endDate];
NSInteger count = [self numberOfSmokes:beginDate toDate:endDate];
[beginDate release];
[endDate release];
return count;
}
the following happens:
*
*You create a new NSDate object via +alloc, hence you own it. beginDate points to this new object;
*You create a new NSDate object via +alloc, hence you own it. endDate points to this new object;
*You send -rangeUnit:containingDate:startsAt:andEndsAt:, passing the address of beginDate and endDate as arguments. Upon return, these two variables point to whatever was placed in them by the method. You do not own the corresponding objects (see above), and you’ve leaked the two NSDate objects you created in steps 1 and 2.
*You send -release to both beginDate and endDate. You don’t own them, hence you shouldn’t release them.
In summary:
*
*You shouldn’t be creating new objects for beginDate and endDate since they’re being returned by -rangeUnit… This causes memory leaks;
*You shouldn’t be releasing beginDate and endDate because you do not own the objects returned by -rangeUnit… This causes overreleases.
The following code should fix your leaks and overreleases:
- (NSUInteger)retrieveSmokesForUnit:(NSCalendarUnit)unit
{
NSDate *beginDate;
NSDate *endDate;
[self rangeForUnit:unit containingDate:[NSDate date] startsAt:&beginDate andEndsAt:&endDate];
NSInteger count = [self numberOfSmokes:beginDate toDate:endDate];
return count;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: efficient way of printing lists to a table in a .txt file using python I want to create a text file which contains a table, created from lists. But, I don't want to have to do something like this:
import string
print >> textfile, string.rjust(listname[0],3), string.rjust(listname[1],3),
The following code demonstrates the idea of what I would like to do, but doesn't work:
import string
listname = ['test1','test2','test3']
i=0
for i in range(0,3):
print >> textfile, string.rjust(listname[i],5)
I would like the output to look exactly like this:
test1 test2 test3
That's what I'm trying to do and how it makes sense in my head, but obviously that won't (and isn't) working.
I've used the join() function to print the lists nicely, but I can't get the spacing right for the table.
Any ideas?
A: If I'm understanding the problem correctly, you could just do this...
>>> def print_table():
... headers = ['One', 'Two', 'Three']
... table = [['test1', 2, 3.0],
... ['test4', 5, 6.0],
... ['test7', 8, 9.0],
... ]
... print ''.join(column.rjust(10) for column in headers)
... for row in table:
... print ''.join(str(column).rjust(10) for column in row)
...
>>>
>>> print_table()
One Two Three
test1 2 3.0
test4 5 6.0
test7 8 9.0
>>>
No need for the string module or integers to index into the table.
I've printed to standard out for clarity, but you can write to a file just as easily.
A: Think most effective way is to generate string using .join method and then do one write operation to the file.
A: What do you mean it isn't working?
First of all, rjust is going to include the characters in the string. It looks like you want a rjust of at around 8 to get the spacing you are looking for with strings like "test1".
Second, because your print has no comma at the end of it, it will print each one on a new line. You probably want something like:
print >> textfile, string.rjust(listname[i],8),
Then, after you are out of the loop you need to print a newline:
print >> textfile
Now, we have some whitespace at the beginning of the line because we rjust the first item in the list. You actually probably want this behavior, because then the columns will line up, the other option is to use ljust.
Some minor style suggestions:
*
*i=0 does nothing here; it will get overwritten
*for item in listname is likely better than the range thing you are doing.
*instead of string.rjust, you should just call rjust on the string itself, like: listname[i].rjust(8)
If you want to be slick with join and a list comprehension, you could do:
print >> textfile, ' '.join(item.rjust(8) for item in listname)
This does an rjust on all the items, then joins them together with a space (you could use empty string here, as well).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I'm looking for a graphics library for Java My task is to make a 2D 8-bit game with a couple of friends. All of us are fairly novice programmers, and only I have any experience with graphics programming (just a little though), so this will mostly be a learning experience for us. So, I have a few questions...
*
*What is a good graphics library for our needs?
*Does Java have any native graphics capabilities or do I have to use
additional libraries? If yes, how are they?
*Is Java a good choice for writing a game in? (we don't have to use
Java)
*Will any graphics library allow you to make animations or any sort or do you actually have to code that kind of thing?
Thanks for your time.
A: Java2D: http://java.sun.com/products/java-media/2D/index.jsp
A: If you are not making serious game, try processing
http://processing.org/
althogh it's designed to make visual and interactive product, I think it is worth considering.
A: The ACM (http://jtf.acm.org/index.html) library is good for basics.
Java has some native graphics, but libraries are far better.
Java is good for games (far better than python even with PYGame). If your game is complex, then you definitely want to use C(++).
There are libraries that allow animations, although you could just program it yourself.
As previously mentioned, Processing is good for non-serious applications. But if you want a full-fledged IDE then you definitely want Eclipse.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Removing events from elements .each vs. .unbind in jQuery... what's the difference? In a script I'm writing, I've noticed there are two currently working ways to 'unbind' an event from an element.
$("elementName").each( function() { $(this).unbind('click'); });
And This way...
$("elementName").unbind('click'); });
I know .each loops through the elements but the second scripts appears to work just as well. So what am I missing, why use .each?
A: There's no reason to use .each in this case. Most jQuery functions are intended to work on groups of matched elements so $("elementName").unbind('click') is best way to apply unbind to multiple elements at once; however, if you like typing you could use the .each iterator and do them one a time.
Generally you'll use .each when you want to do something different to some or all of the matched elements. For example:
$('a').each(function(i) { $(this).addClass('pancakes' + i) });
would add a different class to each <a> and would be an appropriate use of .each. Or an unbind example:
$('a').each(function() {
var $this = $(this);
if($this.data('where-is') == 'pancakes-house')
$this.unbind('click');
// Yes, there are other ways to do this, this is just an illustrative example.
});
A: Essentially the same thing.
You would use $.each, though, when you also wanted to do something else to each of the elements that you are matching.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to check if at least one radio button is checked in this function? I'm making a quiz with PHP, but I am using JavaScript to go between the questions first and then I submit the form and let PHP do the rest.
I made two JavaScript functions called ChangeQuestion() and BackQuestion().
function ChangeQuestion(prev, next) {
$('#' + prev).fadeOut(600, function() {
$('#' + next).fadeIn(600);
});
}
function BackQuestion(last, prev) {
$('#' + prev).fadeOut(600, function() {
$('#' + last).fadeIn(600);
});
}
They're pretty basic. But what I would like to do is check if their is at least one radio button checked in a question before continuing with the function. You'll be able to see in my markup/HTML how I'm using the above functions.
First of all, here's a jsFiddle: http://jsfiddle.net/3XdUA/
Here's my markup:
<form id="quiz1" name="quiz1" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<div id="starter">
Hello! Welcome to the HTML Quiz powered by PHP. Click on Start to begin.
<br /><br />
<button type="button" onclick="ChangeQuestion('starter','question1');$('#qIndicator').fadeIn(800);">Start »</button>
</div>
<div id="question1" style="display:none;">
1. What does HTML stand for?
<br />
<br />
<input type="radio" name="q1" id="q1-a1" />
<label for="q1-a1">Hyperlinks and Text Markup Language</label>
<br />
<input type="radio" name="q1" id="q1-a2" />
<label for="q1-a2">Home Text Markup Language</label>
<br />
<input type="radio" name="q1" id="q1-a3" />
<label for="q1-a3">Hyper Text Markup Language</label>
<br />
<input type="radio" name="q1" id="q1-a4" />
<label for="q1-a4">Hyper Text Marking Language</label>
<br /><br />
<button type="button" onclick="ChangeQuestion('question1','question2');$('#qIndicator').html('Question 2 of 10');">Next »</button>
</div>
<div id="question2" style="display:none;">
2. What is the proper way to add a blue background to the <code><body></code> and remove the margin & padding?
<br />
<br />
<input type="radio" name="q2" id="q2-a1" />
<label for="q2-a1"><body backgroundColor="blue" padding="0" margin="0"></label>
<br />
<input type="radio" name="q2" id="q2-a2" />
<label for="q2-a2"><body style="background-color: blue; margin: 0; padding: 0;"></label>
<br />
<input type="radio" name="q2" id="q2-a3" />
<label for="q2-a3"><body style="backgroundColor: blue; margin: 0px; padding: 0px;"></label>
<br />
<input type="radio" name="q2" id="q2-a4" />
<label for="q2-a4"><body background="blue" padding="0" margins="0"></label>
<br /><br />
<button type="button" onclick="BackQuestion('question1','question2');$('#qIndicator').html('Question 1 of 10');">« Back</button>
<button type="button" onclick="ChangeQuestion('question2','question3');$('#qIndicator').html('Question 3 of 10');">Next »</button>
</div>
<div id="question3" style="display:none;">
3. Which of the following font styling tags isn't valid?
<br />
<br />
<input type="radio" name="q3" id="q3-a1" />
<label for="q3-a1"><small></label>
<br />
<input type="radio" name="q3" id="q3-a2" />
<label for="q3-a2"><strong></label>
<br />
<input type="radio" name="q3" id="q3-a3" />
<label for="q3-a3"><em></label>
<br />
<input type="radio" name="q3" id="q3-a4" />
<label for="q3-a4"><large></label>
<br /><br />
<button type="button" onclick="BackQuestion('question2','question3');$('#qIndicator').html('Question 2 of 10');">« Back</button>
<button type="button" onclick="ChangeQuestion('question3','question4');$('#qIndicator').html('Question 4 of 10');">Next »</button>
</div>
<div id="question4" style="display:none;">
4. Suppose you have this HTML on your page:
<br /><br />
<code>
<a name="target4">Old listing</a>
</code>
<br /><br />
How would you link to the above target?
<br />
<br />
<input type="radio" name="q4" id="q4-a1" />
<label for="q1-a1"><a url="#target4">Check Old Listing as well</a> </label>
<br />
<input type="radio" name="q4" id="q4-a2" />
<label for="q1-a2"><a href="#target4">Check Old Listing as well</a></label>
<br />
<input type="radio" name="q4" id="q4-a3" />
<label for="q1-a3"><link url="target4">Check Old Listing as well</link> </label>
<br />
<input type="radio" name="q4" id="q4-a4" />
<label for="q1-a4"><a href="Listing.target4">Check Old Listing as well</a></label>
<br /><br />
<button type="button" onclick="BackQuestion('question3','question4');$('#qIndicator').html('Question 3 of 10');">« Back</button>
<button type="button" onclick="ChangeQuestion('question4','question5');$('#qIndicator').html('Question 5 of 10');">Next »</button>
</div>
<div id="question5" style="display:none;">
5. What does HTML stand for?
<br />
<br />
<input type="radio" name="q2" id="q2-a1" />
<label for="q1-a1">Hyper Tool Markup Language</label>
<br />
<input type="radio" name="q2" id="q2-a2" />
<label for="q1-a2">Home Text Markup Language</label>
<br />
<input type="radio" name="q2" id="q2-a3" />
<label for="q1-a3">Hyper Text Markup Language</label>
<br />
<input type="radio" name="q2" id="q2-a4" />
<label for="q1-a4">Hyper Text Marking Language</label>
<br /><br />
<button type="button" onclick="BackQuestion('question4','question5');$('#qIndicator').html('Question 4 of 10');">« Back</button>
<button type="button" onclick="ChangeQuestion('question5','question6');$('#qIndicator').html('Question 6 of 10');">Next »</button>
</div>
<div id="question6" style="display:none;">
6. What does HTML stand for?
<br />
<br />
<input type="radio" name="q2" id="q2-a1" />
<label for="q1-a1">Hyper Tool Markup Language</label>
<br />
<input type="radio" name="q2" id="q2-a2" />
<label for="q1-a2">Home Text Markup Language</label>
<br />
<input type="radio" name="q2" id="q2-a3" />
<label for="q1-a3">Hyper Text Markup Language</label>
<br />
<input type="radio" name="q2" id="q2-a4" />
<label for="q1-a4">Hyper Text Marking Language</label>
<br /><br />
<button type="button" onclick="BackQuestion('question5','question6');$('#qIndicator').html('Question 5 of 10');">« Back</button>
<button type="button" onclick="ChangeQuestion('question6','question7');$('#qIndicator').html('Question 7 of 10');">Next »</button>
</div>
</form>
Yes, it is long. Sorry about that. But, I provided a jsFiddle which would be much easier to understand. (because of the preview, etc.)
I do know how to check if a radio is selected, but I do not know how to make sure that one is selected with this function.
A: use :radio:checked
function ChangeQuestion(prev, next) {
var current = $('#' + prev);
var selection = current.find(":radio:checked").attr("id");
if (selection) {
alert(selection);
}
current.fadeOut(600, function() {
$('#' + next).fadeIn(600);
});
}
an alternative to my update would be
function ChangeQuestion(prev, next) {
var current = $('#' + prev);
if (prev != "starter") {
var selection = current.find(":radio:checked").attr("id");
if (selection === undefined) {
alert("no selection");
} else {
alert(selection);
current.fadeOut(600, function() {
$('#' + next).fadeIn(600);
});
}
} else {
current.fadeOut(600, function() {
$('#' + next).fadeIn(600);
});
}
}
I just didn't like repeating
current.fadeOut(600, function() {
$('#' + next).fadeIn(600);
});
see here
A: Use the :checked pseudo selector.
function ChangeQuestion(prev, next) {
var prevQ = $('#'+prev);
var numChecked = prevQ.find('input[type=radio]:checked').length;
if( prev !=='starter' && numChecked == 0 ) {
// no radio checked in this question
return;
}
prevQ.fadeOut(600, function() {
$('#' + next).fadeIn(600);
});
}
A: You can also use $("[name=q1]").is(":checked") just to check if something is selected. Of course, substitute q1 with whichever question you are on. In your case it looks like you'll be using q1, q2, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TypeError: 'str' does not support the buffer interface - python I'm currently doing an online Python puzzle series, and I've gotten to a problem where you need to unload a pickled file. I read the documentation on it, but I kept getting
TypeError: 'str' does not support the buffer interface
...so I search on Google and arrive at a question on SO with a similar problem. The answer points to http://wiki.python.org/moin/UsingPickle .
I tried the code in the example and I'm getting the same problem? I'm using Python 3.2.2. WTF??
Complete Traceback :
Traceback (most recent call last):
File "C:\foo.py", line 11, in <module>
test1()
File "C:\foo.py", line 9, in test1
favorite_color = pickle.load( open( "save.p" ) )
TypeError: 'str' does not support the buffer interface
From the example here: http://wiki.python.org/moin/UsingPickle
I have already successfully created the save.p file with the first code example in the tutorial.
A: Open the pickle file in binary mode: favorite_color = pickle.load(open("save.p", "rb")).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is moving between iOS subviews within a single view possible without returning to the view? Is moving between iOS subviews within a single view possible without returning to the view? If so, how? Code example welcome.
How I'm doing it now but this requires returning to the "home" view:
In the myFile.m
// Define the other views
DF_Results *df_Results;
CR_FiringRange *cr_FiringRange;
CR_AssetLoader *cr_AssetLoader;
DB_GeneralData *db_GeneralData;
DB_ArmorData *db_ArmorData;
DB_WeaponsData *db_WeaponsData;
@synthesize ScreenButton01;
@synthesize ScreenButton02;
@synthesize ScreenButton03;
@synthesize ScreenButton04;
@synthesize ScreenButton05;
@synthesize ScreenButton06;
@synthesize ScreenButton07;
.
.
.
-(IBAction) ScreenButton02Clicked:(id) sender {
df_Results = [[DF_Results alloc]
initWithNibName:@"DF_Results"
bundle:nil];
[UIView beginAnimations:@"flipping view" context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
[self.view addSubview:df_Results.view];
[UIView commitAnimations];
}
In DF_Results to return we tap another button but I would like to be able to jump straight to another subview:
-(IBAction) ResultsScreenButton01Clicked:(id) sender {
[UIView beginAnimations:@"flipping view" context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view.superview cache:YES];
[self.view removeFromSuperview];
[UIView commitAnimations];
}
A: In iOS 4.0 UIView has a number of block based animation transitions tasks which according to docs are the recommended approach. E.g. this one could be useful:
(void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion
See UIView docs for more details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating a 2 page PDF with a different background image on the second page I am trying to use itextsharp to take dynamic information and generate a PDF with it.. The PDF's use a background Image on each page which is different and the text content is positioned where it needs to be using the contentByte helper. Thats the plan anyways. I hit a hang up when I tried to add another page and then drop the image and text onto that page... My first page ends up with the image that should be on my second page and the first page image fails to display at all on either page... My code so far is as follows:
Function ID_and_Parking(ByVal id As Integer) As ActionResult
Dim _reg_info As reg_info = db.reg_info.Single(Function(r) r.id = id)
Dim _conf_info As conf_info = db.conf_info.Single(Function(f) f.id = 0)
Dim _name As String = String.Empty
If Not String.IsNullOrWhiteSpace(_reg_info.name_tag_pref) Then
_name = _reg_info.name_tag_pref
Else
_name = _reg_info.first_name + " " + _reg_info.last_name
End If
Dim _LastName As String = _reg_info.last_name
Dim _Employer As String = _reg_info.business_name
Dim _Class_1 As String = _reg_info.tues_class
Dim _Class_2 As String = _reg_info.wed_class
Dim _Class_3 As String = _reg_info.thur_class
Dim _Class_4 As String = _reg_info.fri_class
Dim _BeginDate As String = _conf_info.conf_start_date
Dim _endDate As String = _conf_info.conf_end_date
Dim _dates As String = _BeginDate + "-" + _endDate
If IsDBNull(_reg_info.tues_class) Then
_Class_1 = ""
End If
If IsDBNull(_reg_info.wed_class) Then
_Class_2 = ""
End If
If IsDBNull(_reg_info.thur_class) Then
_Class_3 = ""
End If
If IsDBNull(_reg_info.fri_class) Then
_Class_4 = ""
End If
Dim pdfpath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\PDF_Files\"
Dim imagepath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\PDF_Files\"
Dim _PdfName As String = _LastName + ".pdf"
Dim doc As New Document
doc.SetPageSize(iTextSharp.text.PageSize.LETTER)
doc.SetMargins(0, 0, 0, 0)
Dim _PnameFont As iTextSharp.text.Font = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 18, iTextSharp.text.Font.NORMAL)
Dim BF_Times As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
Dim _Parking_Name As New Font(BF_Times, 18, Font.NORMAL, BaseColor.BLACK)
Dim _Parking_Date As New Font(BF_Times, 24, Font.BOLD, BaseColor.BLACK)
Try
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(pdfpath + _PdfName, FileMode.Create))
doc.Open()
Dim jpg As Image = Image.GetInstance(imagepath + "/Parking_Pass.jpg")
jpg.Alignment = iTextSharp.text.Image.UNDERLYING
jpg.ScaleToFit(612, 792)
doc.add(jpg)
Dim cb As PdfContentByte = writer.DirectContent
'Render Parking Permit
cb.BeginText()
cb.SetFontAndSize(BF_Times, 16)
cb.SetTextMatrix(145, 135.5)
cb.ShowText(_BeginDate)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 16)
cb.SetTextMatrix(429, 135.5)
cb.ShowText(_endDate)
cb.EndText()
Dim _idJpg As Image = Image.GetInstance(imagepath + "/Id_Tag.jpg")
Dim imageWidth As Decimal = _idJpg.Width
Dim imageHeight As Decimal = _idJpg.Height
doc.SetPageSize(iTextSharp.text.PageSize.LETTER)
_idJpg.Alignment = iTextSharp.text.Image.UNDERLYING
_idJpg.ScaleToFit(612, 792)
doc.NewPage()
doc.Add(_idJpg)
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(100, 50)
cb.ShowText(_name)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(200, 100)
cb.ShowText(_Employer)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(300, 150)
cb.ShowText(_Class_1)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(310, 50)
cb.ShowText(_Class_2)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(320, 50)
cb.ShowText(_Class_3)
cb.EndText()
cb.BeginText()
cb.SetFontAndSize(BF_Times, 18)
cb.SetTextMatrix(330, 50)
cb.ShowText(_Class_4)
cb.EndText()
doc.Close()
Catch dex As DocumentException
Response.Write(dex.Message)
Catch ioex As IOException
Response.Write(ioex.Message)
Catch ex As Exception
Response.Write(ex.Message)
End Try
Return RedirectToAction("showUserPDF", New With {.pdfName = _PdfName})
End Function
I have been all over every forum about this but all of the information I have found seems to be off from what I am looking for, OR maybe I am just going about this the wrong was all together... Any help would be greatly appreciated...
A: In your code you've got this:
Dim jpg As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath + "/Parking_Pass.jpg")
jpg.Alignment = iTextSharp.text.Image.UNDERLYING
jpg.ScaleToFit(612, 792)
But you are never actually adding jpg to the doc
A: I actually have figured out the issue I overlooked my placement of the newpage and the image placement... I had the 2nd page image before the newpage... Thanks for your help... If anyone else neededs to dynamically fill a image with data the above solution works...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Quick assist with finding Javascript variable (PollDaddy hash) I'm working on finding a variable for a PollDaddy poll. The API says that the hash is attributed to the variable PDV_h[PollID] (check "Voting" part of API). I've been looking all around this poll here but can't seem to find it. Can anyone help me figure out the hash and tell me how you were able to find it?
A: The hash doesn't seem to be used in the link you gave me here.
But on what I assume is your site, here, there's a variable PDV_h5547018, which gives you the hash you need to make the request.
This is what I got back, but this will be invalidated, of course:
PDV_n0='f5a9a0cf08b733a0e1738e271c9303d6';PD_vote0(0);
I would track down where it was made but there are so many script references. I assume you are using a script request from them, which is why they say it's in the JavaScript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Testing STM functions purely I've recently started using STM for some bits in a project of mine, but I'm having trouble figuring out how to test it.
I have no IO in these functions and was hoping I could write QuickCheck properties to test things, but "atomically" (STM a -> IO a) seems to be the only way to get anything out of the STM monad.
Is this possible, or should I just write my tests in HUnit instead?
A: You can test IO actions with quickcheck: http://hackage.haskell.org/packages/archive/QuickCheck/2.4.1.1/doc/html/Test-QuickCheck-Monadic.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Low level cycle counter in iOS devices Now that it's clear that the Cortex-A8 performance counters aren't available on the iPhone/iPad (they need to be explicitly enabled for usermode, which Apple hasn't done), is there some other way of getting a reasonable cycle count on iOS devices, for micro-profiling?
A: The most fine grain timing available to iOS user code via a public API appears to be using mach_absolute_time(), from mach/mach_time.h, whose output appears to scaled results from one of the ASIC's clock cycle counters. Call it one extra time just before you start timing to pre-fill the ICACHE with the mach_time library code. Note that some of Apple's ASICs may shift gears for the app's CPU core clock speed, depending.
A: I might be completely off, but is CFAbsoluteTimeGetCurrent too coarse for you?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Should I create service for GPS tracking APP? I am writing a location service App that log where the user has been every minute.
Should I create a service for the GPS process? OR just create the LocationManager at the Activity? Which one is better?
Moreover, I have tried to hide the application by pressing hardware home button and turn off GPS at Setting -> Location. I found that the App closed automatically within an hour.
Is it possible to keep the application always alive?
A: I highly recommend creating the gps at the very least as a thread in the activity, if you want to be slick set it up as a service and broadcast intents from inside an asynctask. Setting it up as a service makes it a bit modular if you want to use it for other applications or in other activities. Thats the way I implemented it.
Its also easier to control the lifetime of your gps readings if you run it from a service instead of your activity, so service doesnt get interrupted if you do switch activities etc.. example of asynctask portion below:
/** Begin async task section ----------------------------------------------------------------------------------------------------*/
private class PollTask extends AsyncTask<Void, Void, Void> { //AsyncTask that listens for locationupdates then broadcasts via "LOCATION_UPDATE"
// Classwide variables
private boolean trueVal = true;
Location locationVal;
//Setup locationListener
LocationListener locationListener = new LocationListener(){ //overridden abstract class LocationListener
@Override
public void onLocationChanged(Location location) {
handleLocationUpdate(location);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
/** Overriden methods */
@Override
protected Void doInBackground(Void... params) {
//This is where the magic happens, load your stuff into here
while(!isCancelled()){ // trueVal Thread will run until you tell it to stop by changing trueVal to 0 by calling method cancelVal(); Will also remove locationListeners from locationManager
Log.i("service","made it to do in background");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onCancelled(){
super.onCancelled();
stopSelf();
}
@Override
protected void onPreExecute(){ // Performed prior to execution, setup location manager
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if(gpsProvider==true){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
if(networkProvider==true){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
@Override
protected void onPostExecute(Void result) { //Performed after execution, stopSelf() kills the thread
stopSelf();
}
@Override
protected void onProgressUpdate(Void... v){ //called when publishProgress() is invoked within asynctask
//On main ui thread, perform desired updates, potentially broadcast the service use notificationmanager
/** NEED TO BROADCAST INTENT VIA sendBroadCast(intent); */
Intent intent = new Intent(LOCATION_UPDATE);
//Put extras here if desired
intent.putExtra(ACCURACY, locationVal.getAccuracy()); // float double double long int
intent.putExtra(LATITUDE, locationVal.getLatitude());
intent.putExtra(LONGITUDE, locationVal.getLongitude());
intent.putExtra(TIMESTAMP, locationVal.getTime());
intent.putExtra(ALTITUDE,locationVal.getAltitude());
intent.putExtra(NUM_SATELLITES,0);/////////////****TEMP
sendBroadcast(intent); //broadcasting update. need to create a broadcast receiver and subscribe to LOCATION_UPDATE
Log.i("service","made it through onprogress update");
}
/** Custom methods */
private void cancelVal(){ //Called from activity by stopService(intent) --(which calls in service)--> onDestroy() --(which calls in asynctask)--> cancelVal()
trueVal = false;
locationManager.removeUpdates(locationListener);
}
private void handleLocationUpdate(Location location){ // Called by locationListener override.
locationVal = location;
publishProgress();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add two variables in a function that every time the one is the working? With the following function I sort the posts of RSS ascending.
usort($posts, 'mysort');
function mysort($x, $y) {
return strtotime($y->pubDate) - strtotime($x->pubDate);
}
However some of those feeds have instead of a pubDate tag (for the date), they have a tag named published.
All feeds are saved ine one array. My question is how to satisfy both using my function or another function? Something like these:
return strtotime($y->pubDate OR $y->published) - strtotime($x->pubDate OR $x->published);
A: Your question is not really clear, but is this what you what?
return strtotime(($y->pubDate)?$y->pubDate:$y->published) -
strtotime(($x->pubDate)?$x->pubDate:$x->published);
Basically, I'm using a ternary IF operator that can be read like so: (if condition)?then do this:else do this;
Does it help?
Edit
Small edit based on your question about echoing the value:
The answer depends on which attribute take precedence over the other.. for instance, if pubDate it's more importante than published, then you'd write something like:
echo ($x->pubDate)?$x->pubDate:$x->published;
And if it was the other way around:
echo ($x->published)?$x->published:$x->pubDate;
(changing $x for whatever your object is called ofcourse..)
Does this help?
A: You can use Date object and get the diff.
`$a = new DateTime($startDate);`
`$b = new DateTime("now");`
`return $b->diff($a);`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c++ strtok in function changes original string value as parameter when I use strtok to tokenize a c++ string, it happens a confusing problem, see the simple code below:
void a(string s){
strtok((char*)s.c_str(), " ");
}
int main(){
string s;
s = "world hello";
a(s);
cout<<s<<endl;
return 0;
}
the program outputs "world".
Shouldn't it output "world hello"? Because I pass the string as a value parameter to function a, the strtok shouldn't modify the original s...
Can anyone explain this trick.
thank you.
A: The problem is (char*)s.c_str(), you are casting the constness away and modified the string contents in a way that you are not supposed to. While the original s should not be modified, I pressume you may have been hit by a smart optimization that expects you to play by the rules. For instance, a COW implementation of string would happen to show that behavior.
A: c_str() returns a const pointer, which is a promise to the compiler that the thing being pointed at won't be modified. And then you're calling strtok which modifies it.
When you lie to the compiler, you will be punished.
A: That's the way strtok() works. It use the first parameter as a buffer. By casting it to a char*, you allow it to modify the string. strtok() does not known about the original std::string. It also store the string pointer in a static variable, that's why you have to call it with a null pointer the next times to continue to parse the same string.
By the way, in c++, you should use std::istringstream instead. It does not use an internal static variable, which is not thread-safe. And you can extract the parameters directly into int, double, etc like we do with cin. std::ostringstring replace sprintf().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Translating PHP fragment code to .net could anybody translate the PHP part of this code into .net?
function showonlyone() {
$(‘div[name|="newboxes"]‘).each(function(index) {
if ($(this).attr(“id”) == <?=htmlentities($_GET['id']);?>) {
$(this).show(200);
}
else {
$(this).hide(600);
}
});
}
Thanks
A: Server.HtmlEncode(Request.QueryString['id']);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to notification to android remotely? Is there anyway in android to send a code or something to a device with an app installed and cause the device to show a notification or vibrate?
What would be the best way to do this?
like a PC you have the ability to send a specific code to the device with the app installed and cause it to do a notification..
What is the best way to do this or go about doing this?
Any ideas will be great!
A: Yea, in general they are called push notications. Check out Android's Cloud 2 Device Messaging system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C# regex to extract groups from input I want to extract anything between two colon's (inclusive of the colon's) in an arbitrary input using C#. Given
String input = "a:one:b:two:c:three:d";
I want
{string[3]}
[0]: ":one:"
[1]: ":two:"
[2]: ":three:"
Using
String[ ] inverse = Regex.Split( input, ":.*?:" );
I get the opposite of what I want...
{string[4]}
[0]: "a"
[1]: "b"
[2]: "c"
[3]: "d"
How can I inverse this or is there something more suitable than Regex.Split in this situation?
A: How about :[^:]+:
1. Match a colon
2. Followed by any non colon character one or more times.
3. Followed by a colon.
To get the set of matches use MatchCollection matches = Regex.Matches(blah, ":[^:]+:"); instead of Regex.Split
Regex's are concise and powerfull but I find myself writting just as many comments as I would code when using them.
A: How about you just use a regular split (on ':'), extract every second element, and then append the colons back on? I think you're overcomplicating this.
A: Try this regex:
^(\w*):|:\w:|:\w$
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: NullPointerException getAsObject method I'm using netbean 7.0.1, glassfish 3.1, primefaces 2.2.1.
This is view
<ui:define name="content">
<h:form enctype="multipart/form-data">
<p:wizard>
<p:tab title="Tab 01">
<p:panel header="This is tab 01">
<h:messages errorStyle="color:red"/>
<h:panelGrid>
<h:selectOneMenu value="#{sellerController.currentCity}">
<f:selectItems value="#{cityController.listCity}" var="obj" itemLabel="#{obj.name}" itemValue="#{obj}"/>
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab title="Tab 02">
<p:panel header="This is tab 02">
<h:panelGrid>
<p:commandButton value="Save" action="#{sellerController.addProperty()}"/>
</h:panelGrid>
</p:panel>
</p:tab>
</p:wizard>
</h:form>
</ui:define>
also try with
<h:selectOneMenu value="#{sellerController.currentCity}">
<f:selectItems value="#{cityController.itemsAvailableSelectOne}"/>
</h:selectOneMenu>
When i click next button on tab 01 and save button on tab 02, sellerController.currentCity return null value. Save button still call : "addProperty()". I got this error
INFO: java.lang.NullPointerException
java.lang.NullPointerException
at my.controller.CityController$CityControllerConverter.getAsObject(CityController.java:67)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:171)
at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectOneValue(MenuRenderer.java:202)
at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:319)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at org.primefaces.component.wizard.Wizard.processValidators(Wizard.java:216)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:508)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1589)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600)
at javax.faces.component.UIForm.visitTree(UIForm.java:344)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1170)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
i have two controller, this is CityController :
@Named(value = "cityController")
@SessionScoped
public class CityController implements Serializable {
@EJB
CityModel cityModel;
List<City> listCity;
/** Creates a new instance of CityController */
public CityController() {
}
public List<City> getListCity(){
if (listCity==null) {
listCity = new ArrayList<City>();
listCity = cityModel.findAll();
}
return listCity;
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(cityModel.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(cityModel.findAll(), true);
}
@FacesConverter(forClass = City.class)
public static class CityControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return "";
}
CityController controller = (CityController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "customerController");
return controller.cityModel.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof City) {
City o = (City) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CityController.class.getName());
}
}
}
}
This is SellerController
@Named(value = "sellerController")
@SessionScoped
public class SellerController implements Serializable {
@EJB
CityModel cityModel;
private City currentCity;
/** Creates a new instance of SellerController */
public SellerController() {
}
public City getCurrentCity() {
if (currentCity==null) {
currentCity = new City();
}
return currentCity;
}
public void setCurrentCity(City currentCity) {
this.currentCity = currentCity;
}
public void addProperty(){
System.out.println("Call from Save button ?? ");
}
}
This is JsfUtil class
public class JsfUtil {
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "---");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
}
Because of CityController. when i use
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "cityController")
@SessionScoped
It's work !
A: Considering this "cityController"-
@Named(value = "cityController")
@SessionScoped
public class CityController implements Serializable {
Is "customerController" right in the following -
CityController controller = (CityController) facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, "customerController");
Change it to "cityController" as follows -
FacesContext fc = FacesContext.getCurrentInstance();
ELResolver elr = fc.getApplication().getELResolver();
ELContext elc = fc.getELContext();
CityController cc = (CityController) elr.getValue(elc, null, "cityController");
A: I think your cityModel is NULL. Is your EJB injection configured right?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Ruby app throwing "attempt to pop an unknown release pool"? (OpenGL, OS X) In my small Ruby project using OpenGL via Gosu and Chingu I'm now seeing a number of these errors pop up during my tests:
2011-09-30 23:31:01.789 ruby[832:903] * attempt to pop an unknown autorelease pool (0x12c55a00)
UPDATE: I'm now also seeing some of these forms, definitely indicating a leak:
2011-10-01 03:50:00.281 ruby[3212:903] * __NSAutoreleaseNoPool(): Object 0x461aa0 of class NSCFNumber autoreleased with no pool in place - just leaking
2011-10-01 03:50:00.282 ruby[3212:903] * __NSAutoreleaseNoPool(): Object 0x461ae0 of class NSConcreteValue autoreleased with no pool in place - just leaking
2011-10-01 03:50:00.283 ruby[3212:903] * __NSAutoreleaseNoPool(): Object 0x10ce230 of class NSCFNumber autoreleased with no pool in place - just leaking
2011-10-01 03:50:00.285 ruby[3212:903] * __NSAutoreleaseNoPool(): Object 0x42abb0 of class NSConcreteValue autoreleased with no pool in place - just leaking
2011-10-01 03:50:00.286 ruby[3212:903] * __NSAutoreleaseNoPool(): Object 0xa031570 of class NSCFDictionary autoreleased with no pool in place - just leaking
Any thoughts on what likely causes might be for this? It's somewhat enigmatic message to me -- or at least it doesn't provide enough context for me to immediately diagnose. It doesn't seem to cause any of the tests to fail or anything, but I'm certain I am leaking memory -- probably from not closing a resource down properly, I would guess, but I'm not really sure how to go about tracking this down. Can ruby-debug help me figure out what's going on here? What should my next steps in the investigation here be?
A: This looks related. If you are using explicit threading in your application, check to see if you can register the cleanup widget they mention there. If not, try dusting off the C++ underneath your gem dependency and see if you can't grep it there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to share objects between different classloaders? I need different classloaders to be able to unload classes. But i need to share objects between them (actually i am getting ClassCastException). So what are the solutions to deal with this?. Thanks
A: One of the primary objectives of using separate classloaders is to prevent exactly the kind of thing that you are trying to do. Security and name conflicts are good reasons for keeping this isolation. Here are a few ways that you can circumvent this isolation.
*
*Using the Common Class Loader
*Sharing Libraries Across a Cluster
*Packaging the Client JAR for One Application in Another
Application
Refer to this link for more details.
A: Will also mention that if you are using interfaces, you can use java.lang.reflect.Proxy to create an instance of an interface local to your classloader which, under the hood, makes calls with reflection to the "real" (foreign) object from a different classloader. It's ugly, and if parameters or return types are not primitive, you will just be passing the ClassCastException further down the line. While you can rig something up to make this work, in general, it is better to either have a parent classloader with some shared types that you want to be able to use across classloaders, or use a more... serialized format for communication (slower), or only share interfaces that deal in primitives.
A: Objects from different classloaders can interact with each other through interfaces and classes loaded by a common classloader.
A: In some situation it may be acceptable to 'switch the context' by for using a thread with desired classloader. For example you create SingleThreadPoolExecutor by a context you need and use that singleton instance to execute the code from different context.
Here was my situation: maven multi module web application deployed to tomcat. One web app registered error notification service bean, and DefaultUncaughtExceptionHandler for the whole JVM using the bean to deliver error by an email (with additional logic inside). When exception was thrown by web application which created the bean email was successfully sent, when exception was thrown by different web app, email functionality failed to cope with javax.mail classes (surprisingly not the exception itself). When I executed a method which send email in an executor, both cases start to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: appcmd.exe to add/change mime type for a subdirectory of a website I read from this link to add mime for IIS 7
appcmd set config /section:staticContent /+"[fileExtension=' .xyz ',mimeType=' application/octet-stream ']"
But if I want to apply the mime settings only to a virtual directory , how to do it ?
Thanks.
A: I was able to solve the same problem just now by adding my web app's "site name" as a parameter right after "config." Not sure if it's different if your virtual directory is not its own app.
appcmd set config "My Site Name" /section:staticContent /+"[fileExtension='.xyz ',mimeType='application/octet-stream ']"
A: The appcmd syntax to add a mime type for a specific folder is like this
appcmd set config "Default Web Site/MyFolder" /section:staticContent /+"[fileExtension='.* ',mimeType='application/octet-stream ']"
to remove a mime type for a specific folder (/- instead of /+)
appcmd set config "Default Web Site/MyFolder" /section:staticContent /-"[fileExtension='.* ',mimeType='application/octet-stream ']"
Change "Default Web Site" to the name of your website
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Funny behaviour from Adobe Flex Transitions-Possible Bug I think I've just spotted an apparent bug in flex 4.5.
The link to the relevant application is here. VIEW SOURCE ENABLED!!
These are the transitions:
<s:states>
<s:State name="State1"/>
<s:State name="State2"/>
<s:State name="State3"/>
</s:states>
<s:transitions>
<s:Transition fromState="State1" toState="State2" autoReverse="true" >
<s:Sequence>
<s:Move duration="500" target="{goButton}"/>
<s:AddAction targets="{[tagsLabel,tagsTextInput]}"/>
<s:Fade targets="{[tagsLabel,tagsTextInput]}" duration="500" />
</s:Sequence>
</s:Transition>
<s:Transition fromState="State1" toState="State3" >
<s:Sequence>
<s:RemoveAction targets="{[searchLabel,searchTextInput,inLabel,inDropDownList]}" />
<s:Move duration="500" target="{goButton}" />
<s:AddAction target="{lessonsDataGrid}" />
</s:Sequence>
</s:Transition>
<s:Transition fromState="State2" toState="State3" >
<s:Sequence>
<s:RemoveAction targets="{[searchLabel,searchTextInput,inLabel,inDropDownList,tagsLabel,tagsTextInput]}" />
<s:Move duration="500" target="{goButton}" />
<s:AddAction target="{lessonsDataGrid}" />
</s:Sequence>
</s:Transition>
<s:Transition fromState="State3" toState="State1" >
<s:Sequence>
<s:RemoveAction target="{lessonsDataGrid}" />
<s:Move target="{goButton}" duration="500" />
<s:AddAction targets="{[searchLabel,searchTextInput,inLabel,inDropDownList]}" />
</s:Sequence>
</s:Transition>
</s:transitions>
You see I'm working a little bit with Transitions here; one transition gets activated on the DropDownList indexChangeEvent and another is triggered by the clickEvent on the magnifier Button.
The problem I'm facing is as follows:
If I click the 'magnifier' Button three times,(not 3 times in quick succession, but 1 click, wait for the transition, another click, wait for the transition, last click) then I get some funny behaviour: the magnifier Button vanishes, even though I've never made it disappear in the transitions; and the TextInput which was supposed to disappear didn't; it somehow got stuck in State3 which is the state with the Datagrid in it.
Trust me, I've spent at least 4 hours on this writing and rewriting those transitions, I tried all sorts of things on the web but to no avail.
Hope someone can help, I'd hate to have to accept that Flex has got a bug. I'd be relieved to know it was something I did wrong and that Flex is still reliable.
Many thanks.
A: I've played around with it for a while. Noticed that by some reason when changing the states, one of the AddItems overrides removes the element with index 0 from the Border container (you can debug and see for yourself if you add a handler for the removedFromStage event to the goButton). I'm still investigating the problem but i have a quick fix for you. Just include the goButton in all three states: includeIn="State1,State2,State3" and it won't disappear :]
If I find the reason i'll post it to you.
Hope that helps,
Blaze
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to use background gps properly in android I am writing a service that records your gps location every 30 mins. what should I write to turn on a location listener, wait x mins until my location.accuracy is less than 25 meters, then turn off the location listener.
Right now my method is draining too much battery and its not acceptable.
Thank you
A: I may have a simple piece of code here for you.
When you're starting the GPS, you just define time and distance limitations.
Also don't forget to kill this when you exit your app (last method below)
private static LocationListener gpsLocationListener = null;
/* GPS will not detach and update every 30 minutes if the delta > 25 meters */
private void getGPSLocation(Context context){
gpsLocationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1800000, 25, gpsLocationListener);
}
private class GPSLocationListener implements LocationListener{
public void onLocationChanged(Location location){
if(location != null){
final double lat = location.getLatitude();
final double lng = location.getLongitude();
// can do your other implementation here //
}
}
@Override
public void onProviderDisabled(String provider){ }
@Override
public void onProviderEnabled(String provider){ }
@Override
public void onStatusChanged(String provider, int status, Bundle extras){ }
}
private void killGPS(){
if(locationManager != null && gpsLocationListener != null){
locationManager.removeUpdates(gpsLocationListener); }
}
}
Hope this helps
-serkan
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Maps & jQuery implementation doesn't work in IE I added a google maps implementation based on google maps api v3 and this hiding/showing of results on this site.
The thing (whilst thoroughly ugly and surely not implemented well) works well in Firefox, Safari, and Opera, but doesn't work in IE. Well - it doesn't really work in IE <=7 at all and in IE8 it throws an error on this one:
($('.resultrow:not(:visible)').length == 0)
Could someone maybe take a look at this and give me any pointers on why this won't work?
You can get there from here: http://psych-info.de/index_distance.php
Just enter any German town's name in the first entry field ("ort:") and select any value (it'll be ignored anyways) from the "... km (Entfernung hier auswählen)"-dropdown.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: function call only once then errors on function it just executed I'm posting some data and retrieving it in a new menu. When I do this, I want to animate my button everytime (specifically rotate it). Rotation happens the first time, but stops executing the second time (my posts work). Firebug throws an error after the first function call that prevents the function from running again (im using jquery rotate plugin).
function submitlogic(){
if(pagetrack == 1){
$.post('combine2.php',firstpost,function(data) {
$("#newmenu").html(data);
});
rotation(); // image rotates but gives firebug error: $("#gear").rotate is not a function
pagetrack = 2;
} else if(pagetrack == 2){
$.post('combine3.php',secondpost,function(data) {
$("#newmenu").html(data);
});
rotation(); // the error prevents this call from executing
pagetrack = 3;
}
function rotation(){
$("#gear").rotate({
angle:0,
animateTo:-360,
easing: $.easing.easeInOutExpo,
callback: rotation
});
So my newbie questions are:
*
*If its erroring, how is the function running the first time? The animation is doing exactly what it should do the first time. What's it getting hung up on?
*What can i do to prevent this?
A: Okay, for anyone out there that ends up googling this -- i fixed this. There's nothing wrong with the code. But there is something wrong with the data being posted.
I was using some php from an old junk website thinking only the php calls would load. There was some commented out javascript at the top and the script tag recalling the jquery library. I stripped that, and i everything started working.
I guess the lesson here is, check to make sure you're calling what you intend to call. I guess the other stuff in the posted page alters how the original functions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: identify if two or more elements in sequence have same property I want to identify and extract the elements if two or more elements in sequence have same property inside a list.
e.g.
i have a List
there is a property for document called Isvalid
now i want to identify if two or more documents in sequence have IsValid == true
suppose the structure is
IsValid = false
IsValid = true
IsValid = true
IsValid = false
IsValid = true
IsValid = false
My query should return only elements 2 and 3 beccause only these two are in sequence and have ISvalid = true
how do i achieve it?
A: You can write a simple LINQ extension method:
public static IEnumerable<IEnumerable<TSource>>
ContinuouslyEqualSubSequences<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> func
) {
var e = source.GetEnumerator();
var currentSequence = default(List<TSource>);
var resultOfCurrentSequence = default(TResult);
if (e.MoveNext()) {
currentSequence = new List<TSource>() { e.Current };
resultOfCurrentSequence = func(e.Current);
}
while (e.MoveNext()) {
var currentResult = func(e.Current);
if(Object.Equals(resultOfCurrentSequence, currentResult)) {
currentSequence.Add(e.Current);
}
else {
if(currentSequence.Count > 1) {
yield return currentSequence;
}
currentSequence = new List<TSource>() { e.Current };
resultOfCurrentSequence = currentResult;
}
}
if (currentSequence.Count > 1) {
yield return currentSequence;
}
}
On
var sequence = new { 3, 4, 7, 8, 9, 2, 4, 6, 0, 1, 1, 17, 2, 3, 2, 20 };
var subsequences = sequence.ContinuouslyEqualSubSequences(x => x % 2);
I get back the sequences
2 4 6 0
1 1 17
2 20
as expected since we're looking here for continuous subsequences of odd or even numbers.
A: You just need to check if the current item is valid and if the previous item is valid at the same time. This will catch most cases, though you'll need to make sure you preserve the previous item if it hasn't been stored already.
Something like the code below should do. Note that it's written from memory, untested, and my not be the most efficient approach.
public List<Document> GetConsecutiveTrueDocs(List<Document> list)
{
var result = new List<Document>();
if(list.Count < 2)
return result;
for(int i = 1; i < list.Count; i++)
{
if(list[i].IsValid && list[i-1].IsValid)
{
if(!result.Contains(list[i-1]))
result.Add(list[i-1]);
result.Add(list[i]);
}
}
return result;
}
A: Here's a relatively simple extension method that takes a source sequence and a function that tells whether any two elements are considered equal, and returns a single sequence of elements:
public static IEnumerable<T> Consecutives<T>(this IEnumerable<T> source,
Func<T, T, bool> equals)
{
T last = default(T);
bool first = true;
bool returnedLast = false;
foreach (T current in source)
{
if (!first && equals(current, last))
{
if (!returnedLast)
yield return last;
returnedLast = true;
yield return current;
}
else
returnedLast = false;
first = false;
last = current;
}
}
If you try it with
var sequence = new[] { 3, 4, 7, 8, 9, 2, 4, 6, 0, 1, 1, 17, 2, 3, 2, 20 };
var subsequences = sequence.Consecutives((x, y) => x % 2 == y % 2);
You'll get back:
2
4
6
0
1
1
17
2
20
If your sequence doesn't have any duplicates, this expansion of Raymond's solution is inefficient, but very simple:
public static IEnumerable<T> Consecutives<T>(this IEnumerable<T> source,
Func<T, T, bool> equals)
{
return source.Zip(source.Skip(1), (x, y) => new[] { x, y })
.Where(d => equals(d[0], d[1]))
.SelectMany(d => d)
.Distinct();
}
A: This can be reduced to a one-liner by zipping the sequence with an offset version of itself.
public static IEnumerable<Tuple<TSource,TSource>>
Consecutives<TSource>(this IEnumerable<TSource> source,
Func<TSource, TSource, bool> equals)
{
return source.Zip(source.Skip(1), (x, y) => Tuple.Create(x,y))
.Where(d => equals(d.Item1, d.Item2));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: hyperlink field in table doesnt work I have an Access table that has a hyperlink field, with the records being a website link, to look up the UPS Worldship shipment tracking#. My problem is that even though the text has blue colored font, the link doesn’t launch and open the web browser when I click on the field.
originally the hyperlink did work, when I created the table and changed the field properties from “text” to “hyperlink”, but once I ran a delete query and an append query (in order to refresh the data), the link no longer functioned, even though the field has hyperlink properties.
Here is an example of my hyperlink record that I want the browser to launch: http://wwwapps.ups.com/WebTracking/processInputRequest?sort_by=status&tracknums_displayed=1&TypeOfInquiryNumber=T&loc=en_us&InquiryNumber1=1Z1467826772975386&track.x=0&track.y=0
Please advise what I need to do in order to make the hyperlink work, so the user doesn’t have to manually copy and paste the link into a web browser.
Thank you very much in advance
Nathaniel, Access 2003
I don't understand what you mean. I need to create an Access app that would be used throughout the day in order to track UPS packages. Ideally the table would provide a link, so that the user doesnt have to manually copy and paste the tracking number into the UPS website. Please advise if this is feasible without VBA.
A: I do not like hyperlink fields, they are difficult to edit and somewhat confusing for the user. I prefer to use a click event with FollowHyperlink. However, if you must use hyperlink fields, they have to have this format to work:
Descriptive text#link#
So
Stackoverflow#http://stackoverflow.com#
http://stackoverflow.com#http://stackoverflow.com#
Email#mailto:[email protected]#
I imagine you have lost the link - that is, the bit between the hash signs.
A: Try going back to the table with the record and change the data type to short text. Close and reopen the table and switch the data type back to hyperlink. If the text is a valid webpage link it should work without any extra coding.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Interacting with native applications using python I'm a Python programmer and I was wondering if there's any module or framework that would allow me to interact with native Windows/Linux applications using python.
Let's say on Windows I have MS Outlook, so would it be possible to let's say automate MS Outlook to compose or check new emails?
I understand that Linux and Windows are different, but what I'm trying to achieve is to let's say open up an application, click on a button programmatically, etc.
I'm not sure if all of these are at all possible using python, so please enlighten me regarding what you think is possible and practical.
A: For something like Outlook, the best bet is probably using Outlook's COM (Component Object Model) with Python COM libraries.
A: Most applications have some kind of API.
And most of those API's are accessible with C.
Therefore, Python offers ctypes.
That's the lowest common denominator. Other API's are available, but you have to use Google to find them. Sometimes they're on PyPi. It's best to be specific and search for the specific app because there may be app-specific Python bindings. You don't know until you search.
MacOSX offers more sophisticated tools than this (via AppleScript and AppScript) but it's unique to Mac OS X.
A: Here's an example in Windows:
Utilizing os.system will work to ping (a native command in Windows):
import os
os.system('ping google.com')
Alternatively, you can also you the recommended subprocess.Popen:
import subprocess
subprocess.Popen('echo "hello world"', shell=True)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery live, bind not working for 'change' I'm trying to create a Chrome extension that interacts with the Pandora player. I need to know when the song changes. I've identified which class (with a unique element) song data is written to, but I can't bind a JQuery 'change' handler to it. In the following code, clicking on the element in question causes the correct alert to display, but no alert is displayed when the value of the element changes (when the song changes).
$(document).ready(function() {
$('.playerBarSong').bind('click', function(){ alert("Click!"); });
$('.playerBarSong').bind('change', function(){ alert("Change!"); });
});
Furthermore, replacing bind with live does not change the situation. How can I detect when the value of the element changes?
A: what happens if you try:
$('.playerBarSong').change(function(){alert("change!");});
Also what exactly is playerBarSong? Is it a value?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bing Phonebook API in auto complete? Anyone know whether it is possible to get the Bing Phonebook API in Autocomplete textbox?
I am working on an application, in which I want to provide an option to add restaurants to there list, I am planning to get the restaurants from bing and wondering is it possible to provide them in Auto Complete option.
Thanks
A: First of all you Need an App-ID.
You can get one at http://www.bing.com/developers/ (5000 Transactions are free).
Then follow: Get business type/industry from Bing Phonebook API
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Detect login shell from Vim script How can I find out if Vim is executed in a login shell? I use the molokai theme for vim which provides really nice colors when I use GVim or a run vim in gnome-terminal, but I tried it in a login shell (after pressing Ctrl + Alt + F1) and it doesn't look good. What I want to do is to change the theme if I am in a session like this. The vim t_Co variable isn't useful as in both cases the terminal is reporting 256 colors.
A: I've used this in the past:
"Set the default color
color evening
"Use molokai if it's gvim or in xterm or similar
if has("gui_running") || &term == "xterm" || &term == "screen"
color molokai
endif
A: How do you know how many colors are supported by your TTY?
The consoles available with Ctrl+Alt+F1 to Ctrl+Alt+F6 don't support 256 colors here (Ubuntu 10.10).
$ echo $TERM returns linux and setting it to other classic values like xterm or xterm-256color makes it go crazy with highlighting, typing and navigation.
So I think you should consider these TTYs as 8 colors and use Matt Rogers' snippet to load a 8 colors capable colorscheme by default and a 256 colors one if possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET MVC routing by string id? In ASP.NET 2, how do I create a route that allows lookup of an object (eg Product) by a string id (eg ProductCode)? The route for looking up the same object by it's integer id (eg ProductId) is automatic, so I don't actually know how it works.
The automatic route by id is:
/Product/1
How do I also create a 2nd route that uses a string id?
/Product/red-widget
And how do I do it so that both routes are available?
A: You should take a look at using a route constraint to do this. See http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="DetailsByName"},
new {productId = @"\w+" }
);
In the above, the constraint regex "\w+" should limit to routes that match only "word" characters (take a look at regex docs for more details on patterns used here).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Map Subdomain to specific AppEngine app version I have a Python app at www.example.com. I want to create a subdomain that will map to a different version of my app (actually a Java app). So want I want to do is:
www.example.com -> example.appspot.com [0]
subdomain.example.com -> subdomain.example.appspot.com [?]
Is it doable??
A: It's not currently possible to do this, except with a reverse proxy in front of your app (or by using your main version as such a reverse proxy).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Accessing MediaPlayer in Background Agent in Windows Phone 7 I am trying to capture the current playing track in the Zune music player, in my Background Agent app. Looking at the Unsupported APIs for Background Agents page on MSDN, all of XNA is not supported - which means I can't use XNA's Media.MediaPlayer. Is there any workaround or solution for this?
A: Nope.
There is currently no way to access anything other than the tracks which you are playing in a BackgroundAudioPlayer agent.
A: Actually, there is no way to access anything other than THE track (not tracks) that the background audio player is playing. There is no concept of a playlist exposed by the BAP singleton, which apparently is the source for much frustration with this component. You have to resort to IsolatedStorage or some other hack to feed the BAP a playlist.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Building hadoop using maven I tried to build hadoop mapreduce project with maven, but it always stuck in following error,
I already perform predefined installation for yarn i.e. Protobuf installation.
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler- plugin:2.3.2:compile (default-compile) on project hadoop-yarn-common: Compilation failure: Compilation failure:
[ERROR] /home/mohyt/workspace/hadoop-trunk/hadoop-mapreduce-project/hadoop-yarn/hadoop- yarn-common/src/main/java/org/apache/hadoop/yarn/ipc/ProtoOverHadoopRpcEngine.java:[76,2] method does not override or implement a method from a supertype
[ERROR] /home/mohyt/workspace/hadoop-trunk/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/ipc/ProtoOverHadoopRpcEngine.java:[262,16] org.apache.hadoop.yarn.ipc.ProtoOverHadoopRpcEngine.Server is not abstract and does not override abstract method call(java.lang.String,org.apache.hadoop.io.Writable,long) in org.apache.hadoop.ipc.Server
[ERROR] /home/mohyt/workspace/hadoop-trunk/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/ipc/ProtoOverHadoopRpcEngine.java:[319,4] method does not override or implement a method from a supertype
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project hadoop-yarn-common: Compilation failure
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
at org.apache.maven.plugin.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:656)
at org.apache.maven.plugin.CompilerMojo.execute(CompilerMojo.java:128)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
... 19 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[ ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR] mvn <goals> -rf :hadoop-yarn-common
A: I came across same problem during hadoop 2.2.0 source code building. During "mvn install -DskipTests" this error came in "Hadoop Auth" Folder.
From somewhere(i dont remember from where) i came to know that there is one missing dependency in pom.xml of this Hadoop Auth folder
dependency is
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-util</artifactId>
<scope>test</scope>
</dependency>
I added this dependency and again tried "mvn install -DskipTests". My error resolved.
Hope this will work in your case also
A: Apache documentation says 'JavaTM 1.6.x, preferably from Sun, must be installed.'.
Also, check the override behavior in the different versions of Java.
Looks like you have Java 5.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best technique to map JSON data into ContentValues I'm developing an Android app which will initiate a number of API calls that return JSON data structures and then store the results in a content provider. Different API calls return different JSON data structures and map to a corresponding table schema in the content provider. I'm looking for a simple and Java-esque method to map from the properties in a JSONObject to a flat ContentValues object. I started to use a simple HashMap and iterating over it's entrySet mapping key strings in the JSONObject to value strings for the ContentValues object, but I'd like to account for the fact that some JSON properties are integers or booleans. Also, in some cases I'd like a more complex mapping such as a JSONArray into a comma separated string. In C, I'd probably just do this with a struct array name, value, type, and an optional callback to handle more complex mappings.
UPDATE: Due to the hierarchal nature of the JSON Data Structure and due to the fact that it can actually have sub-tables at certain depths I've taken the following approach.
private static interface MapJSON {
public void mapData(JSONObject object, ContentValues values)
throws JSONException;
}
private static abstract class AbstractMapJSON implements MapJSON {
protected final String mJSONName;
protected final String mContentName;
public AbstractMapJSON(String jsonName, String contentName) {
mJSONName = jsonName;
mContentName = contentName;
}
public abstract void mapData(JSONObject object, ContentValues values)
throws JSONException;
}
/* This is the basic template for each of the basic types */
private static class BooleanMapJSON extends AbstractMapJSON {
public BooleanMapJSON(String jsonName, String contentName) {
super(jsonName, contentName);
}
public void mapData(JSONObject object, ContentValues values)
throws JSONException {
values.put(mContentName, object.getBoolean(mJSONName));
}
}
/* This class takes a nested JSON Object and flattens it into the same table */
private static class ObjectMapJSON implements MapJSON {
protected final String mJSONName;
protected final MapJSON[] mMap;
public ObjectMapJSON(String jsonName, MapJSON[] map) {
mJSONName = jsonName;
mMap = map;
}
public void mapData(JSONObject object, ContentValues values)
throws JSONException {
JSONObject subObject = object.getJSONObject(mJSONName);
for(MapJSON mapItem: mMap) {
mapItem.mapData(subObject, values);
}
}
}
With that defined, I've can create mappings like this:
private static final MapJSON[] mainSiteMap = new MapJSON[] {
new StringMapJSON("name", StackPad.Sites.NAME),
new LongMapJSON("creation_date", StackPad.Sites.CREATION_DATE),
new StringMapJSON("description", StackPad.Sites.DESCRIPTION),
};
private static final MapJSON sitesMap = new ObjectMapJSON("main_site", mainSiteMap);
But it still seems like it needs a little work to mesh well.
A: Maybe you can build a class and use it in the hashmap , I dont know whats your types but for example
class Foo{
String name;
String value;
String type;
int opt;
}
.....
HashMap hm = new HashMap();
Foo foo = new Foo("123","123","type",1);
hm.put("100", foo);
.....
A: you can try using google's gson, create a structure for your object then map them to the object.. you can specify what datatype and support primitive types as well..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Whats the difference between a uniformed and non-uniformed histogram? I am using openCV and am wondering about the diff between being uniformed or non-uniformed.
Could someone give me a simple, NON-TECHNICAL description?
Thanks
A: A uniform histogram has bins that are exactly the same size,
For example a uniform historgram from 0-10 with 2 bins would contain the bins
{0-5} and {5-10}
Basically the histogtram is split evenly into a certain number of bins all the same size.
A non-uniform histogram will contain bins that are not of uniform size, etc, a non uniform histogram from 0-10 with 2 bins will contain bins like
{0-3} and {3-10}
Basically the historgram is split unevently into bins that are not the same size.
reference found here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django - A counter template tag that works well even with nested for tag I am trying to make a custom template tag that will increment a variable. That would be used like this:
{% for fruit in basket %}
{if fruit.is_apple %}{% count apples %}{% endif %}
{% endfor %}
<p>There are {{ apples }} apples in your basket</p>
I came up with this:
#project/app/templatetags/counter.py
class CounterNode(template.Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
if self.varname in context:
context[self.varname] += 1
else:
context[self.varname] = 1
return ''
@register.tag
def counter(parser, token):
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError(
"'counter' node requires a variable name.")
return CounterNode(args)
This works fine until you try to use the counter tag within a for loop. The count variable increments inside the loop, but gets reset to 1 when the variable is called outside the loop.
This has to do with the render() method of the template.defaulttags.ForNode class, which calls context.pop() at the end, but I am not able to grasp why this is done and how it can be dealt with within my custom template tag.
So the question is: how could I get my counter tag to increment even through for loops?
A: Scrap the count tag and create either a model method that counts fruit or pass the count via the view method. Templates are not really intended for business logic, even if it as simple as counting.
A: I found django-templateaddons library that has {% counter %} tag that works on a template level independent of nested loops.
A: I have a technique that works well for limiting behavior within nested loops that doesn't require any custom tags. The only limitation is that you must know in advance the upper limit you're trying to set. In our case, we knew we wanted to only display the first six image galleries out of an arbitrary number of publishers, and galleries per publisher. It's strictly a presentation layer limit, so we didn't want to special-case the view. The major caveat is that you must have n+1 values in the cycle tag to insure nothing repeats. Yes, I know I'm referring to 'mycycle' before it is declared, but since you can't really declare a variable inside the Django template language, I think I can be forgiven; it works great.
{% for pubs in sortedpubs %}
{% for gallery in pubs.publisher.galleries.all %}
{# Code to count inside nested loops... #}
{# Uses "cycle" from the next line to count up to 6, then stop rendering #}
{% if mycycle < 6 %}
<!-- {% cycle 1 2 3 4 5 6 7 as mycycle %} -->
{# ...Render Stuff here... #}
{% endif %}
{% endfor %}
{% endfor %}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I use ON DUPLICATE KEY UPDATE with an INSERT query using the SET option? I've seen the following (using the VALUES option):
$query = "INSERT INTO $table (column-1, column-2, column-3) VALUES ('value-1', 'value-2', 'value-3') ON DUPLICATE KEY UPDATE SET column1 = value1, column2 = value2, column3 = value3, ID=LAST_INSERT_ID(ID)";
... but I can't figure how to add ON DUPLICATE KEY UPDATE to what I'm using:
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
";
e.g.:, pseudo-code
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
ON DUPLICATE KEY UPDATE SET
column1 = value1,
column2 = value2,
column3 = value3,
$id=LAST_INSERT_ID(id)";
$my_id = mysql_insert_id();
";
I would find the latter easier to read. Would appreciate clarification, didn't find an example in the manual.
cheers
A: I've used ON DUPLICATE KEY UPDATE a lot. For some situations it's non-standard SQL extension that's really worth using.
First, you need to make sure you have a unique key constraint in place. The ON DUPLICATE KEY UPDATE function only kicks in if there would've been a unique key violation.
Here's a commonly used format:
$query = "INSERT INTO $table (column1, column2, column3)
VALUES ('value-1', 'value-2', 'value-3')
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);"
column1 = values(column1) means "Update column1 with the value that would have been inserted if the query hadn't hit the duplicate key violation." In other words, it just means update column1 to what it would've been had the insert worked.
Looking at this code, it doesn't seem correct that you're updating all three of the columns you're trying to insert. Which of the columns has a unique constraint on it?
EDIT: Modify based on 'SET' format of mysql insert statement per the question from the OP.
Basically to use ON DUPLICATE KEY UPDATE, you just write the insert statement as you normally would, but add the ON DUPLICATE KEY UPDATE clause tacked onto the end. I believe it should work like this:
INSERT INTO $table
set column1 = 'value-1',
column2 = 'value-2',
column3 = 'value-3'
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);
Again, one of the columns you're inserting has to have a unique index (or a combination of the columns). That can be because one of them is the primary key or because there is a unique index on the table.
A: Have you tried using REPLACE INTO instead?
http://www.mysqlperformanceblog.com/2007/01/18/insert-on-duplicate-key-update-and-replace-into/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Android - How to detect a single tap on a LinearLayout? I have a View and I need to detect a single tap on a LinearLayout.
I don't care about movements, All I want to detect is a single tap.
Basically a touch detection just like the touch detection on buttons. How can I achieve this?
myView.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
// This gets called so many times on every movement
return true;
}
});
A: I'm pretty sure, this would work aryaxt:
myView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// myView tapped //
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Static variables used as constants return zero in other class I have a class that I'm using to store some static default variables for a visual experiment I'm creating.
They are not marked as const, because Im using a GUI to tweak them at runtime.
When I log them in the main class ( which calls the static function init on the Defaults class ) - they are valid. But in the constructor of the different class it returns zero.
The output looks like this
"Constants::init() called" // Constants::Heads::MIN_LIFETIME initialized to 1200
preSetup-Log Constants::Heads::MIN_LIFETIME 1200
PhysicsObject- Constants::Heads::MIN_LIFETIME 0 // Y you zero?
postSetup-Log Constants::Heads::MIN_LIFETIME 1200
I'm defining the constants like this:
namespace Constants {
namespace Forces {
static int MAX_LIFETIME;
static float GRAVITY_FORCE;
};
}
static void init() {
std::cout << "Constants::init()" << std::endl;
Constants::Forces::GRAVITY_FORCE = 40000.0f;
Constants::Forces::MAX_LIFETIME = 3000;
}
A: This is because when you declare a variable static inside a (say .h) file and include that file in various .cpp files then for every .cpp file (translation unit), a separate copy of the variable is created. For example,
// x.h ...
namespace Forces {
static int MAX_LIFETIME; // unique copy for each translation unit (.cpp)
static float GRAVITY_FORCE; // same as above
extern int SOMETHING; //<----- creates only single copy
};
As shown, you should create the variable as extern inside the namespace and define that variable in only one of the .cpp files.
Other way is to enclose them inside a class instead of namespace:
class Forces {
static int MAX_LIFETIME; // only 1 copy
static float GRAVITY_FORCE; // only 1 copy
};
You still have to define them in one of the .cpp files as,
int Forces::MAX_LIFETIME = <>;
A: // header.h
namespace Constants {
namespace Forces {
extern int MAX_LIFETIME;
extern float GRAVITY_FORCE;
}
}
// my_constants.cpp
namespace Constants {
namespace Forces {
int MAX_LIFETIME = 3000;
float GRAVITY_FORCE = 40000.0f;
}
}
Then include header.h in a file that uses the constants. The constants will be initialized automatically when the program starts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I determine if there is an active facebook access token? I am using the PHP Facebook 3.0 SDK for the graph API and want a simple way to find out if there is currently an active token so that I can handle errors gracefully.
getUserAccessToken() is a protected method and so I can't seem to access it with the facebook object. There has to be a simple way to do
if(active token){ do stuff} else{ don't}
Help anyone?
A: The Facebook PHP SDK Example has all the code you need for this:
<?php
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
?>
A: Maybe you can use this type of code:
$data=file_get_contents('https://graph.facebook.com/me?access_token=xxx');
foreach ($http_response_header as $rh) if (substr($rh, 0, 4)=='HTTP') list(,$status,)=explode(' ', $rh, 3);
if ($status==200 && $data)
//Token is good, parse data
else
//Token is no good
A: Try this:
try {
$User = $Facebook->api('/me');
} catch(Exception $e) {
echo 'No active token.';
echo $e->getMessage();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What classes of problems is Clojure good/bad at solving vis-a-vis Scala? Both languages are JVM based with strong support for functional programming. I'm aware that there would be a large class of problems where both languages would provide excellent solutions.. What I would like to know is if there are any particular types of problems where features of Clojure would give it a notable edge against Scala and vice versa. At the moment we do a lot of our work in Scala but I would like to be on the lookout for particular problem spaces where Clojure can potentially provide a better solution.
A: One of the great things about Clojure and Scala is that you can use both of them in the same place, with minimal friction. I'd only suggest doing most of the interop in Clojure, since I think it has an edge there.
Just try both, and see which problems and languages fit together. You can always interoperate between Java, Scala, and Clojure code in the same system very easily.
A: Both languages are extremely capable and suitable for almost all domains. You can't particularly go wrong with either language - I'd go so far as to say that they are probably the two most promising languages around at the present.
I still think there are a couple of areas where they each have distinctive advantages:
Clojure's particular strengths relative to Scala:
*
*Concurrency - Clojure has unique and very powerful concurrency support built into the language, based around a new way of thinking about object identity and mutable state. This has been explained very well elsewhere so I won't particularly go into details here, but this video by Rich Hickey is a great place to get some insights.
*Metaprogramming - Clojure is a homoiconic language which makes it particularly suitable for macro based metaprogramming, DSL creation and code generation. It follows the Lisp "code is data" philosophy in this respect.
*Dynamic typing - Clojure is a dynamic language, with all the advantages usually associated with dynamic languages (less boilerplate, rapid prototyping, very concise code etc.)
*Functional programming - although you can do FP in Scala, Clojure definitely feels more like a functional langauge (whereas Scala is probably best described as multi-paradigm). This functional emphasis in Clojure manifests itself in several ways, for example built in lazy evaluation support across all the core libraries, all data structures are immutable, idiomatic Clojure "coding style" is functional rather than imperative/OOP.
Scala's particular strengths relative to Clojure:
*
*Object orientation - Scala is conceptually closer to Java and has better support for Java-style OOP approaches. While you can do OOP in Clojure, it's not such a comfortable fit.
*Syntactic familiarity - Scala syntax will probably be more comfortable to people coming from other non-Lisp languages
*Static typing - Scala has a very sophisticated static type system. In situation where static typing is advantageuos, Scala will have a clear edge. The usual advantages of static typing apply - the compiler can catch more potential "type" errors, the compiler has more opportunity to do performance optimisations etc.
*More mature - Scala has been around a bit longer than Clojure (2003 vs. 2007), and as a result has some of the benefits that you would expect from a more mature language (better tool support, slightly larger community)
For completeness, there are a couple of distinctive advantages that both languages share:
*
*Active and innovative communities - both languages have built up an active community with a wide variety of contributors
*Excellent interoperability with Java - both languages can easily make use of the huge array of libraries and tools in the Java ecosystem
*JVM advantages - both languages benefit from all the great engineering in the JVM (JIT compiler, garbage collection algorithms, optimised execution environment etc.)
A: I prefer using Clojure for writing DSLs because of Clojure's macro system. Also, I prefer Clojure for certain kinds of concurrent systems. Clojure's native support for software transactional memory is quite different than Scala's actor model.
Clojure doesn't have great support for object oriented programming. For projects where the object oriented paradigm works well, or you will be relying heavily on Java libraries/frameworks, I prefer Scala.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Function of type unsigned int returns negative number Wow I thought I knew my C++ but this is weird
This function returns an unsigned int so I thought that means I will never get a negative number returned right?
The function determines how many hours ahead or behind of UTC you are. So for me I'm in Australia, Sydney so I am +10 GMT which means I am UTC = LocalTime + (-10). Therefore the GetTimeZoneInformation correctly determines I am -10.
BUT my function returns an unsigned int so shouldn't it return 10 not -10?
unsigned int getTimeZoneBias()
{
TIME_ZONE_INFORMATION tzInfo;
DWORD res = GetTimeZoneInformation( &tzInfo );
if ( res == TIME_ZONE_ID_INVALID )
{
return (INT_MAX/2);
}
return (unsigned int(tzInfo.Bias / 60)); // convert from minutes to hours
}
TCHAR ch[200];
_stprintf( ch, _T("A: %d\n"), getTimeZoneBias()); // this prints out A: -10
debugLog += _T("Bias: ") + tstring(ch) + _T("\r\n");
A: Here's what I think is happening:
The value of tzInfo.Bias is actually -10. (0xFFFFFFF6)
On most systems, casting a signed integer to an unsigned integer of the same size does nothing to the representation.
So the function still returns 0xFFFFFFF6.
But when you print it out, you're printing it back as a signed integer. So it prints-10. If you printed it as an unsigned integer, you'll probably get 4294967286.
What you're probably trying to do is to get the absolute value of the time difference. So you want to convert this -10 into a 10. In which you should return abs(tzInfo.Bias / 60).
A: One error is in your _T call. It should be:
_T("A: %u\n")
The function does return a non-negative integer. However, by using the wrong printf specifier, you're causing it to get popped off the stack as an integer. In other words, the bits are interpreted wrong. I believe this is also undefined behavior.
A: You are trying to print an unsigned int as a signed int. Change %d to %u
_stprintf( ch, _T("A: %u\n"), getTimeZoneBias());
^
The problem is that integers aren't positive or negative by themselves for most computers. It's in the way they are interpreted.
So a large integer might be indistinguishable from a small (absolute value) negative one.
A: As other people have pointed out, when you cast to an unsigned int, you are actually telling the compiler to use the pattern of bits in the int and use it as an unsigned int. If your computer uses two's complement, as most do, then your number will be interpreted as UINT_MAX-10 instead of 10 as you expected. When you use the %d format specifier, the compiler goes back to using the same bit pattern as an int instead of an unsigned int. This is why you are still getting -10.
If you want the absolute value of an integer, you should try to get it mathematically instead of using a cast.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Voice recording from background Blackberry I am new in Blackberry and I want to record voice automatically from background, Please suggest me how to move further for this. And if possible please give some code.
A: Record audio on a BlackBerry smartphone
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to evaluate IO Bools in Haskell I'm trying to write a function that takes an IO Bool and does stuff based on what this is, but I can't figure out how to evaluate the IO Bool. I tried saying do cond and do {cond==True} but got the error Couldn't match expected type 'Bool' against inferred type 'a b'. Can someone direct me to a solution?
A: You'll need to unpack/pull the bool out of IO before you can use it. Here's an example:
main = useBool trueIO
trueIO :: IO Bool
trueIO = return True
useBool :: IO Bool -> IO ()
useBool a = do
b <- a
putStrLn (show b)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: inconsistent checking response.responseText? I'm using jQuery and jqGrid in an application. I have a function
function messageControl(response, formdata, id){
switch(response.responseText){
case '0': ....
case '1': ....
case '2': ....
default: ....
}
}
The response is a PHP statement like echo 0; from the jqGrid editUrl. I have this function implemented on a series of scripts that are very similar except for the database table they access. Why would this work on some, and on others always skip the case options to the default? I can see in Firebug that the response is the correct digit.
A: Make sure you're using break statements. If you are already, walk through it in a debugger to see what's happening.
EDIT: Well, that's the issue. "\n1" is not strictly equal (=== operator) to '1' (switch-case uses strict equality). In fact, it's not loosely equal (==) either. Most likely, you have output somewhere in an include. Search for headers already sent. Even though you're not getting that error, it's the same cause.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert XAML attributes to Style I have the following Rectangle:
<Rectangle x:Name="RefractionLayer" Width="200" Margin="-10,0,-80,0" Opacity=".5" >
<Rectangle.Fill>
<RadialGradientBrush GradientOrigin="0.396,1.152">
<RadialGradientBrush.RelativeTransform>
<TransformGroup>
<ScaleTransform CenterX="0.6" CenterY="0.4" ScaleX="2" ScaleY="-1"/>
<TranslateTransform X="0.02" Y="0.01"/>
</TransformGroup>
</RadialGradientBrush.RelativeTransform>
<GradientStop Offset="1" Color="#00000000"/>
<GradientStop Offset="0.4" Color="#FFFFFFFF"/>
</RadialGradientBrush>
</Rectangle.Fill>
</Rectangle>
Which I am trying to convert to a Style so I can reuse it. Here is what I have so far:
<Style x:Key="RibbonRefractionRectangle" TargetType="{x:Type Rectangle}">
<Setter Property="Width" Value="200" />
<Setter Property="Margin" Value="-10,0,-80,0" />
<Setter Property="Opacity" Value=".5" />
<Setter Property="Fill" TargetName="GradientOrigin" Value="0.396,1.152">
I cant seem to figure out how to get the Fill converted.
Ben
A: You can use the Setter.Value element as such:
<Style x:Key="RibbonRefractionRectangle" TargetType="{x:Type Rectangle}">
<Setter Property="Width" Value="200" />
<Setter Property="Margin" Value="-10,0,-80,0" />
<Setter Property="Opacity" Value=".5" />
<Setter Property="Fill">
<Setter.Value>
<RadialGradientBrush GradientOrigin="0.396,1.152">
<RadialGradientBrush.RelativeTransform>
<TransformGroup>
<ScaleTransform CenterX="0.6" CenterY="0.4" ScaleX="2" ScaleY="-1"/>
<TranslateTransform X="0.02" Y="0.01"/>
</TransformGroup>
</RadialGradientBrush.RelativeTransform>
<GradientStop Offset="1" Color="#00000000"/>
<GradientStop Offset="0.4" Color="#FFFFFFFF"/>
</RadialGradientBrush>
</Setter.Value>
</Setter>
</Style>
The rest of the style properties is as you already implemented.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to avoid exception driven programming on "connect/disconnect" methods I know that exception driven programming is something that shouldn't be done (and I imagine why).
I'm building a library where I have to estabilish a connection with a device, so the programmer will call MyDeviceInstance.Connect on some point and now is where my problem shows up.
I wrote my connect methods as void Connect(), so I'm not returning anything (because actually I don't need anything), but I will throw exception in a lot of situations:
*
*If connection already exists
*If there are some wrong settings in MyDeviceInstance
*If my interop method deviceConnect will fail (and here is the biggest problem, because it will returns an int that represents a lot of errors)
Should Connect returns a boolean instead of void?There will be a lot of possibilities that I'll throw an exception.
The second part of this question is on another method, called void Update(). This method can works only if MyDeviceInstance is already connected. In this case I'll throw exceptions when:
*
*Connection doesn't exist
*Connection is lost for any reason (and the programmer will not expect this will happen, but can)
*Other interop errors
Should update returns a bool value instead of throwing all those exceptions (at least, to limit common errors like "connection doesn't exist")?
Thanks for any answer
EDIT 1:
I have to be more precise on one point: because we are talking about an USB device, when I'll call my method Update, this method could fail depending on the device (if is connected or not). More important, if I reconnect the device the interop method will start working again (and the normal method will do the same), without needing a reconnection or things like that (I don't know how this is working internally).
For update methods, should I throw if the device is disconnected? Programmatically speaking this is an exception, but user-speaking this will be a quite-normal situation.
A: Use exceptions for exceptional circumstances. So how do you know that you have an exceptional circumstance? It does depend on context of course and there are no hard and fast rules about it. Note that exceptions are heavy-weight, and you should not be using them for normal flow in your application.
In the instances that you mention, most seem to warrant exceptions.
For Connect, a connection already existing may not be an exceptional situation. You may want to make it idempotent if you want. Interop deviceConnect failing is definitely an exceptional situation. Something you did not expect. You can raise exceptions here, probably mapping the exit codes to meaningful exceptions.
For Update, connection doesn't exist is probably an exceptional circumstance and you can raise an exception. Also, connection lost is exceptional. Like this you can evaluate your situations.
Also, you can look at returning an int that is actually the error, rather than a boolean.
A: Exceptions are exactly the right thing to use in this situation.
*
*Exceptions indicate something exceptional happened. In general you expect the connection to succeed so a failure to connect indicates an exceptional event.
*Exceptions can provide rich information about why the call failed.
*You can't ignore an exception (well you have to be deliberate about it). When the action requested represents an invalid request, it's easy for the calling method to just ignore it and continue abusing the connection. An exception forces the caller to deal with the problem.
The primary argument against using exceptions generally revolves performance. Which can be an issue if you're using exceptions for all error passing. However, when the action you are performing should typically succeed, an exception will not have any affect on performance.
A: Exceptions should be exceptional and should not be used for flow control.
Depending on your app, if the connection already exists, you could choose to be passive an return successfully.
If there's incorrect settings, that's exceptional and should throw an exception.
Concerning the interop and connect, if you return bool, you have to ask yourself if consumers will have to handle and act differently based on the different error cases. There's two models - if you return bool, you may need to return other info (as out) if consumers need to handle cases differently. Handling error conditions should also not be based on string messages - you need some structured data like an exception type or error code.
On the Update call ...
If connection does't exist, you should throw an invalidOperationException since that's a programming error.
On connection post and interop errors, it goes back to the two patterns I discussed above. If consumers need to handle different error cases you can either return bool with other info or throw.
Personally, I prefer to have less exceptions thrown and limit them to programming errors or truly exceptional cases. For example, if you save an entity that violate a business rule is that an exception? You could argue that but I would argue that it's not exceptional for someone to fill out a form and enter something that doesn't meet the rules in code - that's not exceptional.
A good rule of thumb is I like to attach a debugger with break on exception and under normal use, nothing should be thrown. It should run clean.
Here's another SO post on exceptions:
Trying to understand exceptions in C#
A: If the code which calls a method will be prepared to deal with unusual results, the method should indicate unusual results via some means other than exceptions. If the calling code will not be prepared to deal with unusual results, then such results should cause exceptions. Unfortunately, there's no way for a class to magically know whether the caller is going to expect unusual results unless the caller tells it somehow. A common pattern in .net is for a class to provide pairs of "DoSomething" and "TryDoSomething" methods:
ResultType DoSomething();
Boolean TryDoSomething(ref ResultType result);
Frankly, I think the latter formulation would be better expressed as:
ResultType TryDoSomething(ref Boolean ok);
or perhaps:
ResultType TryDoSomething(ref Exception ex);
where "ex", if non-null, would indicate that an exception (ex) would have been thrown by DoSomething (but with a blank stack trace, since the exception won't actually have been thrown). Another pattern in some cases may be:
ResultType TryDoSomething(Action failureAction);
If an unexpected situation arises, the code will call the indicated delegate, with a parameter providing details of the context where the situation arose. That delegate may be able to allow for better error handling and recovery than would otherwise be possible, since it could be called before TryDoSomething gave up on whatever it was doing. For example, it could direct TryDoSomething() to keep retrying the operation unless or until the object supplying the delegate receives a cancel request.
A: if your Connect/Update methods can fail, then by all means return a bool for failure/success. you can also add an error code and/or error message methods/properties to your class that the programmer can access if he/she needs to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: test if a specific id is used as foreign key in any foreign table entry i have a table 'users' with a column 'id'.
this id is used as foreign key in many other tables (like posts, comments, etc.).
i want to find out if there are any links to a specific user's id in any foreign tables.
this gives me all table names and column names where the column 'id' from the table 'users' is used as foreign key:
SELECT table_name,column_name
FROM information_schema.key_column_usage
WHERE referenced_table_name = 'users';
now, how can i test if my specific user id is used as foreign key in one of those tables/columns in the result - and merge this test into the sql code above to get a single query?
i found a solution and added the following function to my php database class:
/**
* isKeyUsedAsForeignKey
*
* returns true if the $key from column 'id' in $table is used as foreign key in other tables and there are one or more entries in one or more of this foreign tables with $key from $table in the respective foreign key column
*
* @param string $table table name
* @param int $key entry id
* @return bool
*/
public function isKeyUsedAsForeignKey( $table, $key ) {
$key = intval($key);
if( preg_match('/^[-_a-z0-9]+$/i',$table) && $key>0 ) {
$result = $this->query("SELECT table_name,column_name FROM information_schema.key_column_usage WHERE referenced_table_name = '".$table."'");
$select = array();
while( $result && $row=$result->fetch_assoc() )
array_push($select,"(SELECT COUNT(DISTINCT ".$row['column_name'].") FROM ".$row['table_name']." WHERE ".$row['column_name']."='".$key."') AS ".$row['table_name']);
$result2 = $this->query("SELECT ".implode(',',$select));
if( $result2 && $row=$result2->fetch_row() )
return array_sum($row)>0 ? true : false;
}
return false;
}
Now i can run the following test to determine if id 3 from 'users' is used as foreign key:
$db->isKeyUsedAsForeignKey('users',3)
As i already mentioned, it would be nice to have everything in one query. but as far as i understand it, this is not possible...
...or do you have any suggestions?
A: There is no way to do this in pure SQL. Many databases however do allow for the execution of "dynamic" queries using their procedural languages (like T-SQL, PL-SQL, etc). But this is really just another way of doing what you already did in php.
Another possibility, if you have good constraints for all of these foreign keys, and they don't cascade deletes, is to make a backup copy of the row, attempt to delete it, and catch the error that will occur if this a constraint violation. If there's no error, you have to restore the data though. Really just a theoretical idea, I think.
Finally, you could maintain an active reference count, or write a query in advance with knowledge of the foreign key relations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: 301 redirect for seo I have a site on which I ran a woorank report. One of the items it's reporting is:
www resolve Be careful! Your website without www doesn't redirect to www (or the opposite). It's duplicate content! Hide advice
High impactEasy to solve
Be sure that http://mysite.com and http://www.mysite.com are not running in parallel.
Redirecting requests from a non-preferred hostname is important because search engines consider URLs with and without "www" as two different websites.
Once your preferred domain is set, use a 301 redirect for all traffic to your non-preferred domain.
I read a few posts online and was wondering what QUICK AND EASY solution there is to fixing this in asp.net 4.
Thanks.
A: had exact same problem, fixed it with this in my global asax
basically i redirect you with 301 if you ask for my site without the www. by the way you most likely wont need the if( url rewriting) stuff. just the line in the else with do the job.
void Application_BeginRequest(object sender, EventArgs e)
{
try
{
if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().StartsWith("http://mysite"))
{
string newUrl = string.Empty;
if (HttpContext.Current.Items["UrlRewritingNet.UrlRewriter.VirtualUrl"] != null)
newUrl = "http://www.mysite.com" + HttpContext.Current.Items["UrlRewritingNet.UrlRewriter.VirtualUrl"].ToString();
else
newUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Replace("http://mysite", "http://www.mysite");
Response.Status = "301 Moved Permanently";
Response.StatusCode = 301;
Response.StatusDescription = "Moved Permanently";
Response.AddHeader("Location", newUrl);
Response.End();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Change color of certain characters in a cell I have the sentence "I would like 50 of those, please" in cell A1. I want to make any numeric characters red text (just the numeric characters). How do I do this? Here's the frame of what I have...
Sub RedText()
Dim i As Integer
For i = 1 To Len(Cells(1, 1).Value)
If IsNumeric(Mid(Cells(1, 1).Value, i, 1)) = True Then
'make the character red text
End If
Next
End Sub
Any help would be greatly appreciated.
A: You can use a RegExp for the same effect.
The advantage of the Regex approach being the code will isolate immediately any groups of numeric characters (or skip any strings that have no numerics) rather than testing each individual character.
So it offers a speed advantage if you are processing reasonably large data sets
Sub RegExpRed()
Dim objRegex As Object
Dim RegMC As Object
Dim RegM As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Global = True
.Pattern = "\d+"
If .test(Cells(1, 1).Value) Then
Set RegMC = .Execute(Cells(1, 1).Value)
For Each RegM In RegMC
Cells(1, 1).Characters(RegM.FirstIndex + 1, RegM.Length).Font.Color = vbRed
Next
End If
End With
End Sub
A: You can use the characters(start, length) property to do this. You can also store the text in a string and loop on that, which will be faster when you work with many cells. Here is an example:
Sub RedText()
Dim i As Long
Dim text As String
text = Cells(1, 1).Value
For i = 1 To Len(text)
If IsNumeric(Mid$(text, i, 1)) = True Then
Cells(1, 1).Characters(i, 1).Font.Color = vbRed
End If
Next
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Is there some kinda onClickDownListener/onClickUpListener? I've been trying to figure out a way to check if a button and/or image is being pressed. But I need to do different things depending if it's being pressed, or not pressed. Here's an example;
A player holds down a fire button, the character continues to fire until the button is lifted. How would I go about doing this?
Thanks for your time, so if my question is to vague.
A: You can just set an OnTouchListener:
ImageView myView = (ImageView)findViewById(R.id.my_image_view);
myView.setOnTouchListener(new View.OnTouchListener(){
public boolean onTouch(View v, MotionEvent event){
if (event.getAction() == MotionEvent.ACTION_DOWN){
// do here what ought to happen until the finger is lifted
}else if(event.getAction() == MotionEvent.ACTION_UP){
// stop the action because the finger is lifted
}
}
});
Hope this helps,
-serkan
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Galleria software - Could not extract a stage height from the CSS I'm experiencing an error - Could not extract a stage height from the CSS: Traced height 0px - when I refresh a page with a Galleria gallery in both IE8 and Firefox 6.0.2. I've made these changes:
1) To the html by changing this tag -
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 //EN"
2) Added the height attribute to the
.galleria-stage {height: 467px;}
3) Matched the following tags in the head section -
link type="text/css" rel="stylesheet" href="galleria/themes/classic/galleria.classic.css"
script type="text/javascript" src="js/galleria-1.2.5.min.js"
script type="text/javascript" src="galleria/themes/classic/galleria.classic.min.js"
I continue to experience this error. Please help! (I've removed less than and greater than symbols in this posting but they are included in my code).
Thanks,
Rick R.
A: According to the script author this problem has been fixed in the latest beta: https://github.com/aino/galleria/blob/master/src/galleria.js
A: I was experiencing the same issue and added the height attribute to the galleria.classic.css as well as implemented the file that "Tell me Where is Gandalf" recommended and my error went away. I was going to +1 his but my reputation isn't high enough ;)
A: not cool solution is to add at the end on galleria styling
.galleria-errors{display: none;}
its just to ignore error message
A: actually, the trick is to add the height setting in-page, and leave the rest of the settings like they are in the example
(at least for me in chrome 18.0.1025.168 m)
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script src="galleria/galleria-1.2.7.min.js"></script>
<style>
#galleria{height:467px}
</style>
</head>
<body>
<div id="galleria">
<img src="photos/photo1.jpg">
<img src="photos/photo2.jpg">
<img src="photos/photo3.jpg">
</div>
<script>
Galleria.loadTheme('galleria/themes/classic/galleria.classic.min.js');
Galleria.run('#galleria');
</script>
</body>
</html>
A: I had the same problem with version 1.2.5 and fixed it by placing:
<!doctype html>
<head>
At the very top of the document. Hope this isn't to late to help you.
A: What a mind altering experience that was! For me, it came down to which install guide I read.
This one gave me the fatal error msg and all my trial changes as I surfed a resolution.
This one got me back up and running. I took the below HTML and updated my file to look like this version with CSS entries. It worked first go.
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script src="galleria/galleria-1.2.7.min.js"></script>
<style>
#galleria{ width: 700px; height: 400px; background: #000; }
</style>
</head>
<body>
<div id="galleria">
<img src="photo1.jpg">
<img src="photo2.jpg">
<img src="photo3.jpg">
</div>
<script>
Galleria.loadTheme('galleria/themes/classic/galleria.classic.min.js');
Galleria.run("#galleria");
</script>
</body>
</html>
A: You may set height and width of the element before you call galleria.run('#galleria');.
I had the same problem and this fixed it.
A: I fixed this issue by opening the javascript file galleria-1.2.7.js and setting debug to false.
Around line 25
VERSION = 1.27,
DEBUG = false,
TIMEOUT = 50000,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why is softKeys() deprecated in Guava 10? As of Guava 10, MapMaker.softKeys is deprecated, and the corresponding method doesn't exist in CacheBuilder.
Why was this change made? What do I need to do with existing code that use it?
A: Here is my attempt of explanation of the issue (a little more complete to Chris' response)
http://groups.google.com/group/guava-discuss/browse_thread/thread/764af1e627d6fa0e?pli=1
A: I wrote the question because, initially, I did genuinely wonder why (as I had existing code that used softKeys). However, the reason was obvious on reflection and I decided to post it here, in case someone else also uses softKeys and was wondering the same thing.
In short, the reason was that softKeys never made any sense in the first place. Thus, its initial inclusion was in itself a mistake, one which the Guava developers are rectifying via deprecation.
In general, you use soft references if you want the object to stick around for a little after all the strong references are gone; in contrast, with weak references, the object usually gets collected soon once there are no strong or soft references left. This is useful for cached values that you want to hold on to temporarily, so that a lookup using the corresponding key will "revive" a strong reference for the value.
However, this behaviour doesn't make any sense for keys:
*
*Since softKeys and weakKeys maps use an identity-based lookup, the only way to get at an entry of interest is to posess a strong reference to its key.† Thus, once there are no strong key references left, the entry is effectively dead (with no possibility of revival).
*The only practical difference between softKeys and weakKeys is how long an entry remains in the map after all the strong references to its key are gone. Since such entries are dead anyway, using softKeys instead of weakKeys only delays the entry's eviction, for no good reason.
Thus, most times when coming across code that uses softKeys, a much more suitable replacement is weakKeys.
† I am not considering the case of fetching the entry via iteration, or anything other than key-based lookup, since maps are primarily about key-based operations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: PInvoke with a CString I'm trying to use P/Invoke to call functions in an unmanaged C++ DLL from C#. The C++ DLL uses CString's as function parameters and returns, such as
CString AFX_EXT_API GetUserName(CString& userID)
Unfortunately, the C++ is legacy code that I cannot change to use the more universal LPSTR (or even char *).
Is there any way to marshal the CString into a .NET compatible object? Or somehow decorate a .NET char[] to be marshaled to a CString?
A: You can't create a CString in managed code. So clearly you need an extra layer between the managed code and the native code.
This gives you an opportunity to make a C++/CLI DLL which sits between. You can call this code from your managed assembly without needing P/invoke. And from the C++/CLI middle layer you can create a CString.
However, there is one caveat. You must be using the same C++ runtime as the native DLL. This may be possible but it is quite likely that it will be a stumbling block. For example if the DLL was written with MSVC6 then you will need to build your intermediate layer with MSVC6 too and that rules out C++/CLI. Back to P/invoke and char* in that case.
I would stress that it is terrible practice to export a DLL interface based on CString and I'd be looking for alternatives to the DLL.
A: If you can't change the DLL itself, the obvious choice is writing a proxy DLL which would accept char[], allocate a CString and then call the DLL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Refresh tableview on enterforeground I have a tab bar application with five views. I need to refresh the second view when the app returns from background, but only if the user was before in that view.
I tried :
- (id)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reloadThisView:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
// Do some more stuff
}
return self;
}
- (void)reloadThisView:(NSNotification *)notification
{
[self getAllLista];
}
But I don't use and don't know how to use init in this case at all…
Any suggestions?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get locale specific directory in My documents I have my custom application that generates a directory in My documents path, after installation the application uses that directory, but i got an issue in Chinese windows OS, where my application folder name appears in Chinese, so is there any way i can get the file name properly in "en" or some wordaround so that i can that directory name at runtime.
A: Use the special folders in System.Environment
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var subFolderPath = Path.Combine(path, "sub folder");
A: String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
then you can append folder name as
string folder ="\\YOUR_FOLDER_NAME\\";
Then append to you path as
String full_path=path+folder;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: jquery function to the element that is being appended? I'm trying to append some html stuff, and I was wondering how come when I try to write some jquery function, that element that was just appended won't work?
For instance, if I had a list of text and when you click on something, that list will populate with some sort of .append('more text') to that list. Then if I have written some jquery function saying when hovering over that text, it won't work. It will only work on text that was already populated before the append.
I hope my example clarifies my question?
Thanks for your help!
A: use jQuery's live() method instead of the regular event handler. For example:
$('#myelement > *').live('mouseenter', function(evt) {
$(this).addClass('hovered');
}).live('mouseleave', function(evt) {
$(this).removeClass('hovered');
})
now, when you do this
$('#myelement').append( '<div>More Stuff</div>' );
the newly added div will get the mouseenter and mouseleave events as you wanted.
A: You are probably binding your handlers using .click(), .hover(), etc. These only work for items already on the page at the time the handler is bound.
Try using .live(event, handler) instead. This binds to elements which match now, and any elements that match that are added later.
e.g.
$('li').live('click', function() {
// do stuff here
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using android facebook sdk without oauth login, only SSO Is it possible to use the android facebook sdk auth, but only for SS0 and disable the fallback to oauth. Another words, only allow the user who has the facebook app installed and is the registered user for the phone.
A: Facebook is internally using OAuth - so I don't think this its possible...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to reference/including external source files/libraries in C with Visual Studio? Trying to create a C project that references this so that I could use it in my own application. Unfortunately I'm having a bit of trouble. I'm a C# programmer and in that language it is very simple. First you reference the library and then you use the using keyword.
However, considering I have never programmed in C before I'm having a bit of trouble with this simple task. I tried just copy and pasting all the source files in to my project directory where my main class was also stored but it still couldn't be found. I also tried including the compiled DLL but got the same error:
error C1083: Cannot open include file: 'mpir.h': No such file or directory
I'm reading the documentation for it and it says to only do this at the top of your source file:
#include <mpir.h>
Which is what I'm doing but it does not seem to be working.. Any suggestions?
A: If mpir.h is in the same directory as your source file, you need to use the include directive with quotations instead of brackets, like this:
#include "mpir.h"
Take a look at Wikipedia's description of including files.
A: I followed this tutorial to get it set up:
http://www.exploringbinary.com/how-to-install-and-run-gmp-on-windows-using-mpir/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Node.js watchFile error. "Undefined is not a function" I am new to Node.js and I am trying to run simple Node.js code.
I have Node.js windows binary.v0.5.8
Here is my js code.
var fs = require("fs");
fs.readFile('message.text', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
fs.watchFile('message.text',function (curr, prev) {
console.log('the current mtime is: ' + curr.mtime);
console.log('the previous mtime was: ' + prev.mtime);
});
When I keep only the readFile in the code it runs smoothly.
But gives following error on watchfile.
C:\Users\GG\Labs\NodeJS>node.exe test.js
node.js:208
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: undefined is not a function
at new StatWatcher (fs.js:596:18)
at Object.watchFile (fs.js:648:37)
at Object.<anonymous> (C:\Users\GG\Labs\NodeJS\test.js:25:4)
at Module._compile (module.js:425:26)
at Object..js (module.js:443:10)
at Module.load (module.js:344:31)
at Function._load (module.js:303:12)
at Array.<anonymous> (module.js:463:10)
at EventEmitter._tickCallback (node.js:200:26)
Any idea?
A: I am pretty sure that watchFile is not yet supported on windows:
https://github.com/joyent/node/issues/1358
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Page background and body background not displaying as I thought they would I am working on this site: http://www.problemio.com and I am trying to get the entire background and the body background set.
I am trying to get the areas on the very left and right sides to be the blue color, and the background of the body to be the gray color.
Instead, what is happening is for some reason, everything is blue except the header is all gray lol.
My css file is here http://www.problemio.com/main.css
How can I get the colors working as I intended? Also, I don't mind keeping the top area with the gray background as I think now it looks relatively ok.
A: @genadinik;
first problem is that your container div didn't take entire height of the child divs so how have to it clear
. Second: right now it's takes entire width of the screen so you have to define width to it
.container{
overflow:hidden;
width:1000px;
margin: 0 auto;
}
A: The default color on your page is blue:
body {
background-color : #4dbefa;
}
It looks like you have a div with the id bd that contains your main content. Since you haven't specified the background color for this div, it's effectively transparent and you'll see whatever background that's behind it. You'll need to override the background color on this div if you want the color to be different.
div#bd {
background-color: #ccc; /* some form of gray */
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to duplicate a request using wget (or curl) with raw headers? I was deubgging some http requests and found that I can grab request headers in this type of format:
GET /download?123456:75b3c682a7c4db4cea19641b33bec446/document.docx HTTP/1.1
Host: www.site.com
User-Agent: Mozilla/5.0 Gecko/2010 Firefox/5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Referer: http://www.site.com/dc/517870b8cc7
Cookie: lang=us; reg=1787081http%3A%2F%2Fwww.site.com%2Fdc%2F517870b8cc7
Is it possible or is there an easy way to reconstruct that request using wget or curl (or another CLI tool?)
From reading the wget manual page I know I can set several of these things individually, but is there an easier way to send a request with all these variables from the command line?
A: Here is curl version:
curl http://www.example.com/download?123456:75b3c682a7c4db4cea19641b33bec446/document.docx \
-H "User-Agent: Mozilla/5.0 Gecko/2010 Firefox/5" \
-H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" \
-H "Accept-Language: en-us,en;q=0.5" \
-H "Accept-Encoding: gzip, deflate"
-H "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7" \
-H "Cookie: lang=us; reg=1787081http%3A%2F%2Fwww.site.com%2Fdc%2F517870b8cc7" \
-H "Referer: http://www.example.com/dc/517870b8cc7"
In Chrome developer tools, you can use Copy as cURL to catch request as curl.
A: Yes, you just need to combine all the headers using --header
wget --header="User-Agent: Mozilla/5.0 Gecko/2010 Firefox/5" \
--header="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" \
--header="Accept-Language: en-us,en;q=0.5" \
--header="Accept-Encoding: gzip, deflate"
--header="Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7" \
--header="Cookie: lang=us; reg=1787081http%3A%2F%2Fwww.site.com%2Fdc%2F517870b8cc7" \
--referer=http://www.site.com/dc/517870b8cc7
http://www.site.com/download?123456:75b3c682a7c4db4cea19641b33bec446/document.docx
If you are trying to do some illegal download,
it might fail,
is depends on how hosting URL being programmed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: About not having Class Variables
Possible Duplicate:
Objective C Static Class Level variables
Objective-C , member/class variable
Just found out that Objective-C doesn't seem to have Class Variables. There are people who suggest that we can use static variables in Class Methods instead. It sounds reasonable to me. Wish that somebody who is knowledgable in this area can confirm this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to set up apache cxf properly in eclipse I use eclipse Helios Service Release 2 version for apache cxf. When I go to windo->preferences->Web services-> CXF 2.x preferences, and set up the cxf runtime, then the version and type doesn't get filled up automatically, which happens on any other system I have tried, What can be the problem? This is why, when I try to create a web service, it shows me "Java virtual machine error" - Could not find the main class, Program is exiting error.
Plz help me what to do to set up apache cxf properly in eclipse helios.
A: The problem was due to incompatibility of jaxb version present inside java and apache cxf. I update my java runtime to contain the latest version of jaxb (same in apache cxf and java runtime). It worked fine then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Improve a word search game worst case Consider:
a c p r c
x s o p c
v o v n i
w g f m n
q a t i t
An alphabet i_index is adjacent to another alphabet j_index in the tile if i_index is next to j_index in any of the following positions:
* * *
* x *
* * *
Here all the * indicates the location which are adjacent to x.
The task is to find a given string in the tile. The condition is that all the characters of the given string should be adjacent, and no one character in the tile may be used more than once to construct the given string.
I have came up with a simply backtracking solution, for which the solutions are pretty fast, but the worst case time is really worse.
For an example: Say the tile has 4x4 filled with all a's , therefore 16 a's, and the string to find is aaaaaaaaaaaaaaab, that is, 15 a's and one b . One what is to eliminate strings with characters which does not appear in the tile. But still worst case can still appear with say the tile have abababababababab and the string to find is abababababababbb .
My attempt is like this:
https://ideone.com/alUPf:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 5
int sp (char mat[MAX][MAX], char *pat, int c, int i, int j)
{
int r = 0;
char temp;
if (c == strlen (pat))
return 1;
if (((i<0) || (j<0)) || (i>=MAX) || (j>=MAX))
return 0;
if (mat[i][j] != pat[c])
return 0;
if (isupper (mat[i][j]))
return 0;
/* Save character and mark location to indicate
* DFS has visited this node, to stop other branches
* to enter here and cross over path
*/
temp = mat[i][j];
mat[i][j] = 0;
r |= sp (mat, pat, c+1, i-1, j-1);
r |= sp (mat, pat, c+1, i-1, j);
r |= sp (mat, pat, c+1, i-1, j+1);
r |= sp (mat, pat, c+1, i, j+1);
r |= sp (mat, pat, c+1, i+1, j+1);
r |= sp (mat, pat, c+1, i+1, j);
r |= sp (mat, pat, c+1, i+1, j-1);
r |= sp (mat, pat, c+1, i, j-1);
/* restore value */
mat[i][j] = temp;
/* mark if success */
if ((mat[i][j] == pat[c]) && (r == 1))
mat[i][j] = toupper (mat[i][j]);
return r;
}
/* Testing the `sp` module */
int main (void)
{
char mat[MAX][MAX] = {
{'a', 'c', 'p', 'r', 'c'},
{'x', 's', 'o', 'p', 'c'},
{'v', 'o', 'v', 'n', 'i'},
{'w', 'g', 'f', 'm', 'n'},
{'q', 'a', 't', 'i', 't'}
};
char pat[] = "microsoft";
int i, j;
for (i=0; i<5; i++)
{
for (j=0; j<5; j++)
printf ("%c ", mat[i][j]);
printf ("\n");
}
for (i=0; i<5; i++)
for (j=0; j<5; j++)
sp (mat, pat, 0, i, j);
printf ("\n\n\n");
for (i=0; i<5; i++)
{
for (j=0; j<5; j++)
{
if (isupper (mat[i][j]))
printf ("%c ", mat[i][j]);
else
printf (". ");
}
printf ("\n");
}
printf ("\n");
return 0;
}
which prints:
a c p r c
x s o p c
v o v n i
w g f m n
q a t i t
. . . R .
. S O . C
. O . . I
. . F M .
. . T . .
The function sp does the work, performs the back tracking.
Is there a better way ? or is it possible to lower the worst case time ?
A: There is no polynomial algorithm, so I don't think you can get much better...
It is possible to encode any grid graph (a planar graph with nodes with degree <= 4) using a letter matrix. The following grid
0-0-0
| | |
0 0-0
| |
0-0-0
Can be converted by turning edges into 'a's, vertices into 'b's and empty spaces into 'z's
B a B a B
a z a z a
B z B a B
a z a z z
B a B a B
Looking for a hamiltonian path in the original graph is equivalent to searching for the string BaBaBaBaBaBaBaBaB (with all 9 Bs). But the Hamiltonian path problem for grids in NP-complete* so the word searching problem is NP-hard.
Since a word path is clearly a polynomial certificate, the word searching problem on matrices is NP-complete.
*I remember seeing a proof for this a while ago and Wikipedia confirms, but without linking to a reference >:/
I'm pretty sure theres more on this problem out there. I just pulled this proof out of my ass and I'm pretty sure were not the first ones to look at the problem. At the least there is a good chance for nice heuristics on the non-degenerate cases you get in a real magazine puzzle...
A: One simple improvement is to check the value of r after each call to sp. If r == 1 then stop calling sp. You found your solution. This is unless you need to find all possible solutions.
Something like this (logical OR operator does not calculate second operand if first is true):
r = sp (mat, pat, c+1, i-1, j-1)) ||
sp (mat, pat, c+1, i-1, j) ||
sp (mat, pat, c+1, i-1, j+1) ||
sp (mat, pat, c+1, i, j+1) ||
sp (mat, pat, c+1, i+1, j+1) ||
sp (mat, pat, c+1, i+1, j) ||
sp (mat, pat, c+1, i+1, j-1) ||
sp (mat, pat, c+1, i, j-1) ? 1 : 0;
A: I think you might find that focusing on the worst case is counterproductive here, because there is no real improvement to be made. However, there are many useful improvements to be made in "real world" cases. For example, if the words are always drawn from a dictionary, if they may be limited in length (or have a natural distribution of lengths, statistically speaking). For small grids you could imagine searching them in advance to find all words from a dictionary, storing the list in a hashmap, and then performing a simple lookup as words need to be "tested". All the time goes into building your index, but that may be acceptable if the grid rarely changes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Not able to register my 64bit dll through nsis script ? I have a 64bit dll which i'm able to register from command prompt with regsvr32. But the problem is when i try to register my dll through nsis script its not registered. I used RegDLL command in nsis script. Anyone knows what the problem may be?
A: RegDLL is known to be problematic in anything but the simplest scenarios. Google site:forums.winamp.com nsis for examples.
To make sure that registration of your DLL, type library, BHO, etc occurs successfully, you should use InstallLib. It provides an option for x64 library installation (plus more!)
See http://nsis.sourceforge.net/Docs/AppendixB.html#B.1 for more details about library installation with NSIS.
A: you could use rundll32.exe instead:
ExecWait '"$SYSDIR\rundll32.exe" $INSTDIR\mydll.dll DllRegisterServer'
rundll32.exe is smart enough to launch the 64bit version of itself if you run it with a 64bit dll
A: ExitWait not found NSIS script. ExitWait instead ExecWait.
you cound use:
ExecWait '"$SYSDIR\rundll32.exe" $INSTDIR\mydll.dll DllRegisterSe
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How could I write select statement to these two columns? Can you write a SQL command for helping me in these two columns?
for example.....these two columns
a1 a2
______ ______
1 1
2 1
1 2
2 3
3 1
3 2
4 1
4 2
I want the output:
a1 a1
1 2
2 3
3 2
4 2
A: I'm guessing, based on your example, that you want the second column to be the maximum a2 value for the corresponding a1 value.
Then you want:
SELECT a1, MAX(a2) AS a2 FROM table GROUP BY a1
A: Basic aggregates:
SELECT a1, MAX(a2) AS a2
FROM AnonymousTable
GROUP BY a1;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Activity killed by system when idle I am writing a Location service programming that when the user go outside a predefined zone, the App will create a Notification at task bar. I am suffering from the system killing my App Activity automatically.
After I hide the App by pressing Home button, the App Activity killed by system automatically after an hour. The problem is the user cannot get any notification after the Activity killed by system.
Note: My GPS code is in the Activity Class without creating a Thread for it.
Is it possible to solve the problem by using Service? Is it possible that the Service killed by system also?
A: Absolutely, create a service, put your code there, make sure it's not too expensive (battery hog etc.) and that should do the job AndroidBegginer - i like the username good one
A:
I am suffering from the system killing my App Activity automatically. After I hide the App by pressing Home button, the App Activity killed by system automatically after an hour.
Of course. This is normal behavior. Android is reclaiming that RAM to be able to run something else. This is no different than a browser app freeing memory associated with Web pages that it downloaded an hour ago, to have more memory for downloading future pages.
Is it possible to solve the problem by using Service?
Yes, a service can run independently of an activity.
Is it possible that the Service killed by system also?
Yes, Android will kill off your service after some period of time. More importantly, the user will kill off your service after some period of time, either via a task killer or the Manage Services screen in the Settings app. Your service needs to die, because if it does not, the user's entire phone will die, because it will run out of battery life. GPS is a significant battery drain -- the phone will only be able to run for a handful of hours before it runs out of charge.
I am writing a Location service programming that when the user go outside a predefined zone, the App will create a Notification at task bar.
This is very possible to write. It is somewhat difficult to write well, in ways that will provide this functionality while not causing excessive battery drain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best Algorithm to randomly generate a number that is divisible by N Is there a better agorithm to do the following?
I am trying to generate 50 random numbers that are divisible by 7. I then select one of those 50 at random & return that number.
Is there a more efficient/better way to randomly generate numbers that are divisible by 7? Is there a better way I could code/do this?
unsigned int generateRandomNumberDivisibleByN( unsigned int n, unsigned int num=10 )
{
// Post: Generate many different random numbers that are divisible by n, then randomly select one of
// of those numbers to return.
unsigned int potentialNums[num];
for (int i=0, j=2; i<num; i++, j=rand()%INT_MAX)
{
potentialNums[i] = j*n;
}
return potentialNums[ rand()%num ]; // should this be rand()%(num-1) so it never returns an invalid array index?
}
A: The most efficient way to randomly generate a number divisible by 7 is to generate a random number and then multiply it by 7.
return ( rand() % ( INT_MAX / 7 ) ) * 7
A: Why can't you just do this?
return (rand() % MAX) * 7;
It does almost the same thing.
Where MAX is small enough to avoid overflow during the multiplication by 7. Which you can define as:
const MAX = INT_MAX / 7;
Or if you want it to be fast, you can do something like:
return (rand() & 0xff) * 7;
A: Why generate a bunch of random numbers, then choose one of them at random? You have the core idea already: generate a random number and multiply it by 7. The potentialNums array doesn't add any value.
A: To make this much faster first use the fast random generation function found here this should make the actual process of creating randoms much faster,
Next, you can multiply the random by 7 and it will always be a multiple of 7, however, if this multiplication causes an overflow of the int (which with randoms is likely) you can always take a mask of the first few bits and multiply them.
e.g.
randomNumber = (generatedRandom & 0x00FFFFFF) * 7
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7618192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.