text stringlengths 8 267k | meta dict |
|---|---|
Q: What is the difference between == and equals() in Java? I wanted to clarify if I understand this correctly:
*
*== is a reference comparison, i.e. both objects point to the same memory location
*.equals() evaluates to the comparison of values in the objects
A: String w1 ="Sarat";
String w2 ="Sarat";
String w3 = new String("Sarat");
System.out.println(w1.hashCode()); //3254818
System.out.println(w2.hashCode()); //3254818
System.out.println(w3.hashCode()); //3254818
System.out.println(System.identityHashCode(w1)); //prints 705927765
System.out.println(System.identityHashCode(w2)); //prints 705927765
System.out.println(System.identityHashCode(w3)); //prints 366712642
if(w1==w2) // (705927765==705927765)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
//prints true
if(w2==w3) // (705927765==366712642)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
//prints false
if(w2.equals(w3)) // (Content of 705927765== Content of 366712642)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
//prints true
A: Both == and .equals() refers to the same object if you don't override .equals().
Its your wish what you want to do once you override .equals(). You can compare the invoking object's state with the passed in object's state or you can just call super.equals()
A: In general, the answer to your question is "yes", but...
*
*.equals(...) will only compare what it is written to compare, no more, no less.
*If a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.
*If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you're left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.
*Always remember to override hashCode if you override equals so as not to "break the contract". As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods show that they are equivalent. The converse is not necessarily true.
A: There are some small differences depending whether you are talking about "primitives" or "Object Types"; the same can be said if you are talking about "static" or "non-static" members; you can also mix all the above...
Here is an example (you can run it):
public final class MyEqualityTest
{
public static void main( String args[] )
{
String s1 = new String( "Test" );
String s2 = new String( "Test" );
System.out.println( "\n1 - PRIMITIVES ");
System.out.println( s1 == s2 ); // false
System.out.println( s1.equals( s2 )); // true
A a1 = new A();
A a2 = new A();
System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" );
System.out.println( a1 == a2 ); // false
System.out.println( a1.s == a2.s ); // true
System.out.println( a1.s.equals( a2.s ) ); // true
B b1 = new B();
B b2 = new B();
System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
System.out.println( b1 == b2 ); // false
System.out.println( b1.getS() == b2.getS() ); // false
System.out.println( b1.getS().equals( b2.getS() ) ); // true
}
}
final class A
{
// static
public static String s;
A()
{
this.s = new String( "aTest" );
}
}
final class B
{
private String s;
B()
{
this.s = new String( "aTest" );
}
public String getS()
{
return s;
}
}
You can compare the explanations for "==" (Equality Operator) and ".equals(...)" (method in the java.lang.Object class) through these links:
*
*==: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
*.equals(...): http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
A: Here is a general thumb of rule for the difference between relational operator == and the method .equals().
object1 == object2 compares if the objects referenced by object1 and object2 refer to the same memory location in Heap.
object1.equals(object2) compares the values of object1 and object2 regardless of where they are located in memory.
This can be demonstrated well using String
Scenario 1
public class Conditionals {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = new String("Hello");
System.out.println("is str1 == str2 ? " + (str1 == str2 ));
System.out.println("is str1.equals(str2) ? " + (str1.equals(str2 )));
}
}
The result is
is str1 == str2 ? false
is str1.equals(str2) ? true
Scenario 2
public class Conditionals {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
System.out.println("is str1 == str2 ? " + (str1 == str2 ));
System.out.println("is str1.equals(str2) ? " + (str1.equals(str2 )));
}
}
The result is
is str1 == str2 ? true
is str1.equals(str2) ? true
This string comparison could be used as a basis for comparing other types of object.
For instance if I have a Person class, I need to define the criteria base on which I will compare two persons. Let's say this person class has instance variables of height and weight.
So creating person objects person1 and person2 and for comparing these two using the .equals() I need to override the equals method of the person class to define based on which instance variables(heigh or weight) the comparison will be.
However, the == operator will still return results based on the memory location of the two objects(person1 and person2).
For ease of generalizing this person object comparison, I have created the following test class. Experimenting on these concepts will reveal tons of facts.
package com.tadtab.CS5044;
public class Person {
private double height;
private double weight;
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(height);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
/**
* This method uses the height as a means of comparing person objects.
* NOTE: weight is not part of the comparison criteria
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (Double.doubleToLongBits(height) != Double.doubleToLongBits(other.height))
return false;
return true;
}
public static void main(String[] args) {
Person person1 = new Person();
person1.setHeight(5.50);
person1.setWeight(140.00);
Person person2 = new Person();
person2.setHeight(5.70);
person2.setWeight(160.00);
Person person3 = new Person();
person3 = person2;
Person person4 = new Person();
person4.setHeight(5.70);
Person person5 = new Person();
person5.setWeight(160.00);
System.out.println("is person1 == person2 ? " + (person1 == person2)); // false;
System.out.println("is person2 == person3 ? " + (person2 == person3)); // true
//this is because perosn3 and person to refer to the one person object in memory. They are aliases;
System.out.println("is person2.equals(person3) ? " + (person2.equals(person3))); // true;
System.out.println("is person2.equals(person4) ? " + (person2.equals(person4))); // true;
// even if the person2 and person5 have the same weight, they are not equal.
// it is because their height is different
System.out.println("is person2.equals(person4) ? " + (person2.equals(person5))); // false;
}
}
Result of this class execution is:
is person1 == person2 ? false
is person2 == person3 ? true
is person2.equals(person3) ? true
is person2.equals(person4) ? true
is person2.equals(person4) ? false
A: The difference between == and equals confused me for sometime until I decided to have a closer look at it.
Many of them say that for comparing string you should use equals and not ==. Hope in this answer I will be able to say the difference.
The best way to answer this question will be by asking a few questions to yourself. so let's start:
What is the output for the below program:
String mango = "mango";
String mango2 = "mango";
System.out.println(mango != mango2);
System.out.println(mango == mango2);
if you say,
false
true
I will say you are right but why did you say that?
and If you say the output is,
true
false
I will say you are wrong but I will still ask you, why you think that is right?
Ok, Let's try to answer this one:
What is the output for the below program:
String mango = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango3);
System.out.println(mango == mango3);
Now If you say,
false
true
I will say you are wrong but why is it wrong now?
the correct output for this program is
true
false
Please compare the above program and try to think about it.
Ok. Now this might help (please read this : print the address of object - not possible but still we can use it.)
String mango = "mango";
String mango2 = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango2);
System.out.println(mango == mango2);
System.out.println(mango3 != mango2);
System.out.println(mango3 == mango2);
// mango2 = "mang";
System.out.println(mango+" "+ mango2);
System.out.println(mango != mango2);
System.out.println(mango == mango2);
System.out.println(System.identityHashCode(mango));
System.out.println(System.identityHashCode(mango2));
System.out.println(System.identityHashCode(mango3));
can you just try to think about the output of the last three lines in the code above:
for me ideone printed this out (you can check the code here):
false
true
true
false
mango mango
false
true
17225372
17225372
5433634
Oh! Now you see the identityHashCode(mango) is equal to identityHashCode(mango2) But it is not equal to identityHashCode(mango3)
Even though all the string variables - mango, mango2 and mango3 - have the same value, which is "mango", identityHashCode() is still not the same for all.
Now try to uncomment this line // mango2 = "mang"; and run it again this time you will see all three identityHashCode() are different.
Hmm that is a helpful hint
we know that if hashcode(x)=N and hashcode(y)=N => x is equal to y
I am not sure how java works internally but I assume this is what happened when I said:
mango = "mango";
java created a string "mango" which was pointed(referenced) by the variable mango something like this
mango ----> "mango"
Now in the next line when I said:
mango2 = "mango";
It actually reused the same string "mango" which looks something like this
mango ----> "mango" <---- mango2
Both mango and mango2 pointing to the same reference
Now when I said
mango3 = new String("mango")
It actually created a completely new reference(string) for "mango". which looks something like this,
mango -----> "mango" <------ mango2
mango3 ------> "mango"
and that's why when I put out the values for mango == mango2, it put out true. and when I put out the value for mango3 == mango2, it put out false (even when the values were the same).
and when you uncommented the line // mango2 = "mang";
It actually created a string "mang" which turned our graph like this:
mango ---->"mango"
mango2 ----> "mang"
mango3 -----> "mango"
This is why the identityHashCode is not the same for all.
Hope this helps you guys.
Actually, I wanted to generate a test case where == fails and equals() pass.
Please feel free to comment and let me know If I am wrong.
A: Just remember that .equals(...) has to be implemented by the class you are trying to compare. Otherwise, there isn't much of a point; the version of the method for the Object class does the same thing as the comparison operation: Object#equals.
The only time you really want to use the comparison operator for objects is wen you are comparing Enums. This is because there is only one instance of an Enum value at a time. For instance, given the enum
enum FooEnum {A, B, C}
You will never have more than one instance of A at a time, and the same for B and C. This means that you can actually write a method like so:
public boolean compareFoos(FooEnum x, FooEnum y)
{
return (x == y);
}
And you will have no problems whatsoever.
A: When you evaluate the code, it is very clear that (==) compares according to memory address, while equals(Object o) compares hashCode() of the instances.
That's why it is said do not break the contract between equals() and hashCode() if you do not face surprises later.
String s1 = new String("Ali");
String s2 = new String("Veli");
String s3 = new String("Ali");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println("(s1==s2):" + (s1 == s2));
System.out.println("(s1==s3):" + (s1 == s3));
System.out.println("s1.equals(s2):" + (s1.equals(s2)));
System.out.println("s1.equal(s3):" + (s1.equals(s3)));
/*Output
96670
3615852
96670
(s1==s2):false
(s1==s3):false
s1.equals(s2):false
s1.equal(s3):true
*/
A: The major difference between == and equals() is
1) == is used to compare primitives.
For example :
String string1 = "Ravi";
String string2 = "Ravi";
String string3 = new String("Ravi");
String string4 = new String("Prakash");
System.out.println(string1 == string2); // true because same reference in string pool
System.out.println(string1 == string3); // false
2) equals() is used to compare objects.
For example :
System.out.println(string1.equals(string2)); // true equals() comparison of values in the objects
System.out.println(string1.equals(string3)); // true
System.out.println(string1.equals(string4)); // false
A: Example 1 -
Both == and .equals methods are there for reference comparison only. It means whether both objects are referring to same object or not.
Object class equals method implementation
public class HelloWorld{
public static void main(String []args){
Object ob1 = new Object();
Object ob2 = ob1;
System.out.println(ob1 == ob2); // true
System.out.println(ob1.equals(ob2)); // true
}
}
Example 2 -
But if we wants to compare objects content using equals method then class has to override object's class equals() method and provide implementation for content comparison. Here, String class has overrided equals method for content comparison. All wrapper classes have overrided equals method for content comparison.
String class equals method implementation
public class HelloWorld{
public static void main(String []args){
String ob1 = new String("Hi");
String ob2 = new String("Hi");
System.out.println(ob1 == ob2); // false (Both references are referring two different objects)
System.out.println(ob1.equals(ob2)); // true
}
}
Example 3 -
In case of String, there is one more usecase. Here when we assign any string to String reference then string constant is created inside String constant pool. If we assign same string to new String reference then no new string constant is created rather it will refer to existing string constant.
public class HelloWorld{
public static void main(String []args){
String ob1 = "Hi";
String ob2 = "Hi";
System.out.println(ob1 == ob2); // true
System.out.println(ob1.equals(ob2)); // true
}
}
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
Java API equals() method contract
A:
The == operator tests whether two variables have the same references
(aka pointer to a memory address).
String foo = new String("abc");
String bar = new String("abc");
if(foo==bar)
// False (The objects are not the same)
bar = foo;
if(foo==bar)
// True (Now the objects are the same)
Whereas the equals() method tests whether two variables refer to objects
that have the same state (values).
String foo = new String("abc");
String bar = new String("abc");
if(foo.equals(bar))
// True (The objects are identical but not same)
Cheers :-)
A: Also note that .equals() normally contains == for testing as this is the first thing you would wish to test for if you wanted to test if two objects are equal.
And == actually does look at values for primitive types, for objects it checks the reference.
A: == operator always reference is compared. But in case of
equals() method
it's depends's on implementation if we are overridden equals method than it compares object on basic of implementation given in overridden method.
class A
{
int id;
String str;
public A(int id,String str)
{
this.id=id;
this.str=str;
}
public static void main(String arg[])
{
A obj=new A(101,"sam");
A obj1=new A(101,"sam");
obj.equals(obj1)//fasle
obj==obj1 // fasle
}
}
in above code both obj and obj1 object contains same data but reference is not same so equals return false and == also.
but if we overridden equals method than
class A
{
int id;
String str;
public A(int id,String str)
{
this.id=id;
this.str=str;
}
public boolean equals(Object obj)
{
A a1=(A)obj;
return this.id==a1.id;
}
public static void main(String arg[])
{
A obj=new A(101,"sam");
A obj1=new A(101,"sam");
obj.equals(obj1)//true
obj==obj1 // fasle
}
}
know check out it will return true and false for same case only we overridden
equals method .
it compare object on basic of content(id) of object
but ==
still compare references of object.
A: It may be worth adding that for wrapper objects for primitive types - i.e. Int, Long, Double - == will return true if the two values are equal.
Long a = 10L;
Long b = 10L;
if (a == b) {
System.out.println("Wrapped primitives behave like values");
}
To contrast, putting the above two Longs into two separate ArrayLists, equals sees them as the same, but == doesn't.
ArrayList<Long> c = new ArrayList<>();
ArrayList<Long> d = new ArrayList<>();
c.add(a);
d.add(b);
if (c == d) System.out.println("No way!");
if (c.equals(d)) System.out.println("Yes, this is true.");
A: == can be used in many object types but you can use Object.equals for any type , especially Strings and Google Map Markers.
A: public class StringPool {
public static void main(String[] args) {
String s1 = "Cat";// will create reference in string pool of heap memory
String s2 = "Cat";
String s3 = new String("Cat");//will create a object in heap memory
// Using == will give us true because same reference in string pool
if (s1 == s2) {
System.out.println("true");
} else {
System.out.println("false");
}
// Using == with reference and Object will give us False
if (s1 == s3) {
System.out.println("true");
} else {
System.out.println("false");
}
// Using .equals method which refers to value
if (s1.equals(s3)) {
System.out.println("true");
} else {
System.out.println("False");
}
}
}
----Output-----
true
false
true
A: You will have to override the equals function (along with others) to use this with custom classes.
The equals method compares the objects.
The == binary operator compares memory addresses.
A: With respect to the String class:
The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.
On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".
As with any explanation, let it sink in.
I hope this clears things up a bit.
A: == is an operator and equals() is a method.
Operators are generally used for primitive type comparisons and thus == is used for memory address comparison and equals() method is used for comparing objects.
A: Since Java doesn’t support operator overloading, == behaves identical
for every object but equals() is method, which can be overridden in
Java and logic to compare objects can be changed based upon business
rules.
Main difference between == and equals in Java is that "==" is used to
compare primitives while equals() method is recommended to check
equality of objects.
String comparison is a common scenario of using both == and equals() method. Since java.lang.String class override equals method, It
return true if two String object contains same content but == will
only return true if two references are pointing to same object.
Here is an example of comparing two Strings in Java for equality using == and equals() method which will clear some doubts:
public class TEstT{
public static void main(String[] args) {
String text1 = new String("apple");
String text2 = new String("apple");
//since two strings are different object result should be false
boolean result = text1 == text2;
System.out.println("Comparing two strings with == operator: " + result);
//since strings contains same content , equals() should return true
result = text1.equals(text2);
System.out.println("Comparing two Strings with same content using equals method: " + result);
text2 = text1;
//since both text2 and text1d reference variable are pointing to same object
//"==" should return true
result = (text1 == text2);
System.out.println("Comparing two reference pointing to same String with == operator: " + result);
}
}
A: The String pool (aka interning) and Integer pool blur the difference further, and may allow you to use == for objects in some cases instead of .equals
This can give you greater performance (?), at the cost of greater complexity.
E.g.:
assert "ab" == "a" + "b";
Integer i = 1;
Integer j = i;
assert i == j;
Complexity tradeoff: the following may surprise you:
assert new String("a") != new String("a");
Integer i = 128;
Integer j = 128;
assert i != j;
I advise you to stay away from such micro-optimization, and always use .equals for objects, and == for primitives:
assert (new String("a")).equals(new String("a"));
Integer i = 128;
Integer j = 128;
assert i.equals(j);
A: In short, the answer is "Yes".
In Java, the == operator compares the two objects to see if they point to the same memory location; while the .equals() method actually compares the two objects to see if they have the same object value.
A: It is the difference between identity and equivalence.
a == b means that a and b are identical, that is, they are symbols for very same object in memory.
a.equals( b ) means that they are equivalent, that they are symbols for objects that in some sense have the same value -- although those objects may occupy different places in memory.
Note that with equivalence, the question of how to evaluate and compare objects comes into play -- complex objects may be regarded as equivalent for practical purposes even though some of their contents differ. With identity, there is no such question.
A: Basically, == compares if two objects have the same reference on the heap, so unless two references are linked to the same object, this comparison will be false.
equals() is a method inherited from Object class. This method by default compares if two objects have the same referece. It means:
object1.equals(object2) <=> object1 == object2
However, if you want to establish equality between two objects of the same class you should override this method. It is also very important to override the method hashCode() if you have overriden equals().
Implement hashCode() when establishing equality is part of the Java Object Contract. If you are working with collections, and you haven't implemented hashCode(), Strange Bad Things could happen:
HashMap<Cat, String> cats = new HashMap<>();
Cat cat = new Cat("molly");
cats.put(cat, "This is a cool cat");
System.out.println(cats.get(new Cat("molly"));
null will be printed after executing the previous code if you haven't implemented hashCode().
A: In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
A: equals() method mainly compares the original content of the object.
If we Write
String s1 = "Samim";
String s2 = "Samim";
String s3 = new String("Samim");
String s4 = new String("Samim");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
System.out.println(s3.equals(s4));
The output will be
true
true
true
Because equals() method compare the content of the object.
in first System.out.println() the content of s1 and s2 is same that's why it print true.
And it is same for others two System.out.println() is true.
Again ,
String s1 = "Samim";
String s2 = "Samim";
String s3 = new String("Samim");
String s4 = new String("Samim");
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s3 == s4);
The output will be
true
false
false
Because == operator mainly compare the references of the object not the value.
In first System.out.println(), the references of s1 and s2 is same thats why it returns true.
In second System.out.println(), s3 object is created , thats why another reference of s3 will create , and the references of s2 and s3 will difference, for this reason it return "false".
Third System.out.println(), follow the rules of second System.out.println(), that's why it will return "false".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "759"
} |
Q: Flash SWF file cannot find XML data file when loaded into WebBrowser control (but works in IE9) Bit of a long explanation below, with a hopefully accurate short question summary here:
Can a .NET WebBrowser control (Win7 64-bit, IE9, current Flash 10.3.183.7) load a SWF file into an <object> tag, where the SWF file is in a separate folder that also contains an XML data file in such a way as to have the SWF file load and display the XML data?
UPDATE: Added some more information below based on some further experimentation...
Gory detail:
This has plagued me for a couple of days. Consider the following:
C:\dev\wb.exe -- program that uses a WebBrowser to show a local SWF file from the disk
c:\data\mySWF.swf -- the SWF file I want to play
c:\data\myData.xml -- the file with data that mySWF.swf is looking for
C:\html\index.html -- HTML file loaded by wb.exe. This file has an <object> tag to set up a Flash ActiveX control playing c:\data\mySWF.swf.
Originally, this started with swfobject.js being used, and when I didn't see the results I was expecting, I kept simplifying until I got to the point where I don't have anything but an HTML file with no additional libraries.
If I load the index.html into IE9, it works. I see the SWF file playing with the data from the XML file loaded.
When I run wb.exe, it loads the C:\html\index.html file, and I see the SWF playing. But the data fields are empty. If I copy the index.html to C:\data\index.html and load it into wb.exe, THEN I see my data.
My index.html file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
* {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body MARGINWIDTH="0" MARGINHEIGHT="0" LEFTMARGIN="0" RIGHTMARGIN="0" TOPMARGIN="0" BOTTOMMARGIN="0">
<object type="application/x-shockwave-flash" width=100%" height="100%" id='player1' name='player1'>
<param name='movie' value='C:\data\mySWF.swf'>
<param name='allowfullscreen' value='true'>
<param name='allowscriptaccess' value='always'>
<param name='base' value='C:\data\'>
<param name='menu' value='false'>
<param name='quality' value='best'>
<param name='scale' value='exactfit'>
</object>
</body>
</html>
The base parameter seemed to be part of getting this to work, but I'm stymied as to why (or whether) I can get the Flash ActiveX control to work the way I need it to, without having to load an HTML file from the same folder as the SWF file.
UPDATE: If I put the myData.xml file into the C:\html folder, and I load from C:\html\index.html, I get the data values in the SWF. So it seems that the Flash plug-in is using the path of the index.html file, and NOT the base parameter.
UPDATE: We've found out, through more experiementation, that this problem does NOT appear to occur if the SWF file uses Action Script 2 (AS2) for its XML handling (via XML.load()), but a SWF file using Action Script 3 (AS3) (via URLLoader.load()) does NOT work properly. This just gets weirder.
I appreciate your patience if you stuck around this far, and hopefully you might be able to educate me as to my problem.
Thanks.
A: As a follow-up to my own question, there's no nice solution.
We worked around the issue by using jQuery to adjust a <base href="">tag in the main HTML to refer to the folder with the SWF and XML file in, each time we loaded a new SWF file. That works, but no one's really happy with it.
We talked to Microsoft, and then to Adobe. Adobe calls the use of Flash in a .NET WebBrowser control an "unsupported use case" and doesn't want anything more to do with the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ant rule/task that can forward a variable number of cmd line arguments to a task I want an ant task that includes command line passed arguments. The command line arguments can vary in number.
Specifically, for the <java> task within ant.
I would like to do this on the command line:
$ ant run foo bar ...
Ideally, "foo" and "bar" and other arguments "...", would be passed as trailing arguments to the java instance created in the <java> task.
java would see:
$ java -classpath ./output Foobar foo bar ...
In other words, I would like the same ant <java> task do the following:
$ ant run foo
# executes "java -classpath ./output Foobar foo"
$ ant run foo bar
# executes "java -classpath ./output Foobar foo bar"
$ ant run foo bar baz
# executes "java -classpath ./output Foobar foo bar baz"
I imagined this might look something like :
<project name="Foobar" basedir=".">
<property name="build" location="output"/>
<target name="run" >
<java failonerror="true" classname="Foobar" fork="true">
<classpath>
<dirset dir="${build}" />
</classpath>
<arg line="$@"/>
</java>
</target>
</project>
Notice the line
<arg line="$@"/>
I imagined something like the above would pass all remaining arguments to the java instance. (The purpose of this Question is to find that particular ant mechanism).
The methods I have seen for this require preconfigured ant variables. That is,
$ ant run -DARG1="foo" -DARG2="bar" ...
But that method precludes a variable length argument list.
Does anyone know a method for a variable number of argument that could be forwarded to an ant <java> task (preferably doesn't require writing a complex set of ant rules)?
A: That's not easy because Ant's command line looks like this:
ant [options] [target [target2 [target3] ...]]
That means your variable arg list foo bar baz items would be treated as targets, leading to similarly named Ant targets being run, or Ant throwing errors if they don't exist.
One option is to use the -Doption=value syntax to pass the variable argument list by means of a wrapper script. Perhaps:
ant -classpath ./output -Dmy_args=\"$@\" Foobar
in a shell script, then make use of the passed arg in the java task:
<arg line="${my_args}"/>
Another option would be to write a Java main() class that will accept the arguments as you want them to be, and then call Ant for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Video making software for Android Tablet I wanted to make video demo of my application in order to present. How can i make my application video when it running and open on android Tablet.
A: I've tried to come up with ways to do this to no avail. Best I've ever been able to achieve is stick your device in front of a nice camera.
However this http://www.bluestacks.com/ seems like it might be promising for this purpose once it is released. If you can run your apps on a windows machine (and it is much better than the emulator) then you could record that section of your screen with something like Fraps.
Edit: Bluestacks has since opened up for beta. For me it runs similarly to the emulator so does not provide a whole lot of benefit for the purposes of recording your applications. If you don't have a development environment with an emulator set up already though bluestacks will be ready for you to actually start recording quicker.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to post to a user's wall while he is offline,renew his token(if expired) via my app. C# Facebook SDK I know how to use the token after the user successfuly logs in with
FacebookLoginDialog(AppId, ExtendedPermissions);
but what happens when my app wants to post at this user while he is offline? And how can i renew the token? Is there a way to regognize that a user has allowed the app to post by only his id?
A: Request offline_access extended permission and then you can post when the user is offline and you want have to worry about refreshing the token.
A: From Facebook's documentation:
Enables your app to post content, comments, and likes to a user's
stream and to the streams of the user's friends. With this permission,
you can publish content to a user's feed at any time, without
requiring offline_access.
It seems like there is really no need to have that offline_access permission to post on user's wall while there are offline - there has to be a way to 'refresh' the access token, or use the application's token.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MPMoviePlayerViewController play movie from Documents directory - objective-c I have subfolder called "Video" in Documents folder. And there is somevideo.mp4 file. I have full path to this file but MPMoviePlayerViewController doesn't want to play video from local. Here is code:
NSString *path = [[self getVideoFolderPath] stringByAppendingPathComponent:@"somevideo.mp4"];
NSURL *fURL = [NSURL fileURLWithPath:path];
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:fURL];
[self presentMoviePlayerViewControllerAnimated:videoPlayerView];
[videoPlayerView.moviePlayer play];
It doesn't play. Appears white screen and nothing else. This code works with remote video, when i put URL to website with video file, but local doesn't play. How to get correct file path to video file?
A: Are you using iOS prior to 4.3? If so, you need to do this
[videoPlayerView setContentURL: fURL];
Here is a snippet of code from where I play video from the documents folder. One of the things I would recommend is to avoid some of the autorelease objects. Especially on NSURL when you have viewcontrollers. I know it should be safe but I've never found it to be 100%
if ( [[NSFileManager defaultManager] fileExistsAtPath:fullpathVideoFile] == NO )
{
NSLog(@"No video file found");
return self;
}
playbackURL = [[NSURL alloc] initFileURLWithPath:fullpathVideoFile isDirectory:NO];
if ( playbackURL == nil )
{
NSLog(@"playbackURL == nil");
return self;
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerLoadedMovie:) name:@"MPMoviePlayerLoadStateDidChangeNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerStartedMovie:) name:@"MPMoviePlayerNowPlayingMovieDidChangeNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinishedMovie:) name:@"MPMoviePlayerPlaybackDidFinishNotification" object:nil];
[self setContentURL:playbackURL];
In my case, I created a subclass of MPMoviePlayerController (as I generally do with all view controllers) so the references to 'self' would be to the MPMoviePlayerController object instance
A: Strange. The code you put seems to be correct. Make sure the path to the audio you are trying to retrieve isn't broken.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MySQL Left Join Subselect I have a simple table of languages / template id's:
language | template
en, t1
en, t1
au, t2
ge, t3
en, t1
ge, t2
ge, t3
Template is always either t1,t2, or t3. In total there are 3 languages: en, au, ge.
There is lots more information in the table, I am just showing what is relevant to this question, I will be using the data for graphing and so need it returning in this format:
en, t1, 3
en, t2, 0
en, t3, 0
au, t1, 0
au, t2, 1
au, t3, 0
ge, t1, 0
ge, t2, 1
ge, t3, 2
This counts however many template occurrences there are in each language. But, the problem I have is returning a zero count if there are no template id's for that particular language in the table.
I was thinking it would need some sort of left join sub select on the template id to make sure the 3 template id's are returned for each language?
A: There might be a better way of doing this, and I haven't tested it in MySQL, but the following works in SQL Server 2005:
Select a.language, b.template, count (c.template) as combo_count
from
(select distinct language from tablename) as a
inner join (select distinct template from tablename) as b on 1 < 2 /* this could be cross join, same thing. */
left outer join tablename c on c.language = a.language and c.template = b.template
group by a.language, b.template
order by 1, 2
Here are the results with your sample data:
au t1 0
au t2 1
au t3 0
en t1 3
en t2 0
en t3 0
ge t1 0
ge t2 1
ge t3 2
A: Select a.language, a.template, Count(*) count
From (Select Distinct language, template From table) a
Left Join table b
On b.language = a.language
And b.template = b.template
Group By a.language, a.template
A: What you need is two tables that list the possible values for language and template.
CREATE TABLE language (...) AS SELECT DISTINCT language FROM your_table;
CREATE TABLE template (...) AS SELECT DISTINCT template FROM your_table;
Then you can do something like this:
SELECT l.language, t.template, SUM(CASE WHEN yours.language IS NULL THEN 0 ELSE 1 END) count
FROM language l CROSS JOIN template t
LEFT OUTER JOIN your_table yours ON l.language = yours.language AND t.template = yours.template
GROUP BY l.language, t.template;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What does self do in ruby on rails? I'm on railcasts just practicing some rails and have come across something I'm trying to understand.
I didn't get what the "self" on the authenticate method was doing. So I deleted it and tested the login of my app to see if it would show an error and it did:
error:
**NoMethodError in SessionsController#create
undefined method `authenticate' for #<Class:0x00000102cb9000**>
I would really appreciate if someone could explain exactly what that "Self" is doing. I was trying to figure out exactly what was going on but can't get my head around it.
Method is defined in model and called in sessions_controller..
I've been continuously deleting my app and starting from scratch to get the hang of it and many things make sense to me each time i start again but I'm stuck at "self".
I'm just the type of person who likes to understand why something works.
controller:
def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_path, :notice => "Logged In"
else
flash.now.alert = "Invalid credentials"
render "new"
end
end
model:
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
A: self defines a method of the class instead of the instance of the class. So with def self.authenticate you can do the following:
u = User.authenticate('email@domain.com','p@ss')
Instead of doing…
u = User.new
u.authenticate('email@domain.com','p@ss')
That way, you don't have to create an instance of user to authenticate one.
A: For the sake of completion and to thwart future headaches, I'd like to also point out that the two are equivalent:
class User
def self.authenticate
end
end
class User
def User.authenticate
end
end
Matter of preference.
A: class User
def self.xxx
end
end
is one way of defining class method while
class User
def xxx
end
end
will define an instance method.
If you remove the self. from the def, you will get a method not found error when you do
User.authenticate
because you are trying to call a method on a class rather than an instance of the class. To use an instance method, you need an instance of a class.
A: This is a basic ruby question. In this case, self is used to define a class method.
class MyClass
def instance_method
puts "instance method"
end
def self.class_method
puts "class method"
end
end
Which are used like this:
instance = MyClass.new
instance.instance_method
Or:
MyClass.class_method
Hope that clears things up a little bit. Also refer to: http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Texture wrap mode repeat is not working I am using the Android mobile platform, with OpenGL ES 2.0.
When I make a texture like so, the textures in my scene draw correctly
//Generate there texture pointer
GLES20.glGenTextures(1, textureHandle, 0);
// parameters - we have to make sure we clamp the textures to the edges!!!
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S,GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T,GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER,GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_LINEAR);
However, I want to be able to scroll a texture, and I believe setting the wrap mode to GLES20.GL_REPEAT would make the needed calculation more possible. However, when using code such as below.
//Generate there texture pointer
GLES20.glGenTextures(1, textureHandle, 0);
// parameters - we have to make sure we clamp the textures to the edges!!!
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S,GLES20.GL_REPEAT);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T,GLES20.GL_REPEAT);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER,GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_LINEAR);
Every texture is black. The only difference I have made here is the setting of the GLES20.GL_REPEAT parameter name in the call to GLES20.glTexParameteri. This seems really odd. Does anyone have some ideas to share?
I appreciate any help.
Thanks.
A: Are the texture sizes powers of two (POT)? If not, there are some limitations on the wrap modes for NPOT textures; only GL_CLAMP_TO_EDGE is supported in that case, which is what you're seeing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to import and use another package I have my main project and I have created another on the side. The new one simply listens for a button click and then runs methods to update a users twitter status.
What I am unable to do at the moment is use this in my original project. I could copy the code into every .java file but that would be excessive.
What would be a better way to accomplish this and activate the onclick listener.
A: If the library is provided as a jar file, then place it in the /libs folder in your project.
If the library is itself an android project, read up on Android Library Projects
If the problem is simply "How do you import a package?", Read this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: capturing network packet in c This question might sound fool, because I know there are bunch of frameworks that does it for you. What I want is actually get in touch with low level C API deeply and able to write a program that sits on computer and intercepts packets between local machine and outer spaces. I tried to figure it out by looking at open source code (i.e. tcpdump) but it's quite difficult for me to find out which file actually performs network sniffing. Any suggestions would be appreciated !
A: You have to use raw socket. Here's an example.
At least for what concern Linux and Unix like operating systems. I don't know about Windows.
A: If you're using a UNIX based system[*] then the simplest mechanism is libpcap, which is part of the tcpdump project.
Your process will need root privileges to be able to access the network interface (as would also be the case with raw sockets).
Usually you'll end up having to decode ethernet frames, IP headers, etc yourself, although for most protocols this isn't that hard.
[*] It is actually available for Win32 as well, but I've not used it under Windows myself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: reloading url from an array in javascript I am working on the following code for a chrome extension. Basically I want it to check the page that initially loads and if it matches my website st.mywebsite.com it will execute the code. Right now it doesn't check and will execute any pages that loads. I am trying to get it to load http://st.mywebsite.com/?q= plus the terms in the array. So every X number of seconds/minutes it will load a new term in the array and add it to the url http://st.mywebsite.com/?q=can anyone help?
if((window.location.hostname != "st.mywebsite.com")){
window.onload = function() {
terms = new Array("5d65sd", "95sd4s", "h2j4g8h", "c87e2dd", "e6e5f2g4", "3m5g5gv");
min = 1;//minimum
max = 60;//maximum
randomnumber = Math.floor(Math.random() * (max - min + 1)) + min;
var seconds = randomnumber;
var timer;
function countdown() {
var container = document.getElementById('right');
seconds--;
if(seconds > 0) {
container.innerHTML = '<p>Please wait <b>'+seconds+'</b> seconds.</p>';
} else {
window.location = 'http://st.mywebsite.com/?q='+terms;
}
}
timer = setInterval(countdown, 1000);
}
}
A: At the line you have window.location, change it to window.location.href
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Copying an instance of a model and updating fields I'm trying to copy an instance of my Page model and set the new page's status to "draft." This code works perfectly in the Django shell, but in the admin action where it lives, a new instance is created but the status is not updated.
for page in pages:
page.pk, page.id = None, None
page.save()
page.status = Page.DRAFT
page.updated_at = datetime.now()
page.save(force_update=True)
So the above code creates a new page, but does not change its status.
I think it might have something to do with Page having proxy models depending on the status (PublishedPage, DraftPage, etc.) I'm not sure what the problem is, though.
A: Don't.
for page in pages:
new_page= Page.objects.create(
this= page.this, that=page.that, ...
status= Page.DRAFT )
Much simpler. Much clearer. And it actually works.
A: It turns out that the proxy models subclassing Page had custom save method overriding my updates.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can contents of a namespace be made available to an entire project without generating Multiply Defined Symbol errors? I am attempting to make a fairly large video game, and my current method of handling mouse input is to pass mouseX, mouseY, and an enum mouseState as arguments to the update function of EVERY single object that requires knowledge of the mouse. It's fairly messy, and I want to make the mouse variables more global by putting them in a namespace called Input so that I can access them with Input::mouseX, et al.
As it stands now, The namespace Input exists in Input.h (contents below)
#pragma once
#include "allegro5\allegro.h"
#include "J_Enum.h"
namespace Input{
ALLEGRO_EVENT_QUEUE *inputQueue;
int mouseX;
int mouseY;
MOUSE_STATE mouseState;
void setUpInput();
void updateInput();
};
and the two member functions are defined in Input.cpp
#include "Input.h"
void Input::setUpInput(){...declaration
void Input::updateInput(){...''
Upon including Input.h in the main loop object's header Core.h the linker throws a hissy fit because in its eyes everything included in Input.h is now a Multiply Defined Symbol.
Clearly something is wrong with my use of header files, because to my knowledge, I haven't made any glaring mistakes in my use of namespaces and the error code prefix of LNK2005 seems to implicate the linker(?).
If anyone can possibly shed some light on my dilemma I would be most grateful
A: Declare the variables as extern:
// header file:
namespace Input {
extern int mouseX;
}
// implementation
#include "input.h"
namespace Input {
int mouseX;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: missing lines while appending files I am new to both stackoverflow and python, so this might look obvious:
In this procedure I want to create a new file named database out of a list of files generated by a previous procedure. The files in the list are quite big (around 13.6 MB). The goal is to have a single file with lines from all other:
database = open('current_database', 'a')
def file_apender(new):
for line in new:
database.write(line)
def file_join(list_of_files):
for file in list_of_files:
file_apender(file)
Then if I:
file_join(a_file_list)
I get the database file, but 26 lines are missing and the last one is not complete.
Here is the ending of the file:
63052300774565. 12 4 3 0 0.37 0.79 10.89 12.00 1.21 25.26 0.00 0.00 0.00 0.00
63052300774565. 12 2 0 0 0.06 0.12 2.04 2.21 0.86 5.30 0.00 0.00 0.00 0.00
63052300774565. 12 0 0 0 0.12 0.26 3.13 4.63 3.81 11.95 0.00 0.00 0.00 0.00
63052300774565. 12 2 2 0 0.06 0.15 1.35 2.39 0.00 3.94 0.00 0.00 0.00 0.00
63052300774565. 12 0 1 0 0.06 0.08 1.13 1.29 3.60 6.16 0.00 0.00 0.00 0.00
63052300774565. 12 2 0 0 0.23 0.41 4.02 6.47 8.39 19.52 0.00 0.00 0.00 0.00
63052300774565. 12 1 3 0 0.05 0.16 1.85 2.50 0.57 5.13 0
I have tried to find out if there is a memory limitation... Otherwise I got no ideas.
A: I'm going to use my psychic debugging skills, and guess that you don't have a database.close().
If you don't close the file when writing to it, there may still be data in the Python output buffers that hasn't been written to the OS yet. If your program exits at that point, then the data is not written to disk and you will be missing data at the end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JavaScript RegExp help for BBCode I have this RegExp expression I found couple weeks ago
/([\r\n])|(?:\[([a-z\*]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])|(?:\[\/([a-z]{1,16})\])/ig
And it's working to find the BBCode tags such as [url] and [code].
However if I try [url="http://www.google.com"] it won't match. I'm not very good at RegExp and I can't figure out how to still be valid but the ="http://www.google.com" be optional.
This also fails for [color="red"] but figure it is the same issue the url tag is having.
A: This part: [^\x00-\x1F"'\(\)<>\[\]] says that after the =there must not be a ". That means your regexp matches [url=http://stackoverflow.com]. If you want to have quotes you can simply put them around your capturing group:
/([\r\n])|(?:\[([a-z\*]{1,16})(?:="([^\x00-\x1F"'\(\)<>\[\]]{1,256})")?\])|(?:\[\/([a-z]{1,16})\])/gi
A: I think you would benefit from explicitly enumerating all the tags you want to match, since it should allow matching the closing tag more specifically.
Here's a sample code:
var tags = [ 'url', 'code', 'b' ]; // add more tags
var regParts = tags.map(function (tag) {
return '(\\[' + tag + '(?:="[^"]*")?\\](?=.*?\\[\\/' + tag + '\\]))';
});
var re = new RegExp(regParts.join('|'), 'g');
You might notice that the regular expression is composed from a set of smaller ones, each representing a single tag with a possible attribute ((?:="[^"]*")?, see explanation below) of variable length, like [url="google.com"], and separated with the alternation operator |.
(="[^"]*")? means an = symbol, then a double quote, followed by any symbol other than double quote ([^"]) in any quantity, i.e. 0 or more, (*), followed by a closing quote. The final ? means that the whole group may not be present at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Question regarding main activity and custom view I am working on an online handwriting recognition tool . I have a custom view which i am adding to linear layout . how can i get the coordinates in custom view and transfer them to main activity file for storing them in linked lists or array lists
A: You could override the method OnTouchEvent on your View.
public boolean onTouchEvent(MotionEvent event) {
float x=event.getX();
float y=event.getY();
}
And then if you want, you could construct a Array or a List.
ArrayList<Point> myList;
...
//Constructor
...
...
public boolean onTouchEvent(MotionEvent event) {
float x=event.getX();
float y=event.getY();
Point p =new Point();
p.set(x, y);
//And then add to the list
myList.add(p);
}
public ArrayList<Point> getMyArray(){
return myList;
}
And for call the method getMyArray of your custom view. You could use this code on your main activity
myView mv = (myView)this.findViewById(R.id.myView1);
ArrayList<Point> points = mv.getMyArray();
That's a possible solution for your problem but I don't know if it helps you.
Edit: This solution works for all customs View but, if I were you, I would use a View that extends SurfaceView. It's logical because , I think, it's the best way to create graphics in a handwriting tool.
A: You need create a custom class that implements the OnTouchListener interface and set it to listen to touch events on your custom view. Its very similar to adding an OnClickListener to a button:
MyView view = (MyView) findViewById(R.id.myView);
view.setOnTouchListener(new MyOnTouchListener());
Where MyOnTouchListener looks something like this:
class MyOnTouchListener implement OnTouchListener{
public int x=-1,y=-1,prevX=-1, prevY=-1;
public boolean onTouch(View v, MotionEvent event)
{
prevX = x;
prevY = y;
int x = (int)event.getX();
int y = (int)event.getY();
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
// there is no prev touch
prevX = -1;
prevY = -1;
// touch down code
break;
case MotionEvent.ACTION_MOVE:
// touch move code
// add points to array here!
break;
case MotionEvent.ACTION_UP:
// touch up code
break;
}
return true;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Converting datetime to different timezones with javascript Im using the InstantAnswer source of the Bing API to retrieve flight status information in JSON format via jQuery.getJSON. This is an example of what im receiving:
if(typeof SearchCompleted == 'function') SearchCompleted({"SearchResponse":{"Version":"2.2","Query":{"SearchTerms":"LA1442"},"InstantAnswer":{
"Results":[{"ContentType":"FlightStatus","Title":"flight status for Lan Airlines 1442","ClickThroughUrl":"http:\/\/www.bing.com\/search?mkt=en-US&q=LA1442&form=SOAPGN","Url":"http:\/\/www.flightstats.com\/go\/FlightStatus\/flightStatusByFlight.do?id=239598315","InstantAnswerSpecificData":{"FlightStatus":{"AirlineCode":"LA","AirlineName":"Lan Airlines","FlightNumber":"1442","FlightName":"LA1442","FlightHistoryId":239598315,"StatusString":"Landed","StatusCode":76,"OnTimeString":"","ScheduledDeparture":"2011-09-22T17:25:00Z","UpdatedDeparture":"2011-09-22T17:15:00Z","ScheduledArrival":"2011-09-22T18:20:00Z","UpdatedArrival":"2011-09-22T18:17:00Z","OriginAirport":{"Code":"GYE","Name":"Guayaquil","TimeZoneOffset":-18000},"DestinationAirport":{"Code":"UIO","Name":"Quito","TimeZoneOffset":-18000},"DepartureGate":"","DepartureTerminal":"","ArrivalGate":"","ArrivalTerminal":"","PreviousSegment":{"FlightHistoryId":239598314,"OriginAirport":"EZE","DestinationAirport":"GYE"},"DataFreshness":1}}}]}}} /*
The information im having trouble with (timezone related) is this:
*
*Scheduled Departure: 2011-09-22T17:25:00Z
*Scheduled Arrival: 2011-09-22T18:20:00Z
Here is the problem: If the flight has already departed, i need to make a projection of which percentage of the flight path has been already travelled.
That would be easy to calculate IF both the Scheduled Departure and Scheduled Arrival fields would be in the same timezone as the computers current timezone (im using a clientside script only) -- but they are not. One of them is using the timezone in Ecuador (GMT -5) and the other is using the timezone in Chile (GMT -4).
My idea is:
*
*convert both values to unix timestamps
*convert both timestamps to the current computer's timezone
*calculate plane's travelled percentage with those 2 timestamps and my computer's current timestamp
The step im having trouble is No. 2 - Any ideas? Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Zend PDO_MYSQL error in application.ini file When in configure my website which is working on zend to mysql in application.ini
resources.db.adapter = PDO_MYSQL
resources.db.isDefaultAdapter = true
resources.db.params.host = 67.227.236.194
resources.db.params.username = rdvscoin_rdvs
resources.db.params.password = P@ssw0rd
resources.db.params.dbname = rdvscoin_rdvs
after this when i run my page than Exception comes....
Message: SQLSTATE[28000] [1045] Access denied for user 'rdvscoin_rdvs'@'host.indiandns.com' (using password: YES)
but above given information is correct.
A: have you bootstrap the resource db?
function _initRegDataBase(){
$this->bootstrap('db');
$ResourceDb = $this->getResource('db');
$ResourceDb->setFetchMode(Zend_Db::FETCH_OBJ);
}
A: replace
resources.db.params.host = 67.227.236.194
with
resources.db.params.host = "host.indiandns.com"
Also remember this code will work on the server not on your computer because by default mysql remote access permission is denied . Secondly I think you are on share host which never gives IP address for free . So you got to use there name host instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spring MVC & UI Components I'm in the "technologies selection" phase of a small, single-page web application that will be heavily-based in AJAX, and which will report to a Java backend.
In a previous question I posted several weeks ago, the SO community at large felt strongly that I would be better off going with a Spring MVC-based web app than with something in JSF. Since Spring is request-oriented, and JSF is component-oriented, it would only make sense to use Spring for something that is going to be getting a lot of asynchronous requests.
If I were going the JSF route, then my next set of decisions would be whether or not to use so-called UI component libraries for the view technology, such as PrimeFaces, IceFaces or MyFaces.
So, I'm wondering: Does Spring MVC have anything similar to, say, PrimeFaces (or its likes) for creating the view component for my page(s)? I know its not component-based, but I'm not all that familiar with Spring MVC's web platform and was wondering what are some de facto standards (if any) or typical technology stacks that Spring web developers use for constructing nice web pages.
And, if Spring just uses run-o-the-mill template engines, would something like Freemarker suffice?
I guess this is a "best practices"-type question for a budding Spring web developer.
Thanks in advance!
A: Yes, JSF is component oriented and Spring MVC is request oriented.
I recommend you to have a look at Thymeleaf Template engine, which is a complete replacement for JSP Engine
....
Thymeleaf Features are:
*
*It allows natural templating.
*HTML5 support
*Higher performance by utilizing in memory caching
Click here for more
A: Typically, the value so-called UI components lies in how they keep track of user interactions on the server side by integrating with a stateful framework.
Since you have decided to go for a request oriented framework, it would make more sense to use some well-known client-side JavaScript libraries instead. Popular choices include:
*
*Backbone.js – an MVC foundation for user interfaces
*jQuery UI for some premade widgets (calendars, etc.)
*If you want to go down a more complex route, but with a more desktop-like feel, Sproutcore
*Finally, if you wish to avoid JavaScript, you can useGoogle Web Toolkit, which compiles Java to JavaScript and is supposed to have good integration with Spring.
Personally, if I don't need a lot of standard prebuilt widgets, I like Backbone.js + underscore.js + jQuery. I don't like Google Web Toolkit since it feels like writing a pidgin JavaScript, and at that point I prefer to write JavaScript directly.
A: Additionally apart from the things mentioned by Ludovico Fischer, if we consider the same question in now a days tech world than you can use one of the most power full thing of recent world : Angular. There are 2 sample scenario's.
*
*If your architecture is full client side: The integration is very natural for it. Spring MVC expose your service as a REST (JSON / XMl ... ) and your client application with Angular JS consume your JSON. Here the war application (Spring mvc ) must be deployed in a Servlet Container (Tomcat) and your client application can be deployed in the same server or in another server Nginx , Apache etc..
*If you want to keep page generation in the server side and only use AngularJS for some nice DOM manipulation so your code must be deployed in the same war (WEB-INF). Mixing the two approachs is not always a good idea. You can try thymeleaf to stay in server side page generation.
Thus in this way you can have simultaneously the cool featuresof angular like templating, testability and clean view code.
A: Here is another approach (Not JSF) to let Spring MVC to work with ZK UI components - Rich Web Application with Spring MVC CRUD Demo
In that article, it used Spring MVC controller to communicate with ZK UI components. (all in Java code)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: Storing custom MySQL MetaData - best practices I have a fairly large database containing a number of different tables representing different product types (eg. cars; baby strollers).
I'm using a website built with PHP to access the data and display it, and I allow users to filter the data (typical online product database sort of stuff).
I'm not sure if I went about storing my metadata the correct way. I'm using XML to do a lot of stuff, which requires making a product type table in MySQL first, and then adding information about each of the columns in that table in my big XML "column attribute" file. So I'll have the name of each column listed in the XML table with information about the column. I store localized names for the column in the XML file, and indicate what type of information about the product is being stored in the column (e.g. Is a column showing a dimension (to be listed in the product dimensions area) or a feature (for the features area)).
First off, am I way off base storing all this custom metadata in XML?
Secondly, if I should be storing some of it in MySQL (and I think I should be moving some of it there), what's the best way to do that? I see that I can make column "comments" in MySQL....are those standard fare for databases? If I move to Oracle some day, would I lose all my comment info? I'm not thinking of moving much information to the database, and some of it could be accomplished by just adding a little identifier to my column names (e.g. number_of_wheels becomes number_of_wheels_quantity, length becomes length_dimension)
Any advice from the database design gurus out there would be vastly appreciated. Thanks :)
A:
First off, am I way off base storing all this custom metadata in XML?
Yes, XML is a great markup for transporting data in a nearly human readable format, but a horrible one for storing it. It's very costly to search through XML, and I don't know of a (good) way to have a query search through XML stored in a field in the DB. You are probably better off with a table that stores these things directly, you can easily convert them into XML if you need to, after you query them from the DB. I think in your case a table with the following columns would be useful: "ColumnName","MetaData" Would be all you need, populate with values as per your example:
__________________________________________________________________________________________________
|colDimension | Is a column showing a dimension (to be listed in the product dimensions area) |
|colFeature | a feature (for the features area) |
--------------------------------------------------------------------------------------------------
This scheme will resolve your comments conundrum as well, as you can add another field to the above table to store the comments in, which will make them much more accessible to your middle tier (php in your case) if you ever want to display those comments.
I had to make a few assumptions as to intent and existing data and whatnot, so if I'm wrong about anything, let me know why it doesn't work for you and I'll respond with some corrections or other pointers.
A: See, your purpose is to keep the Meta data at a place. right?
I'll suggest you to use the freely available tool Mysql Workbench. In this tool you have option to create ER diagram (or EER diagram). You can keep the whole structure and at any point of time you can sync with server and restore the structure. You can backup those structures also. Its kind of you have to learn first if you are not already using it. But at last its a very helpful tool for keeping the structure in an organized way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "Live" get(x) and get(Y) values (for MotionEvents) ****UPDATE**** I was wondering how to get accurate, live get(x) and get(y) values for a MotionEvent? What is happening is that when I touch a specific area on the screen, I tell an action to happen.
The problem is that once I touch the screen and take my finger off, it still thinks my finger is at the same location (since that was the last location I touched). So when I have more than one Down event (for multitouch) it throws everything off. Is there a way to reset the X and Y values so when I let off the screen, they go back to 0 or null (or whatever)? Thanks
A: What you are describing isn't a problem. You the programmer are responsible for keeping track of the touch locations and what they mean. If you care about motion you need to keep track of the previous touch and the current touch each time a touch occurs. I find something like this works great:
public int x=-1,y=-1,prevX=-1, prevY=-1;
public boolean onTouch(View v, MotionEvent event)
{
prevX = x;
prevY = y;
int x = (int)event.getX();
int y = (int)event.getY();
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
// there is no prev touch
prevX = -1;
prevY = -1;
// touch down code
break;
case MotionEvent.ACTION_MOVE:
// touch move code
break;
case MotionEvent.ACTION_UP:
// touch up code
break;
}
return true;
}
A: Just catch the MotionEvent.ACTION_UP or ACTION_MOVE event, depending on when the action needs to happen (since you want it live, you should use the ACTION_MOVE event). You should handle setting external variables when ACTION_DOWN occurs, and handle the results on ACTION_MOVE or ACTION_UP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error deploying signed jar+jad to a blackberry 9300 curve 5.0 My setup is Eclipse, BB JRE 5.0, Blackberry application (not MIDlet). It works ok debugging it from eclipse on the aforementioned device. However, packaging it (firstly signs the cod files and then) produces some files which are manually copied under a folder from the phone file system. Then, from he phone, navigating to them and clicking:
myapp.jar: error message: 907 invalid jar descriptor missing required attribute Midlet-1
myapp.jad: No additional application can be found. Your file might contain applications that already exist in the application list, are not compatible for you device, or have errors.
The jad and jar files look ok at a first glance, although reference to MIDlet attributes can be found in the .jad file. Is this the standard deployment mechanism for BB apps ? through .jad files coming from MIDP 1.0 ? How can I debug this further ?
A: I am not familiar with the 'copy files to the phone filesystem' install method. Have you tried using javaloader.exe?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: file upload to the wrong directory I try to use the copy() function in php to store two same files in the sever at one time, I have specified the directory for the copied file, but it doesn't go to the directory I specified which is "edituploads" folder, instead it goes to the current directory which the upload php scrpit is located. and I have used the copy() function three times , is that a problem?
Any one could tell me what's wrong, thanks alot.
here is my php code:
if (!empty($_FILES))
{
$a = uniqid();
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetpath4=$_SERVER['DOCUMENT_ROOT']."/example/upload/edituploads/";
$targetFile = str_replace('//','/',$targetPath) . $a.".jpg";
$targetFile4 = str_replace('//','/',$targetPath4) . $a.".jpg";
move_uploaded_file($tempFile,$targetFile);
copy($targetFile, $targetFile4);
}
A: php's copy/move commands work purely on a filename basis. You can't specify a directory as a source or a target, because they don't operate in directories. It's not like a shell where you can do
$ cp sourcefile /some/destination/directory/
and the system will happily create 'sourcefile' in that directory for you. You have to specify a filename for the target, e.g.:
$ cp sourcefile /some/destination/directory/sourcefile
Beyond that, your move command is usign$targetPath, which your code snippet doesn't define, so it's going to just create a $a.jpg filename in the current working directory.
And your copy() command is using $targetFile4, which is based off targetPath3, which is also not defined anywhere.
A: You need to copy the file first, then move over the TMP to the other directory.
copy($tempFile,'somePlace_1');
move_uploaded_file($tempFile, 'somePlace_2');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding a drop down in itemtemplate and populating value dynamically I have an item template in a GridView and I want to create a dropdown for each row and bind it to a value retrieved from the database.. but I am not sure how to do this.. this is what i have so far.. but not sure where to put the code to populate the drop down per row..
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlMyQuantity" SelectedValue='<%#
(DataBinder.Eval(Container.DataItem,"Quantity")) %>'>
</asp:DropDownList>
</ItemTemplate>
and in code behind, not sure how to or where to put this so that it is created on every row..
public void BindMyQuantity()
{
for (int i = 1; i < 15; i++)
{
ddlMyQuantity.Items.Add(i.ToString());
}
}
Also i am not sure if i can do that, but the code is not complaining.. adding SelectedValue in the asp declaration
A: You can use OnRowDataBound to dynamically bind your dropdown:
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var dropdownList = (DropDownList)e.Row.FindControl("ddlMyQuantity");
for (int i = 1; i < 15; i++)
{
dropdownList.Items.Add(i.ToString());
}
dropdownList.SelectedValue =
Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Quantity"));
}
}
Add binding:
<asp:GridView ... OnRowDataBound="GridView_RowDataBound">
...
</asp:GridView>
A: As per my knowledge, the best option would be to write this code in "RowDataBound" event of the Grid. See sample code below.
protected void GridView_RowDataBound(..)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
DropDownList ddl = e.Row.FindControl("ddlMyQuantity") as DropDownList;
if (ddl != null)
{
for (int i = 1; i < 15; i++)
{
ddl.Items.Add(i.ToString());
}
}
}
}
In the aspx page, provide this
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlMyQuantity"></asp:DropDownList>
</ItemTemplate>
Hope this Helps!!
A: <asp:TemplateField HeaderText="Type Cargo" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataValueField="DESCRIPTION"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Code Behind will look like this...
Dim rowId As DropDownList
For i As Integer = 0 To gridView1.Rows.Count - 1
Dim gridrow As GridViewRow = gridView1.Rows(i)
rowId = DirectCast(gridrow.FindControl("DropDownList1"), DropDownList)
Dim dt As DataTable = Get_List()
rowId.DataSource = dt
rowId.DataBind()
Next
Get_List is a Function that returns a DataTable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Helper Gem for Rest on Rails 3 I know that Rails has some tools on board to create a REST API. However, concepts like HATEOS aren't supported out of the box.
I googled around for Gems that are filling the gap. The most complete Gem I found is Restfulie (https://github.com/caelum/restfulie). But I am not complete convinced about Restfulie and the project looks abandoned. Hence, I am looking for good alternatives to Restfulie.
What's the best Gem to create a REST API for Rails?
A: Popular choices are RABL and Roar / roar-rails.
I personally like Roar better because it allows you to consume your representations which is a bit harder with RABL. On the other hand, it's concepts are still in flux so things still tend to change.
A: Grape is worth a try.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Site is calling same file multiple times but doesn't show in code? I am honestly not sure where the issue lays but here is my problem:
I have a single file: card.gif. When I check firebug or Google pagespeed, I learn the file is called twice during the page fetch once as normal file name and a second time with a random number (that does not change). Example:
*
*card.gif
*card.gif?1316720450953
I have scoured my actual source code, the image is only called once. It is not called in a CSS file. To be honest I have no idea what is the issue, some thought that when I originally installed mod_pagespeed that it appended ID's to each image in cache for any future overwrites but I can't be certain.
Has anybody ever had this issue before?
A: In the end - Dagon's comments above led me to believe that things like Firebug and Pagespeed may not always be correct. I do show two images being loaded in the timelines for both plugins but it is very difficult for me to decifer otherwise. If another answer is provided contradicting this, I am more than happy to test that theory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Node.js + Express without using Jade Is it possible to use express without any template engine?
A: For anyone having the need to immediately use regular HTML without jade in a new express project, you can do this.
Add a index.html to the views folder.
In app.js change
app.get('/', routes.index);
to
app.get('/', function(req, res) {
res.sendfile("views/index.html");
});
UPDATE
Use this instead. See comment section below for explanation.
app.get('/', function(req, res) {
res.sendFile(__dirname + "/views/index.html");
});
A: Yes,
app.get('/', function(req, res){
res.render('index.html');
});
should just work
A: You can serve static files automatically with Express like this:
// define static files somewhere on top
app.use(express['static'](__dirname + '/your_subdir_with_html_files'));
Actually this should be express.static(...) but to pass JSLint above version works too ;)
Then you start the server and listen e.g. on port 1337:
// app listens on this port
app.listen(1337);
Express now serves static files in /your_subdir_with_html_files automatically like this:
http://localhost:1337/index.html
http://localhost:1337/otherpage.html
A: This is all out of date - correct answer for 3x, 4x is
The second answer here:
Render basic HTML view?
A: UPDATED
Some might have concerns that sendFile only provides client side caching. There are various ways to have server side caching and keeping inline with the OP's question one can send back just text too with send:
res.send(cache.get(key));
Below was the original answer from 3+ years ago:
For anyone looking for an alternative answer to PavingWays, one can also do:
app.get('/', function(req, res) {
res.sendFile('path/to/index.html');
});
With no need to write:
app.use(express['static'](__dirname + '/public'));
A: In your main file:
app.get('/', function(req, res){
res.render('index');
});
Your index.jade file should only contain:
include index.html
where index.html is the raw HTML you made.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: Call an Objective-C function non-virtually Is it possible to force Objective-C to call a specific instance of a virtual method, rather than going through the standard virtual message dispatch? I know this is generally a Bad Idea, but I'd like to know how to do it using the Objective-C runtime.
For example, given class A and B that implement -(void) foo, where B is a subclass of A, I'd like to call the foo method on A with the B instance (even though B would normally handle this message).
I know that I can make this happen by moving the guts of A's foo method to a new method and delegating to it, but I'd like to figure out some way to do this through the Objective-C runtime.
NOTE: For the purposes of this question, assume that I can't change the source of A or B and I've carefully weighed the risks of breaking encapsulation.
A: This page is a great source for understanding the runtime; a quick memory-assisted scan shows that the section titled "So what happens in objc_msgSend anyway?" is a good place to start for an immediate answer, but the article as a whole will really help you understand what goes on.
Here's an example where he queries the runtime for the appropriate function pointer, then calls the function directly:
//declare C function pointer
int (computeNum *)(id,SEL,int);
//methodForSelector is COCOA & not ObjC Runtime
//gets the same function pointer objc_msgSend gets
computeNum = (int (*)(id,SEL,int))[target methodForSelector:@selector(doComputeWithNum:)];
//execute the C function pointer returned by the runtime
computeNum(obj,@selector(doComputeWithNum:),aNum);
A: What Matthias said... however:
For example, given class A and B that implement -(void) foo, where B
is a subclass of A, I'd like to call the foo method on A with the B
instance (even though B would normally handle this message).
In other words, you have an implementation of foo on B that you want to avoid by calling a's implementation directly?
Obviously, if you are the implementer of B, then this is trivial; just implement the appropriate logic to determine when it is needed and call [super foo];.
If you are not the implementer of B, then this is beyond a bad idea. It is pretty much guaranteed to lead to mystery crashers and/or misbehavior. Worse, if B is actually a part of a system framework or something that may be updated via a mechanism other than your app being updated, then you have a ticking time bomb that may start crashing your app at any time on any random configuration of the OS.
Specifically:
*
*B's foo may not be self contained; it may do stuff before/after calling A's foo that sets up internal state that may later be required for continued correct operation. You are breaking encapsulation with a sledgehammer.
*calling the implementation directly is going to bypass any KVO in play. Unless you happen to grab a derived method implementation, at which point, your behavior is going to explode when that derived method should no longer be in play.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: shell script wget not working when used as a cron job i have a function in a php web app that needs to get periodically called by a cron job. originally i just did a simple wget to the url to call the function and everything worked fine, but ever since we added user auth i am having trouble getting it to work.
if i manually execute these commands i can login, get the cookie and then access the correct url:
site=http://some.site/login/in/here
cookie=`wget --post-data 'username=testuser&password=testpassword' $site -q -S -O /dev/null 2>&1 | awk '/Set-Cookie/{print $2}' | awk 'NR==2{print}'`
wget -O /dev/null --header="Cookie: $cookie" http://some.site/call/this/function
but when executed as a script, either manually or through cron, it doesn't work.
i am new to shell scripting, any help would be appreciated
this is being run on ubuntu server 10.04
A: In theory, the only difference from manually executing these and using a script would be the timing.
Try inserting a sleep 5 or so before the last command. Maybe the http server does some internal communication and that takes a while. Hard to say, because you didn't post the error you get.
A: OK simple things first -
*
*I assume the file begins with #!/bin/bash or something
*You have chmodded the file +x
*You're using unix 0x0d line endings
And you're not expecting to return any of the variables to the calling shell, I presume?
Failing this try teeing the output of each command to a log file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery .css() property simply not functioning (no error)? As part of an upvote/downvote system (like on stackoverflow or Reddit) I'm using jQueries .css() property to change the background-position when an upvote or downvote arrow is clicked:
jQuery code:
$(document).ready(function() {
$('#vpUp').click(function() {
$('.vpVote').css('background-position','28 0;');
var pId=1;
vpVoteF(pId,1);
});
$('#vpDown').click(function() {
$('.vpVote').css('background-position', '56 0;');
var pId=1;
vpVoteF(pId,-1);
});
});
HTML:
<div class="vpVote">
<div class="vpUD" id="vpUp"></div>
<div class="vpUD" id="vpDown"><span id="vpVoteText"><?php echo $Votes; ?></span></div>
</div>
The background-position would change the background image to the upvote being highlighted or the downvote highlighted. However, the code doesn't seem to run at all. When I place an alert in either function it alerts when I click #vpUp or #vpDown, but they don't change the background position and in Chrome and Firefox with firebug open there are no errors.
I am completely at a loss.
Note: You can see a live demo of the voting (not) in action here: http://www.texturepacker.net/viewPacks2.php
A: Specify UNITS (px) with your position.
A: $(document).ready(function() {
$('#vpUp').click(function() {
$('.vpVote').css('background-position','28px 0px');
var pId=1;
vpVoteF(pId,1);
});
$('#vpDown').click(function() {
$('.vpVote').css('background-position', '56px 0px');
var pId=1;
vpVoteF(pId,-1);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Query to merge continuous temporal records I have a table like this:
id START_DATE end_date
1 01/01/2011 01/10/2011
2 01/11/2011 01/20/2011
3 01/25/2011 02/01/2011
4 02/10/2011 02/15/2011
5 02/16/2011 02/27/2011
I want to merge the records where the start_date is just next day of end_date of another record: So the end record should be something like this:
new_id START_DATE end_date
1 01/01/2011 01/20/2011
2 01/25/2011 02/01/2011
3 02/10/2011 02/27/2011
One way that I know to do this will be to create a row based temp table with various rows as dates (each record for one date, between the total range of days) and thus making the table flat.
But there has to be a cleaner way to do this in a single query... e.g. something using row_num?
Thanks guys.
A: Try This
Declare @chgRecs Table
(updId int primary key not null,
delId int not null,
endt datetime not null)
While Exists (Select * from Table a
Where Exists
(Select * from table
Where start_date =
DateAdd(day, 1, a.End_Date)))
Begin
Insert @chgRecs (updId, delId , endt)
Select a.id, b.id, b.End_Date,
From table a
Where Exists
(Select * from table
Where start_date =
DateAdd(day, 1, a.End_Date)))
And Not Exists
(Select * from table
Where end_Date =
DateAdd(day, -1, a.Start_Date)))
Delete table Where id In (Select delId from @chgRecs )
Update table set
End_Date = u.endt
From table t join @chgRecs u
On u.updId = t.Id
Delete @delRecs
End
A: No, was not looking for a loop...
I guess this is a good solution:
taking all the data in a #temp table
SELECT * FROM #temp
SELECT t2.start_date , t1.end_date FROM #temp t1 JOIN #temp t2 ON t1.start_date = DATEADD(DAY,1,t2.end_date)
UNION
SELECT START_DATE,end_date FROM #temp WHERE start_date NOT IN (SELECT t2.START_DATE FROM #temp t1 JOIN #temp t2 ON t1.start_date = DATEADD(DAY,1,t2.end_date))
AND end_date NOT IN (SELECT t1.end_Date FROM #temp t1 JOIN #temp t2 ON t1.start_date = DATEADD(DAY,1,t2.end_date))
DROP TABLE #temp
Please let me know if there is anything better than this.
Thanks guys.
A: declare @T table
(
id int,
start_date datetime,
end_date datetime
)
insert into @T values
(1, '01/01/2011', '01/10/2011'),
(2, '01/11/2011', '01/20/2011'),
(3, '01/25/2011', '02/01/2011'),
(4, '02/10/2011', '02/15/2011'),
(5, '02/16/2011', '02/27/2011')
select row_number() over(order by min(dt)) as new_id,
min(dt) as start_date,
max(dt) as end_date
from (
select dateadd(day, N.Number, start_date) as dt,
dateadd(day, N.Number - row_number() over(order by dateadd(day, N.Number, start_date)), start_date) as grp
from @T
inner join master..spt_values as N
on N.number between 0 and datediff(day, start_date, end_date) and
N.type = 'P'
) as T
group by grp
order by new_id
You can use a numbers table instead of using master..spt_values.
A: A recursive solution:
CREATE TABLE TestData
(
Id INT PRIMARY KEY,
StartDate DATETIME NOT NULL,
EndDate DATETIME NOT NULL
);
SET DATEFORMAT MDY;
INSERT TestData
SELECT 1, '01/01/2011', '01/10/2011'
UNION ALL
SELECT 2, '01/11/2011', '01/20/2011'
UNION ALL
SELECT 3, '01/25/2011', '02/01/2011'
UNION ALL
SELECT 4, '02/10/2011', '02/15/2011'
UNION ALL
SELECT 5, '02/16/2011', '02/27/2011'
UNION ALL
SELECT 6, '02/28/2011', '03/06/2011'
UNION ALL
SELECT 7, '02/28/2011', '03/03/2011'
UNION ALL
SELECT 8, '03/10/2011', '03/18/2011'
UNION ALL
SELECT 9, '03/19/2011', '03/25/2011';
WITH RecursiveCTE
AS
(
SELECT t.Id, t.StartDate, t.EndDate
,1 AS GroupID
FROM TestData t
WHERE t.Id=1
UNION ALL
SELECT crt.Id, crt.StartDate, crt.EndDate
,CASE WHEN DATEDIFF(DAY,prev.EndDate,crt.StartDate)=1 THEN prev.GroupID ELSE prev.GroupID+1 END
FROM TestData crt
JOIN RecursiveCTE prev ON crt.Id-1=prev.Id
--WHERE crt.Id > 1
)
SELECT cte.GroupID, MIN(cte.StartDate) AS StartDate, MAX(cte.EndDate) AS EndDate
FROM RecursiveCTE cte
GROUP BY cte.GroupID
ORDER BY cte.GroupID;
DROP TABLE TestData;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to use XPath 2.0 Methods in .NET 4.0? I am using .NET 4.0 and I would like to use XPath 2.0 methods such as ([Matches()][1], [upper-case()][2], [lower-case()][3]) when trying to find elements in a document.
Example XPath: "/MyDocument/MyNode[matches(@MyAttribute, 'MyValue', 'i')]"
I have tried using:
*
*System.Xml.XPath.XPathNavigator.Compile()
*System.Xml.XmlDocument.SelectNodes()
*System.Xml.Linq.XDocument.SelectElements()
But I basically throw the exception "UndefinedXsltContextException" (or something similar). Can this be done in .NET 4.0 and if so can you provide a small example on how to set it up to work?
Thanks
A: .NET doesn't currently support XPath 2.0. See this question for more details and third-party alternatives: XPath and XSLT 2.0 for .NET?
If you don't want to use third-party libraries you could do the minimum required query to get your target element(s) with either XPath 1.0 or LINQ to XML, then do additional work on the data using .NET methods to perform the checks and modifications desired:
*
*Matches = Regex.IsMatch - be aware that the XPath regular expression pattern might have different metacharacters than the .NET pattern, so some translation might be needed.
*upper-case = String.ToUpper - the link mentions culture/invariant options too, in case you need them
*lower-case = String.ToLower
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: comboBox selected value change I'd like to give the customer an option to choose a city from COMBOBOX, and once the city's chosen, a list of that city's streets should be in COMBOBOX2. I tried the following code and I got an error, during the first run, maybe someone can explain this to me?
private void Search_by_Apartment_Load(object sender, EventArgs e)
{
List<Cities> city = DAL.cities();
cmBxCity.DataSource = city;//Here he ran the second function, why?
cmBxCity.DisplayMember = "city";
cmBxCity.ValueMember = "cityID";
}
private void cmBxCity_SelectedIndexChanged(object sender, EventArgs e)
{
List<Streets> street = DAL.streets(Convert.ToInt32(cmBxCity.SelectedText));
// List<Streets> street = DAL.streets(Convert.ToInt32(cmBxCity.SelectedValue));
comBxStreet.DataSource = street;
comBxStreet.DisplayMember = "street";
//cmBxCity.ValueMember = "cityID";
}
A: when you assign the DataSource of the cmBxCity control its selectedItem changes from nothing to one item and this triggers the event handler cmBxCity_SelectedIndexChanged.
in the question you are talking about COMBOBOX and COMBOBOX2 but in the code there is only one control which is: cmBxCity.
shouldn't you show the streets in the second control called: cmBxStreet ?
A: The SelectedIndexChanged event is fired whenever the selected index is changed programatically or by the user.
As Davide Pirsa points out, when you change the DataSource of cmBxCity, you are programatically changing the selected index, hence firing the 'cmBxCity.SelectedIndexChanged' event at this line:
cmBxCity.DataSource = city;//Here he ran the second function, why?
One possible solution is to use the SelectionChangeCommitted event instead, which is only fired for changes made by the user.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Confusion with pointers I am trying to learn C. The reading I've been doing explains pointers as such:
/* declare */
int *i;
/* assign */
i = &something;
/* or assign like this */
*i = 5;
Which I understand to mean i = the address of the thing stored in something
Or
Put 5, or an internal representation of 5, into the address that *i points to.
However in practice I am seeing:
i = 5;
Should that not cause a mismatch of types?
Edit: Semi-colons. Ruby habits..
A: Well, yes, in your example setting an int pointer to 5 is a mismatch of types, but this is C, so there's nothing stopping you. This will probably cause faults. Some real hackery could be expecting some relevant data at the absolute address of 5, but you should never do that.
The English equivalents:
i = &something
Assign i equal to the address of something
*i =5
Assign what i is pointing to, to 5.
A: If you set i = 5 as you wrote in your question, i would contain the address 0x00000005, which probably points to garbage.
Hope this helps explain things:
int *i; /* declare 'i' as a pointer to an integer */
int something; /* declare an integer, and set it to 42 */
something = 42;
i = &something; /* now this contains the address of 'something' */
*i = 5; /* change the value, of the int that 'i' points to, to 5 */
/* Oh, and 'something' now contains 5 rather than 42 */
A: If you're seeing something along the lines of
int *i;
...
i = 5;
then somebody is attempting to assign the address 0x00000005 to i. This is allowed, although somewhat dangerous (N1256):
6.3.2.3 Pointers
...
3 An integer constant expression with the value 0, or such an expression cast to type
void *, is called a null pointer constant.55) If a null pointer constant is converted to a
pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
...
5 An integer may be converted to any pointer type. Except as previously specified, the
result is implementation-defined, might not be correctly aligned, might not point to an
entity of the referenced type, and might be a trap representation.56)
...
55) The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant; see 7.17.
56) The mapping functions for converting a pointer to an integer or an integer to a pointer are intended to be consistent with the addressing structure of the execution environment.
Depending on the architecture and environment you're working in, 0x00000005 may not be a valid integer address (most architectures I'm familiar with require multibyte types to start with even addresses) and such a low address may not be directly accessible by your code (I don't do embedded work, so take that with a grain of salt).
A:
I understand to mean i = the address of the thing stored in something
Actually i contains an address, which SHOULD be the address of a variable containing an int.
I said should because you can't be sure of that in C:
char x;
int *i;
i = (int *)&x;
if i is a pointer, than assign to it something different to a valid address accessible from you program, is an error an I think could lead to undefined behavior:
int *i;
i = 5;
*i; //undefined behavior..probably segfault
here's some examples:
int var;
int *ptr_to_var;
var = 5;
ptr_to_var = var;
printf("var %d ptr_to_var %d\n", var, *ptr_to_var); //both print 5
printf("value of ptr_to_var %p must be equal to pointed variable var %p \n" , ptr_to_var, &var);
A: I hope this helps.
This declares a variable name "myIntPointer" which has type "pointer to an int".
int *myIntPointer;
This takes the address of an int variable named "blammy" and stores it in the int pointer named "myIntPointer".
int blammy;
int *myIntPointer;
myIntPointer = &blammy;
This takes an integer value 5 and stores it in the space in memory that is addressed by the int variable named "blammy" by assigning the value through an int pointer named "myIntPointer".
int blammy;
int *myIntPointer;
myIntPointer = &blammy;
*myIntPointer = 5;
This sets the int pointer named "myIntPointer" to point to memory address 5.
int *myIntPointer;
myIntPointer = 5;
A: assignment of hard-coded addresses, is something that shouldn't be done (even in the embedded world, however there are some cases where it's suitable.)
when declaring a pointer, limit yourself to only assign a value to it with dynamiclly allocated memory(see malloc()) or with the & (the address) of a static (not temporary) variable. this will ensure rebust code, and less chance to get the famous segmentation fault.
good luck with learning c.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: In mongodb is there a performance reason to separate collections into more than on database? I have an application using a MongoDB database and am about to add custom analytics. Is there a reason to use a separate database for the analytics or am I better off to build it in the application database?
A: Here are the reasons I can think of:
*
*Name collisions between production collections and analytics collections
*You need a different replica set configuration for analytics
*You need a different sharding configuration for analytics
*You want different physical media for some data (production data on fast disks, analytics on slow disk, for example)
*Starting in Mongo 2.2, the "global write lock" will be a per-database lock, so different databases will isolate analytics traffic from production traffic a bit more.
Unless something on this list applies to you, then you don't need to split them out. Also, it's much easier to move a collection across DBs in MongoDB than an RDBMS (as you don't have foreign keys to cause trouble), so IMO it's a relatively easy decision to delay.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: jQuery: pass parameter to function I want to pass a parameter into my function. The parameter will be a variable that representsa CSS class name. Based upon which checkbox was selected I will set the value of the variable (eg, if CheckBox1 was selected the value of the variable would be the class name '.list1').
The dropdownlist has a large number of options and I want to select a subset of the options based on their 'class' and use those options to populate another list (fl_listEmpty).
Here is my code as far as I've gotten:
function FillDropDownList(parameter) {
$('.fl_list1 [**put class name parameter here**]).each(function (index) {
$(".fl_listEmpty").append($('<option> </option>').val(index).html($(this).text()));
})
}
A: Just compose the selector as if it were a string (which it is).
function FillDropDownList(parameter) {
$('.fl_list1 ' + parameter).each(function (index) {
$(".fl_listEmpty").append($('<option> </option>').val(index).html($(this).text()));
})
}
A: Assuming your space is intentional between classes, a find would be appropriate. If it is possible that the value may be undefined, you could just make a condition:
function FillDropDownList(parameter) {
var selset = parameter ? $('.fl_list1').find('.' + parameter) : $('.fl_list1');
selset.each([** your function here **]);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to show JQuery-UI Dialog window beneath the radio button i have two radio button:
radiobutton1 and radiobutton2 and when i hover over it i showed the jquery-ui dialog window... currently its showing the dialogue too far to the right... what i want to show the dialog window right underneath the radiobutton. as shown in second image.
$(document).ready(function () {
$('#div_').dialog({
autoOpen: false,
});
$(".radiobutton1").hover(
function (){
$('#div_').dialog({title: "Iamge Left)"});
$('#div_').removeClass("radiobutton1_1 radiobutton2").dialog('open');
var target = $(this);
$("#div_").dialog("wid").position({
my: 'center top',
at: 'center bottom'//,
//of: target
});
},
function (){
$('#div_').dialog('close');
});
$(".radiobutton2").hover(
function (){
$('#div_').dialog({title: "Images Right"});
$('#div_').removeClass("radiobutton1_1 radiobutton2").addClass("radiobutton2").dialog('open');
$("#div_").dialog("wid").position({
my: 'center top',
at: 'center bottom'//,
//of: target
});
},
function (){
$('#div_').dialog('close');
});
});
A: I whipped up a fiddle: http://jsfiddle.net/jensbits/dhp3d/1/
I added this to a tut on positioning dialogs: http://www.jensbits.com/2011/06/19/position-jquery-ui-dialog-relative-to-link/
Give it a try. You might need to code for window scrolling and resizing so that is in the fiddle. I only tested this in jsfiddle. You will have to run it on a page to see if the positioning works correctly when the page is resized or scrolled.
If you don't care about resizing or scrolling, then you can take out all the window scroll and resize functions.
HTML:
<input type="radio" name="radioImage" id="radio1" class="opendialog" />Images Right
<input type="radio" name="radioImage" id="radio2" class="opendialog" />Images Left
<div id="dialog1" class="dialog">
<p> My positioned dialog 1</p>
</div>
<div id="dialog2" class="dialog">
<p> My positioned dialog 2</p>
</div>
jQuery:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("id").substring((prefix.length));
return num;
}
function positionDialog(base, dialog) {
linkOffset = base.position();
linkWidth = base.width();
linkHeight = base.height();
scrolltop = $(window).scrollTop();
dialog.dialog("option", "position", [(linkOffset.left) + linkWidth / 2, linkOffset.top + linkHeight - scrolltop]);
}
$(function() {
$(".dialog").dialog({
autoOpen: false,
show: 'fade',
hide: 'fade',
modal: false,
width: 320,
minHeight: 180,
buttons: {
"Close": function() {
$(this).dialog("close");
}
}
});
$(".opendialog").change(function() {
$(".dialog").dialog("close");
if ($(this).is(":checked")) {
var num = getNum($(this), "radio");
positionDialog($("#radio1"), $("#dialog" + num));
$("#dialog" + num).dialog("open");
}
return false;
});
//resize and scroll function are optional - you may or may not need them
$(window).resize(function() {
var openDialog = $(".dialog" + getNum($(".opendialog:checked")), "radio");
positionDialog($("#radio1"), openDialog);
});
$(window).scroll(function() {
var openDialog = $(".dialog" + getNum($(".opendialog:checked")), "radio");
positionDialog($("#radio1"), openDialog);
});
});
A: You can pass in the x,y coordinates of where you want the dialog to open as an array i.e
$( ".selector" ).dialog({ position: [300,300] });
$('#div_').dialog({
autoOpen: false,
position: [300,300]
});
A: I think what you have is almost correct. You just need to have my: 'left top', instead of my: 'center top' in the position method. Also, change .dialog("wid") to .dialog("widget"). I am guessing the latter is a typo at your side.
var target = $(this);
$("#div_").dialog("widget").position({
my: 'left top',
at: 'center bottom',
of: target
});
See this in action: http://jsfiddle.net/william/dVZex/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image replacement I have a large div with the site header/logo as the background image. Is there anything wrong with putting a h2 tag containing the site title behind this using z-index, so that it would show if the user couldn't/didn't get the image for some reason? I know this is different to a standard [background on the h2 element] image replacement. (EDIT: Sorry maybe i'm not making it clear - i'm using a div background image not an IMG tag)
A: You should use the alt attribute of the img tag, so if the image isn't loaded for some reason, the text would appear.
This is exactly why the alt attr exists,.
A: You can simple place img tag with alt attribute. That way if image is not loaded, text will be displayed.
<img src="" alt="This text will be displayed" />
A: If possible, I would ditch the div and just use an h2 with an id and set a background image to that.
I do that whenever possible to avoid excessive divs when I could use other block-level elements, if it only has a background and text. An h* with a background image is still a heading.
A: Google doesn't like what you describe:
http://www.google.com/support/webmasters/bin/answer.py?answer=66353
However, from a pure design perspective, there is no real problem, save some bloated code.
You might want to see how often your images fail before you attempt any changes.
A: That's fine. Note that many feel the site logo isn't really something you'd put into an h* tag other than on the home page, when it makes sense to put it in an h1 tag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hibernate multiple users, dynamically changing There are technically two questions here, but are tightly coupled :)
I'm using Hibernate in a new project. It's a POS project.
It uses Oracle database.
We have decided to use Hibernate because the project is large, and because it provides (the most popular) ORM capabilities.
Spring is, for now, out of the question - the reason being: the project is a Swing client-server application, and it adds needless complexity. And, also, Spring is supposed to be very hungry on the hardware resources.
There is a possibility to throw away Hibernate, and to use JDBC. Why? The project requirement is precise database interaction. Meaning, we should have complete control over the connections, sessions and transactions(and, yes, going as low as unoptimized queries).
The first question is - what are your opinions on using the mentioned requrement?
The second question revolves around Hibernate.
We developed a simple Hibernate pilot project.
Another project requirement is - one database user / one connection per user / one session per user / transactions are flexibile(we can end them when we want, as sessions).
Multiple user can log in the application at the same time.
We achived something like that. To be precise, we achived the full described functionality without the multiple users requirement.
Now, looking at the available resources, I came to a conclusion that if we are to have multiple users on the database(on the same schema), we will end up using multiple SessionFactory, implementing a dynamic ConnectionProvider for new user connections. Why?
The users hashed passwords are in the database, so we need to dynamically add a user to the list of current users.
The second question is - can this be done a little easier, it seems weird that Hibernate doesn't support such configurations.
Thank you.
A: If you're pondering about weather to use Hibernate or JDBC, honestlly go for JDBC. If your domain model is not too complex, you don't really get a lot of advantages from using hibernate. On the other hand using JDBC will greatly improve performance, as you have better control on your queries, and you get A LOT less memory usage from not habing all the Hibernate overhead. Balance this my making an as detailed as possible first scetch of your model. If you're able to schetch it all from the start (no parts that are possible to change wildly in throughout the project), and if said model doesn't look to involved, JDBC will be your friend.
About your users and sessions there, I think you might be mistaking (tho it could just be me), but I don't think you need multiple SessionFactories to have multiple sessions. SessionFactory is a heavy object to initialize, but once you have one you can get multiple hibernate session objects from it which are lightweight.
As a final remark, if you truly stick with an ORM solution (for whatever reason), if possible chose EclipseLink JPA2 implementation. JPA2 has more features over hibernate and the Eclipselink implementation is less buggy then hibernate.
A: So, as far as Hibernate goes, I still dont know if the only way to dynamicaly change database users(change database connections) was to create multiple session factories, but I presume it is.
We have lowered our requriements, and decided to use Hibernate, use only one user on the database(one connection), one session per user(multiple sessions/multiple "logical" users). We created a couple of Java classes to wrap that functionality. The resources how this can be done can be found here.
Why did we use Hibernate eventually? Using JDBC is more precise, and more flexibile, but the effort to once again map the ResultSet values into objects is, again, the same manual ORM approach.
For example, if I have a GUI that needs to save a Page, first I have to fetch all the Page Articles and then, after I save the Page, update all the Articles FK to that Page. Notice that Im speaking in nouns(objects), and I dont see any other way to wrap the Page/Articles, except using global state. This is the one thing I wouldnt like to see in my application, and we are, after all, using Java, a OO language.
When we already have an ORM mapper that can be configured(forced would be the more precise word to use in this particular example) to process these thing itself, why to go programming it?
Also, we decided to user google Guice - its much faster, typesafe, and could significantly simplify our development/maintence/testing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I set up my openGL blending so that I can draw on only the opaque areas on a CCRenderTexture using a CCSprite that has some transparency? I'm having trouble drawing to a CCRenderTexture with a texture that includes transparency due to the blending that I've used.
The sprite that I am drawing with has a blending function of:
glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA).
The render texture that it is drawing to has the blending function:
glBlendFuncSeparate(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_SRC_COLOR, GL_ONE_MINUS_SRC_ALPHA).
The render texture is set up with it being mostly transparent with some completely opaque areas on it. The above blend functions allow me to draw with a completely solid sprite on the solid areas while it not drawing on the transparent areas.
Trouble arises when I try to change the sprite that I draw with to include some transparency. It tends to "erase" the opaque areas on the render texture. Ideally I would like the transparent areas on the sprite that I draw with to have no effect. I was wondering if an openGL blending guru was able to give me some guidance?
To clarify, the final effect that I am trying to achieve is to be able draw a sprite that includes some transparent areas to my render texture. The transparent areas of the sprite should not draw to my render texture. The opaque areas of the sprite should only draw to the render texture if they are over an opaque area on the render texture.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL: trigger/delimiter without SUPER Attempting to run this SQL:
DELIMITER $$
CREATE TRIGGER crypt_f
BEFORE INSERT ON c_data_test
FOR EACH ROW
BEGIN
UPDATE c_data_test
SET f_id = ENCRYPT(f_id, 'key');
END$$
DELIMITER ;
Gives this error:
ERROR 1227 (42000): Access denied; you need the SUPER privilege for this operation
We are not allowed SUPER access from our host. How can I create this trigger?
A: You would have to ask the DBA of your host to run the trigger create statement for you. The newest versions of MySQL allows non SUPER users to create triggers (MySQL 5.1.6 and greater). However if binary logging is on you will still need SUPER privileges.
So first, double check the version of MySQL running, and if its MySQL 5.1.6 or greater and binary logging is turned off, request the TRIGGER privilege from the hosts DBA, otherwise you would have to ask the DBA to create the trigger for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I show a PDF inside a DIV with a zoom function? I have a large PDF and I need to show it 50% reduced in size inside a div tag that is 600px 600px in size. I also need to offer the client a zoom function.
Should I use the "object" tag? But can I reduce the pdf size inside an "object"?
Is there a jquery example or anything out there?
Need help.
A: <div>
<object data="febrero2012.pdf" type="application/pdf" width="600px" height="600px">
alt : <a href="febrero2012.pdf">febrero2012.pdf</a>
</object>
</div >
I coudn't find the way to set a default zoom level yet. If you find a way, please let me know.
A: No. PDFs cannot be displayed in a DIV, as they're not html or an image. You can convert the PDF to html/images on the server and display that, just like google's "quick view" function does. But in general, PDF rendering in-browser is dependent on the presence of a plugin (e.g. Adobe Reader, Chrome's built-in rendering engine notwithstanding). Plugins can't be displayed in divs, just embed/object/iframe sections.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't Route An MVC Controller I have tried routes.mapRoute but i can't figure a way in MVC 3 to use it make a root path route to an action. e.g mywebsite.com/party should redirect to mywebsite.com/events/party where events is the controller and party is the action.
Is this even possible?
A: Without seeing your existing routes, its hard to give you an exact solution.
One rule to keep in mind:
MVC will resolve the first in your route collection that matches the requested URL
not necessarily the most specific match.
Make sure you do not have another rule that would also satisfy that route placed earlier in your code, e.g. the routing algorithm might be finding a "party" controller and "index" action because you have a default rule like:
routes.MapRoute(
"Default",
"{action}",
new { controller = "Home", action = "Index" }
);
placed before your rule.
You need to put something like
routes.MapRoute(
"PartyRoute",
"party",
new { controller = "Events", action = "Party" }
);
BEFORE any route that might match a URL with just a single parameter
A: routes.MapRoute(
"Default",
"{action}",
new { controller = "Events", action = "Index" }
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: issue with FB like, a new activity gets posted in profile When a user likes a post in my website http://thewittyshit.com it adds a new activity in their profile.
I have used "og:type = article" meta content on the pages having like button.
Can somebody enlighten me on how to stop my pages from being added to my user's activity section in their FB profile?
Let me know if some other information is also required.
Thanks
A: This is not possible, because they like something. By like, the new feed item is automatically added to their profile/wall
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Resizing an element when the document resizes I'd like to resize an element when the document resizes. If a draggable div is moved around and causes the document to scroll. I want to resize an element like this $("#page").css('height','120%');. I do that in the onresize event for a div. Is that the right way? Is there a different event that where I should do this?
Here is the HTML.
<div id="matting" onresize="resize_page();"> <!-- Begin page matting div -->
<div id="page"> <!-- Begin page div -->
</div> <!-- End page div -->
</div> <!-- End page matting div -->
<script type="text/javascript">
function resize_page() {
alert ('resize_page');
$("#page").css('height','120%');
}
</script>
A: You need to hook into the draggable stop callback:
$("#matting" ).resizable({
stop: function(event, ui) { ...YOUR CODE... }
});
A: You can hook the resize event in jQuery: http://api.jquery.com/resize/
A better solution would probably be to put a restriction on the draggable object so it can't move out of bound and scroll the page.
A: I understand now, the new code uses a plugin that allows the resize method to be applied to every element.
http://jsfiddle.net/P9Ppb/
<< Resize the window.
A: The solution was to reset the height of the page div to be that of the scrolling height of the parent div (the document).
var page_height = $('#matting')[0].scrollHeight;
$("#page").css('height',page_height);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can i disable error prompts on build for locked dll files (in other workspaces) in vs2010? Is there a way to disable the warning prompt that pops up when vs2010 finds a dll file locked by another user during a build? I'm using visual studio 2010 with TFS 2008.
A: By default, TFS disables shared check-outs for binary files - this is enforced for any user, including the build process.
If you wish to enabled shared check-outs for all files, you can update the file extension list for mergeable files: see the Managing File Types article on MSDN.
A: I'm gonna try Edward's solution once i have proper rights on the TFS but for now I've changed my settings as follows:
This way it avoids the prompt, and also checks out any files i edit once i save em.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple UIViewControllers - Best way to implement this I'm building an iOS application and I try to determine the best way to implement this :
I have a main UIViewController (MainViewController) that displays a simple view. This view contains a button that let the user add an object (let's say a Circle) to the main view. The user can add multiple circles by pressing the button and move each of them by dragging them. The circle objects should have their own color (randomly chosen).
The question is: what is the best way to implement this?
Should I create an other UIViewController subclass (CircleViewController) for the Circle object, whose view actually draws the circle?
And then, when the user presses the button, should I create a new instance of this CircleViewController and add its view to the MainViewController?
When the user double-tap a circle, it should disappear... How can I send a message to the mainViewController to tell it to remove the concerned CircleViewController's view?
Thank you very much for your help.
A: If your object is really as simple as a circle you should look at Quartz in Apple's Documentation and the method drawRect: in UIView. If you are doing something more like an image you could subclass UIView and put your code in there. Either way, you do not need to create new viewControllers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to convert an NSData into an NSString Hex string? When I call -description on an NSData object, I see a pretty Hex string of the NSData object's bytes like:
<f6e7cd28 0fc5b5d4 88f8394b af216506 bc1bba86 4d5b483d>
I'd like to get this representation of the data (minus the lt/gt quotes) into an in-memory NSString so I can work with it.. I'd prefer not to call -[NSData description] and then just trim the lt/gt quotes (because I assume that is not a guaranteed aspect of NSData's public interface and is subject change in the future).
What's the simplest way to get this representation of an NSData object into an NSString object (other than calling -description)?
A: Keep in mind that any String(format: ...) solution will be terribly slow (for large data)
NSData *data = ...;
NSUInteger capacity = data.length * 2;
NSMutableString *sbuf = [NSMutableString stringWithCapacity:capacity];
const unsigned char *buf = data.bytes;
NSInteger i;
for (i=0; i<data.length; ++i) {
[sbuf appendFormat:@"%02X", (NSUInteger)buf[i]];
}
If you need something more performant try this:
static inline char itoh(int i) {
if (i > 9) return 'A' + (i - 10);
return '0' + i;
}
NSString * NSDataToHex(NSData *data) {
NSUInteger i, len;
unsigned char *buf, *bytes;
len = data.length;
bytes = (unsigned char*)data.bytes;
buf = malloc(len*2);
for (i=0; i<len; i++) {
buf[i*2] = itoh((bytes[i] >> 4) & 0xF);
buf[i*2+1] = itoh(bytes[i] & 0xF);
}
return [[NSString alloc] initWithBytesNoCopy:buf
length:len*2
encoding:NSASCIIStringEncoding
freeWhenDone:YES];
}
Swift version
private extension Data {
var hexadecimalString: String {
let charA: UInt8 = 0x61
let char0: UInt8 = 0x30
func byteToChar(_ b: UInt8) -> Character {
Character(UnicodeScalar(b > 9 ? charA + b - 10 : char0 + b))
}
let hexChars = flatMap {[
byteToChar(($0 >> 4) & 0xF),
byteToChar($0 & 0xF)
]}
return String(hexChars)
}
}
A: In Swift you can create an extension.
extension NSData {
func toHexString() -> String {
var hexString: String = ""
let dataBytes = UnsafePointer<CUnsignedChar>(self.bytes)
for (var i: Int=0; i<self.length; ++i) {
hexString += String(format: "%02X", dataBytes[i])
}
return hexString
}
}
Then you can simply use:
let keyData: NSData = NSData(bytes: [0x00, 0xFF], length: 2)
let hexString = keyData.toHexString()
println("\(hexString)") // Outputs 00FF
A: I agree on the solution not to call description which is to be reserved for debugging, so good point and good question :)
The easiest solution is to loop thru the bytes of the NSData and construct the NSString from it. Use [yourData bytes] to access the bytes, and build the string into an NSMutableString.
Here is an example by implementing this using a category of NSData
@interface NSData(Hex)
-(NSString*)hexRepresentationWithSpaces_AS:(BOOL)spaces;
@end
@implementation NSData(Hex)
-(NSString*)hexRepresentationWithSpaces_AS:(BOOL)spaces
{
const unsigned char* bytes = (const unsigned char*)[self bytes];
NSUInteger nbBytes = [self length];
//If spaces is true, insert a space every this many input bytes (twice this many output characters).
static const NSUInteger spaceEveryThisManyBytes = 4UL;
//If spaces is true, insert a line-break instead of a space every this many spaces.
static const NSUInteger lineBreakEveryThisManySpaces = 4UL;
const NSUInteger lineBreakEveryThisManyBytes = spaceEveryThisManyBytes * lineBreakEveryThisManySpaces;
NSUInteger strLen = 2*nbBytes + (spaces ? nbBytes/spaceEveryThisManyBytes : 0);
NSMutableString* hex = [[NSMutableString alloc] initWithCapacity:strLen];
for(NSUInteger i=0; i<nbBytes; ) {
[hex appendFormat:@"%02X", bytes[i]];
//We need to increment here so that the every-n-bytes computations are right.
++i;
if (spaces) {
if (i % lineBreakEveryThisManyBytes == 0) [hex appendString:@"\n"];
else if (i % spaceEveryThisManyBytes == 0) [hex appendString:@" "];
}
}
return [hex autorelease];
}
@end
Usage:
NSData* data = ...
NSString* hex = [data hexRepresentationWithSpaces_AS:YES];
A: Sadly there's no built-in way to produce hex from an NSData, but it's pretty easy to do yourself. The simple way is to just pass successive bytes into sprintf("%02x") and accumulate those into an NSMutableString. A faster way would be to build a lookup table that maps 4 bits into a hex character, and then pass successive nybbles into that table.
A: Just wanted to add that @PassKits's method can be written very elegantly using Swift 3 since Data now is a collection.
extension Data {
var hex: String {
var hexString = ""
for byte in self {
hexString += String(format: "%02X", byte)
}
return hexString
}
}
Or ...
extension Data {
var hex: String {
return self.map { b in String(format: "%02X", b) }.joined()
}
}
Or even ...
extension Data {
var hex: String {
return self.reduce("") { string, byte in
string + String(format: "%02X", byte)
}
}
}
A: I liked @Erik_Aigner's answer the best. I just refactored it a bit:
NSData *data = [NSMutableData dataWithBytes:"acani" length:5];
NSUInteger dataLength = [data length];
NSMutableString *string = [NSMutableString stringWithCapacity:dataLength*2];
const unsigned char *dataBytes = [data bytes];
for (NSInteger idx = 0; idx < dataLength; ++idx) {
[string appendFormat:@"%02x", dataBytes[idx]];
}
A: While it may not be the most efficient way to do it, if you're doing this for debugging, SSCrypto has a category on NSData which contains two methods to do this (one for creating an NSString of the raw byte values, and one which shows a prettier representation of it).
http://www.septicus.com/SSCrypto/trunk/SSCrypto.m
A: Seeing there is a Swift 1.2 snippet in the comments, here's the Swift 2 version since C style for loops are deprecated now.
Gist with MIT license and two simple unit tests if you care.
Here's the code for your convenience:
import Foundation
extension NSData {
var hexString: String {
let pointer = UnsafePointer<UInt8>(bytes)
let array = getByteArray(pointer)
return array.reduce("") { (result, byte) -> String in
result.stringByAppendingString(String(format: "%02x", byte))
}
}
private func getByteArray(pointer: UnsafePointer<UInt8>) -> [UInt8] {
let buffer = UnsafeBufferPointer<UInt8>(start: pointer, count: length)
return [UInt8](buffer)
}
}
A: Assuming you have already set:
NSData *myData = ...;
Simple solution:
NSString *strData = [[NSString alloc]initWithData:myData encoding:NSUTF8StringEncoding];
NSLog(@"%@",strData);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
} |
Q: Considerations for updating Android app using Android API to Google API I have an Android geolocation application released into the market named apna ilaka.
It is using Android API level 2.1. In order to allow a user to add places I would like to display a Google map with which the user could find different locations and would be able to add place indicators and information.
Following are my questions :
*
*Do I really need to change my Android API level to Google API level in config path?
*Since my app is already in market if I upload this new apk on market will it create any issue in updating the software on user side?
A: You only need to update the API level of you app if you want to use any api that are higher than the currently set level.
Supporting multiple API levels can be tricky but it isn't a nightmare, check out this great post by google on this subject:
http://android-developers.blogspot.com/2010/07/how-to-have-your-cupcake-and-eat-it-too.html
A: *
*I guess you are talking about "Google API" versus "Android API"? If you need Google Maps you will need to use "Google API" as it contains the Maps libraries. Otherwise you could not use Maps classes when developing/compiling.
*No, as far as I know you should not have any problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery module for price caculator? Ive made a website with a booking feature. When you make a booking you specify the distance in the booking form. What I need is for the price of the booking to be calculated from the rates below:
Rates:
0-5 km $20/ mile
5-10 km $15/ mile
10-20 km $10/ mile
20-30 km $5/ mile
So if the distance was 11km, the price would be 11 x 15 = 165. This value would then need to be written to another input field in the booking form.
Doing this with PHP is beyond my skills so Im hoping to do it with jQuery. Are there any modules that do this sort of thing or can make life a bit easier? This interface is only for the site admin so js reliance and loading extra plug ins or libraries isn't an issue.
Thanks
A: The jQuery Calculation plugin can be attached to form fields and do dynamic operations. For example, one of samples has four text boxes you can edit, with a fifth one immediately updating the average value of all of them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Retrieving object data from multiple tables help Sorry if I'm not wording this too well, but let me try to explain what I'm doing. I have a main object of class A, that has multiple objects of classes B, C, D and E.
such that:
Class ObjectA
{
ObjectB[] myObjectBs;
ObjectC[] myObjectCs;
ObjectD[] myObjectDs;
ObjectE[] myObjectEs;
}
where A---B mapping is 1 to many, for B, C, D and E. That is, all B,C,D,E objects are associated with only one object A.
I'm storing the data for all these objects in a database, with Table A holding all the data for the instances of Class A, etc.
Now, when getting the data for this at run time on the fly, I'm running 5 different queries for each object.
(very simplified psuedocode)
objectA=sql("select * from tableA where id=#id#");
objectA.setObjectBs(sql("select * from tableB where a_id=#id#");
objectA.setObjectCs(sql("select * from tableC where a_id=#id#");
objectA.setObjectDs(sql("select * from tableD where a_id=#id#");
objectA.setObjectEs(sql("select * from tableE where a_id=#id#");
if that makes sense.
Now, I'm wondering, is this the most efficient way of doing it? I feel like there should be a way to get all this info in 1 query, but doing something like "select * from a,b,c,d,e where a.id = #id# and b.a_id = #id# and c.a_id = #id# and d.a_id = #id# and e.a_id = #id#" will give a result set with all the columns of A,B,C,D,E for each row, and there will be many many more rows that I'd be needing.
If there was only one array of objects (like just ObjectBs) it could be done with a simple join and then handled by my database framework. If the relationships were A(one)....B(many) and B(one)....C(many) it could be done with two joins and work. But for A(one)....B(many) and A(one)....C(many) etc I can't think of a good way to do joins or return this data without having too many rows, as with joins if A has 10 Bs and 10Cs, it'll return 100 rows rather than 20.
So, is the way I'm currently doing it, with 5 different selects, the most efficient (which it seems like its not), or is there a better way of doing it?
Also, If I were to grab a large set of these at once (say, 5000 ObjectAs and all the associated Bs, Cs, Ds, and Es), would there be a way to do it without running a ton of consecutive queries one after the other?
A: You can try iBatis using N+1 Select Lists
http://ibatis.apache.org/docs/dotnet/datamapper/ch03s05.html
Hth.
A: There is a huge performance issue with N+1 selects (check https://github.com/balak1986/prime-cache-support-in-ibatis2/blob/master/README). So please don't use it unless there is no other way of achieving this.
Luckily iBatis has groupBy property, that is created exactly to map data for these kind of complex object.
Check the example from http://www.cforcoding.com/2009/06/ibatis-tutorial-aggregation-with.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python re module's cache clearing While reading the documentation on Python re module I decided to have a look on re.py source code.
When I opened it, I found this:
_cache = {}
_MAXCACHE = 100
def _compile(*key):
cachekey = (type(key[0]),) + key
p = _cache.get(cachekey)
if p is not None:
return p
#...Here I skip some part of irrelevant to the question code...
if len(_cache) >= _MAXCACHE:
_cache.clear()
_cache[cachekey] = p
return p
Why is the cache cleared using_cache.clear() when it reaches _MAXCACHE of entries?
Is it common approach to clear cache completely and start from scratch?
Why just not used the longest time ago cashed value is deleted?
A: Here is a quote from one of the developers of a new regex module scheduled for 3.3 regarding the caching, this is part of a list of features that separates the new module from the current re module.
7) Modify the re compiled expression cache to better handle the
thrashing condition. Currently, when regular expressions are compiled,
the result is cached so that if the same expression is compiled again,
it is retrieved from the cache and no extra work has to be done. This
cache supports up to 100 entries. Once the 100th entry is reached, the
cache is cleared and a new compile must occur. The danger, all be it
rare, is that one may compile the 100th expression only to find that one
recompiles it and has to do the same work all over again when it may
have been done 3 expressions ago. By modifying this logic slightly, it
is possible to establish an arbitrary counter that gives a time stamp to
each compiled entry and instead of clearing the entire cache when it
reaches capacity, only eliminate the oldest half of the cache, keeping
the half that is more recent. This should limit the possibility of
thrashing to cases where a very large number of Regular Expressions are
continually recompiled. In addition to this, I will update the limit to
256 entries, meaning that the 128 most recent are kept.
http://bugs.python.org/issue2636
This seems to indicate that it is more likely the laziness of the developer or "an emphasis on readability" that explains the current caching behavior.
A: If I had to guess I'd say that it was done this way to avoid having to keep track of when / how long individual values had been stored in the cache, which would create both memory and processing overhead. Because the caching object being used is a dictionary, which is inherently unordered, there's no good way to know what order items were added to it without some other caching object as well. This could be addressed by using an OrderedDict in place of a standard dictionary, assuming you're working with Python >= 2.7, but otherwise, you'd need to significantly redesign the way the caching was implemented in order to eliminate the need for a clear().
A: The point of caching is to decrease the average call time of the function. The overhead associated with keeping more information in _cache and pruning it instead of clearing it would increase that average call time. The _cache.clear() call will complete quickly, and even though you lose your cache this is preferable to maintaining a cache state and having the overhead of removing individual elements from the cache when the limit is reached.
There are a few things to think about when calculating the cache efficiency:
*
*Average call time on cache hits (very short)
*Average call time on cache misses (longer)
*Frequency of cache hits (fairly uncommon)
*Call time when cache is cleared or pruned (fairly uncommon)
The question is does increasing #3 make sense if it means increasing #2 and #4 as well. My guess is that it doesn't, or the difference is negligible enough that keeping the code simple is preferable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Why is sizeof(array) different in these two cases?
Possible Duplicate:
Sizeof array passed as parameter
Given the following code, the system I'm currently on (which seems to be 64-bit given the size of a pointer) prints:
32
4
Now, the size of an int should be 4 bytes on this system, so 8*4 = 32 makes sense. Also, I understand that the size of a pointer should also be 4 bytes, which is what I'm guessing is happening to the array in foo.
My question is why is sizeof(arr) in the foo function treated differently than sizeof(myarray) in main() when both are specifically int[8] arrays? I had anticipated receiving 32 in both cases and it confuses me why it would end up otherwise.
#include <iostream>
void foo(int arr[8])
{
std::cerr << sizeof(arr) << std::endl;
}
int main()
{
int myarray[8];
std::cerr << sizeof(myarray) << std::endl
foo(myarray);
}
A: Arrays decay into pointers when passed into functions such that you are printing the sizeof the array pointer of int of 4 bytes in foo().
The sizeof(myarray) prints the size of the array which is 32 (num elements x size of int).
A: Its because arrays that are function arguments get translated to pointers.
so
void foo(int arr[8])
is actually
void foo(int *arr)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: closing jquery ui modal from within another function again.
I have a script that is using the jQuery UI plugin to generate inline modal windows, as such:
function openModal(src, width, title){
$("#" + src).dialog({
modal: true,
width: width,
title: title,
resizable: false,
show: 'fade',
hide: 'fade'
});
$('.ui-widget-overlay').hide().fadeIn();
return false;
}
$(document).ready(function() {
$('#newTopicBtn').click(function(e) {
e.preventDefault();
openModal('newTopic', 650, 'New Topic');
});
});
The modal window pops up just as it should.
Most of these modal windows open forms of some sort. The problem is that when the form is submitted, and processed by the script, i can't seem to get the form's modal to close by itself when i use $('#newTopic').dialog("close"):
$('#newTopic_form').bind('submit', function() {
var error = '';
var topicTitle = $('input[name=newTopicTitle]').val();
var topicBody = $('textarea[name=newTopicBody]').val();
if(topicTitle == '' || topicTitle.length < 2)
{
error = error + '<br />You must enter a longer title.';
}
if(topicBody == '' || topicBody.length < 2)
{
error = error + '<br />You must enter a longer topic.';
}
if(error != '')
{
$('#newTopicError').css("display","none");
$('#newTopicError').html(error);
$('#newTopicError').fadeIn(1000);
}
else
{
var pageUrl = window.location.search;
var pattern = /mode=viewcat&id=(\d+)&title/gi;
var catID = pageUrl.match(pattern);
var data = 'mode=newTopic&cat_id=' + catID + '&title=' + encodeURIComponent(topicTitle) + '&content=' + encodeURIComponent(topicBody) + '&u=' + usrId;
$.ajax({
url: "data.php",
type: "POST",
dataType: "json",
data: data,
cache: false,
success: function(data) {
if(data.response == 'added')
{
$('#newTopicError').css("display", "none");
$('#newTopicError').html("You have added your topic.");
$('#newTopicError').fadeIn(1000);
setInterval(10000, function(){
$('#newTopic').dialog("close");
});
}
}
});
}
return false;
});
The form submits and is processed perfectly fine, and the correct strings are faded into the modal's form response area, but the window never closes.
There is also an issue with my RegEx, as it only returns null instead of the catID, if anyone wants to help out with that one, too. :)
A: I think
setInterval(10000, function(){
$('#newTopic').dialog("close");
});
should be:
setTimeout(function(){
$('#newTopic').dialog("close");
}, 10000);
The original code has its parameters in the wrong order, and it says that you want to close the dialog every 10 seconds. The new code has the parameters in the right order, and will only execute once, 10 seconds from being set.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get days between dates I need to remove files that are older than 14 days from a directory that stores our backups. I can get the time of an individual file by using something like this:
start = (os.path.getmtime(join(dirpath, name))/3600*24)
But I'm getting confused with how I use timedelta to find the difference between this and the current date.
I'd like to use something like this:
d = (datetime.timedelta(time.now() - os.path.getmtime(join(dirpath, dirname))
but I'm just not getting it. I'm on my own here, and I'd love some help.
A: Try:
if time.time() - os.path.getmtime(filename) > 14 * 24 * 3600:
print 'the file is older than 14 days'
A: a timedelta is the result of subtracting a datetime from another datetime. in this example i show that my /bin/bash is 1168 days and some older than my /dev/null:
>>> import datetime
>>> import os.path
>>> datetime.datetime.fromtimestamp(os.path.getmtime("/dev/null"))
datetime.datetime(2011, 7, 24, 18, 58, 28, 504962)
>>> datetime.datetime.fromtimestamp(os.path.getmtime("/bin/bash"))
datetime.datetime(2008, 5, 12, 15, 2, 42)
>>> datetime.datetime.fromtimestamp(os.path.getmtime("/dev/null"))-datetime.datetime.fromtimestamp(os.path.getmtime("/bin/bash"))
datetime.timedelta(1168, 14146, 504962)
>>> d = datetime.datetime.fromtimestamp(os.path.getmtime("/dev/null"))-datetime.datetime.fromtimestamp(os.path.getmtime("/bin/bash"))
>>> d.days
1168
A: datetime.datetime.now()-datetime.timedelta(days=14)
Something like that?
A: aix has a perfectly good answer using the time module. Here's an answer that uses datetime.
from datetime import *
maxdays = timedelta(14)
mtime =datetime.fromtimestamp(os.path.getmtime(filename))
if mtime - datetime.now() > maxdays:
print filename, 'older than 14 days'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Optimize contentProvider query for retrieve contact names and phones Currently, I'm using this code in order to get the contact name and the phone number:
ContentResolver contentResolver = getContentResolver();
Cursor people = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
int nameIndex = people.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int idIndex = people.getColumnIndex(ContactsContract.Contacts._ID);
int hasPhoneNumberIndex = people.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
String name, id;
int hasPhoneNumber;
while(people.moveToNext()){
name = people.getString(nameIndex);
id = people.getString(idIndex);
hasPhoneNumber = people.getInt(hasPhoneNumberIndex);
if(hasPhoneNumber > 0){
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+id, null, null);
phones.moveToFirst();
int phoneIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String phone = phones.getString(phoneIndex);
HashMap<String, String> namePhoneType = new HashMap<String, String>();
namePhoneType.put("Name", name);
namePhoneType.put("Phone", phone);
m_peopleList.add(namePhoneType);
phones.close();
}
}
But this is extremely slow.
Is there a way to retrieve name and phone in only one query?
A: It seems to me that the noted performance issue stems from the inherent "n+1 select" problem in the implementations proposed.
*
*open a cursor to iterate over all contacts (1)
*for each contact open a cursor to iterate over the phone numbers for that contact (n)
A faster approach, if you truly need all this data, is to perform two queries from contacts and phone numbers returning the appropriate surrogate and primary keys and then performing the join in memory.
Query 1: get all contacts as a Map by ContactId
With the myriad of solutions proposed being sure to pull out the _ID field as the ContactId
Query 2: get all the phone numbers and store them in a list
Cursor c = MyO2Application.getContext().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER },
null,
null,
null
);
while (c.moveToNext()) {
String id = c.getString(0);
String contactId = c.getString(1); // this is the foreign key to the contact primary key
String displayName = c.getString(2);
String number = c.getString(3);
You can then iterate through the list of phone numbers, looking up the contact from the map by ContactId and associate the phone numbers with the contact.
Execution speeds for 1000 contacts went from 60 seconds down to 4 seconds. As is often the case, there is a trade-off on memory consumption and impact to GC.
Observation while posting: getting the ids as an int and using SparseArray may be an approach worth considering. Minimal impact expected, however, compared to the "n+1 select" issue addressed here.
A: You can read more about how to do it in a different way here
Here's a snippet
//query for the people in your address book
Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null,People.NAME + " ASC");
startManagingCursor(cursor);
//bind the name and the number fields
String[] columns = new String[] { People.NAME, People.NUMBER };
int[] to = new int[] { R.id.name_entry, R.id.number_entry };
SimpleContactAdapter mAdapter = new SimpleContactAdapter(this, R.layout.list_entry, cursor, columns, to);
this.setListAdapter(mAdapter);
A: I've founded a way:
Cursor people = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null, Phone.DISPLAY_NAME + " ASC");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Provisioning Profiles + Push Notifications + Production vs Development I'm building an iOS app that uses push notifications, and I'm finally ready to submit it. Before I do, I'd like to test out push notifications off the Production server, to make sure everything is working correctly. Thus far, the sandbox environment has been working fine.
After doing quite a bit of searching, I learned that switching the servers over from ssl://gateway.sandbox.push.apple.com:2195 to ssl://gateway.push.apple.com:2195 wasn't enough, and that production push tokens are different from sandbox push tokens. Instead, apparently I need a new provisioning profile with Production entitlements, new certs installed on my server, and to re-build my app with said profile so that it knows to create the correct push tokens.
So, after going through all the steps, I can't even make a build run on my phone; XCode says
This profile cannot be installed on devices
Here are the steps I've taken. If I'm missing something please let me know:
*
*In my iOS Developer Center, I've made sure that my AppID is "enabled for production" under the Apple Push Notification Service.
*Also in my iOS Developer Center, I've created my Production Push SSL Certificate, gone through the necessary conversion steps, and installed the resulting .pem on my server.
*Per the instructions, I've create "a new provisioning profile containing the App ID you wish to use for notifications." I've done this by going to Provisioning, and clicking on the "Distribution" tab, and making a new profile. I've confirmed that "production" is set under the "entitlements" section of this profile.
*I've selected the provisioning profile in my project settings. I get the message
This profile cannot be installed on devices
and I'm stuck.
A: Build an ad-hoc distribution version of your app, and install it on your own device. That will use the production APN gateway and certs.
A: You cannot install an app compiled with a appstore distribution (production) profile on a device. Only Apple reviewers can do that. you can only test push on an app compiled in development mode and using sandbox server.
If you want to test production servers, you must compile the app using an AdHoc distribution profile enabling the devices you want to do the test. Clearly you must recompile and the send the app for review using the App Store distribution profile.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: grails for each I am trying to use groovy to create a list of items that is three items across and n number of items down. right now, my script is just one item across and n items down. here is what i have so far:
<g:each in="${Friends}" status="i" var="Friends">
<div style="position:relative; border:1px solid red; height:150px;width:150px">
<img src=${Friends[3]} ><br>${Friends[1]} <br>${Friends[2]} <br>
<input type="checkbox" name="email" value=${Friends[0]} />
<input type="hidden" name="fname" value=${Friends[1]}>
</div>
</g:each>
So, for each item in ${Friends}, I want to display it on the web page but i want it to be displayed in a grid that is three items across and n/3 items down.
thanks for your help
jason
A: If I understand you correctly, just add the equivalent of
if i % 3 == 0 { print a <br/> }
as the first statement in your loop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Static array of method pointers I'm facing an error I dont understand.
I try to create and use a static array of method pointers. The declaration in my class looks like this:
static void (Client::*packetHandler[Op::handledOpcodeMax - Op::handledOpcodeMin + 1])(QByteArray &data);
Initialization takes place in my .cpp files is like that:
void (Client::*packetHandler[Op::handledOpcodeMax - Op::handledOpcodeMin + 1])(QByteArray &data);
Here comes the troubles, in one of my Client's class method I try to use this methods pointers' array.
I tried several ways, for example :
(this->*packetHandler[_opcode])(data);
I said I didnt understand the problem, let me explain why. Running make on my code results in a proper compilation, tought, there is a problem when linking.
client.cpp:71: undefined reference to `Client::packetHandler'
This message is repeated 5 times.
Any help would be welcome.
Thank you.
A: void (Client::*packetHandler[Op::handledOpcodeMax - Op::handledOpcodeMin + 1])(QByteArray &data); declares a global variable named packetHandler. You want to define your class variable, which needs an extra Client:: like so:
void (Client::*Client::packetHandler[Op::handledOpcodeMax - Op::handledOpcodeMin + 1])(QByteArray &data);
A: Client::*packetHandler is a member function pointer that points to a member function named Client::packetHandler. I'm not sure how to make a member function pointer that points to an arbitrary member function which is what you seem to want to do. I think George is right. You should consider using something like boost::function or std::tr1::function or write your own member function wrapper class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Defining text selection highlight with CSS I'm having problems designing a CSS for a website I'm making. It's similar to the one shown in this pic:
.
How can I make it so that when a user selects and blocks the text, the areas on its right and left don't get selected as well? In my case, I've tried wrapping the tag-containing text (and <article> tag) inside a <div> but I don't see any change.
A: I know this is pretty old, but I thought I'd chime in just in case my solution might help anyone the future.
I had the same issue occurring where the text selection was including the padding within a div element. I tried @Joseph Marikle's solution; however, I had other elements being floated that were problematic with the float solution and using absolute positioning was not an option.
I then tried looking for ways to remove the elements (p elements in my case) from the page flow. I landed on this SO question and decided to try relative positioning on my p elements and it seemed to produce the desired effect.
Here is a CodePen demonstrating the results. The second p element has relative positioning applied to it and the text selection is constrained.
A: mgunadi and welcome to SO
What's happening here is you have a centering method that leaves a margin. when you highlight the text in your browser, it also selects the margin. this can be fixed to some degree by changing the way you center your content. For instance, if you use a position:absolute solution, this margin is not needed and is not selected on highlight. (demo: http://jsfiddle.net/FX45g/). Unfortunately, if this is not an option and you must use a margin to center the content, then this is a browser issue and depends entirely on how a particular browser handles it.
to center content with positioning the content must be of a fixed width (for this example 300px). then you can apply the following rule:
.centered
{
position:absolute;
left:50%;
margin-left:-150px;
}
EDIT
Found another way. :P a wrapper! (with the help of a float)
http://jsfiddle.net/hSpBw/
.wrapper{margin:0 auto; width:300px;}
.wrapper>div {float:left;}
A: CSS does not provide this feature. It's a function of the browser itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: When updating Marking entity datetime property unchanged I have this entity service in my domain model with two datetime type properties entrydate and updatedon.
When user in edit view make any changes and submit form back I want entrydate property of the postedback/modified object to be marked as unchanged so entrydate can't be overwritten when performing updates.
public class Service
{
public int ServiceID
{
get;
set;
}
[Required(ErrorMessage="Please enter Name")]
public string Name
{
get;
set;
}
[Required(ErrorMessage="Please enter the duration for the service")]
public short Duration
{
get;
set;
}
[DataType(DataType.Date)]
public DateTime EntryDate
{
get;
set;
}
[DataType(DataType.Date)]
public DateTime UpdatedOn
{
get;
set;
}
public decimal Cost
{
get; set;
}
}
Repository method that is persisting changes into db is as follows:
public void InsertOrUpdate(Service service)
{
if (service.ServiceID == default(int)) {
// New entity
context.Services.Add(service);
} else {
// Existing entity
context.Entry(service).State = EntityState.Modified;
}
}
A: You can reload the original entity from the database:
else {
// Existing entity
var serviceInDb = context.Services.Find(service.ServiceID);
service.EntryDate = serviceInDb.EntryDate;
context.Entry(serviceInDb).CurrentValues.SetValues(service);
}
When you call SaveChanges later an UPDATE statement only for properties which have really changed will be sent to the database (has also benefits for other unchanged properties).
Or just reload the EntryDate:
else {
// Existing entity
var entryDateInDb = context.Services
.Select(s => s.EntryDate)
.Single(s => s.ServiceID == service.ServiceID);
service.EntryDate = entryDateInDb;
context.Entry(service).State = EntityState.Modified;
}
Another working but ugly approach is this:
context.Services.Attach(service); // thanks to user202448, see comments
context.Entry(service).Property(s => s.Name).IsModified = true;
context.Entry(service).Property(s => s.Duration).IsModified = true;
context.Entry(service).Property(s => s.UpdatedOn).IsModified = true;
context.Entry(service).Property(s => s.Cost).IsModified = true;
So, don't set the EntryDate property to modified but all the other properties one by one.
The approach which comes into mind ...
context.Entry(service).State = EntityState.Modified;
context.Entry(service).Property(s => s.EntryDate).IsModified = false;
... unfortunately doesn't work because setting back a property to not-modified which is already marked as Modified is not supported and will throw an exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Corona sdk app runs great on emulator, but not when uploaded to Droid I have been working a platforming game for about three months. I had the game working fine, and it worked fine on the Droid when uploaded. Recently, I worked on using director.class and a display group and navigating from the menu to the game using director:changeScene(). This works fine on the emulator with no error messages, but when uploaded to the Droid, the main menu loads just fine, but when I touch a button to load the lua file for the game, the screen goes black and nothing happens. I even un-installed several apps in case it was a memory problem, but that didn't change anything. Any help in what I am missing would be appreciated.
A: After much searching, I found the answer to my problem: The Corona emulator isn't case sensitive, but the Droid is case sensitive. I found that most of my .png files had uppercase extensions. As an example, pillar.png was actually pillar.PNG in the folder. Apparently, my graphic editor stores the file extension in uppercase by default. When viewing it with Windows Explorer, it wasn't obvious. I viewed them from the command prompt window and found the problem. Also any requires must be exactly the case as the filenames. After making this simple change, the apk deployed on the droid just fine. Also in my searching the forums, I found some other tips. The latest builds of Corona sdk have a problem with files stored in sub directories. Keep all your files in the same directory if you expect to deploy to a Droid.
Jerry
A: I had similar problem and thanks to @Jerry for pointing out images.
In my case image i included had resolution more than 2048 * 2048 (Maximum resolution allowed by Android as of now)
And reducing the image resolution solved the issue for me.
Kudos!!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Accessing child/nested movie clips with JSFL AS3 CS5.5 How can I access a movie clip's children (specifically child movie clips) in jsfl?
I am already at the instance level from
flash.documents[0].timelines[0].layers[0].frames[0].elements[0].instance
I've found this documentation but not much else.
Thanks in advance.
A: The thing to remember in JSFL is that elements on stage are also items in the library, so it doesn't matter how many times you have something nested, it's still a clip in the library, and often that's the thing you want to work from.
In your case it would be:
// break up your previous path to illustrate the "timeline" point
var timeline = flash.documents[0].timelines[0];
// grab the element
var element = timeline.layers[0].frames[0].elements[0];
// get its associated library item (same instance, just a Library Item, not a stage Element)
var item = element.libraryItem;
// then grab the library item's "timeline" property
var childTimeline = item.timeline
// and you can now access any "nested" elements on it
trace(childTimeline.layers[0].frames[0].elements)
It does seem counter-intuitive at first, but you soon get used to it. The easiest way to think about it is that essentially all elements are "top level" as they all live in the library.
Also, fl.getDocumentDOM().getTimeline() is the usual way to get the current document & timeline.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Windows Forms: Is there a way to wait for all pending Invokes to a Control to end? I need to do this in order to solve a deadlock.
My Windows Forms Control has a reference to a C++/CLI class which wraps a C++ native class. The native class makes callbacks to the C++/CLI class, which maps them to events handled by the form. These callbacks are called from a thread which runs all the time.
When I want to dispose the control, I unregister all events, so that the native class can't call back anymore. Once that's done, I dispose the C++/CLI wrapper, which in turn destroys the native class. In the native class destructor, I signal the thread to end using a Windows event, and wait indefinitely for the thread to end.
However, if the thread was in the middle of a callback when the disposal starts, he might be stopped in a Control.Invoke, and deadlock ensues. Hence the title question. Is this possible? If it were so, I could proceed this way:
*
*Unregister all events (native thread won't be able to call back anymore)
*Wait for all pending .Invokes to finish
*Dispose C++/CLI wrapper
*
*Destroy C++ native class
*
*Signal thread to end
*Wait for thread to end (can't deadlock with an Invoke since all of those finished and no more of them could have been fired since events were unregistered)
*Bliss
I'm open to other suggestions for solving this problem
A: Option 1: Process pending callbacks via Application.DoEvents after removing the event handlers but before the destructor. Note the documentation says this handles Windows messages and does not mention if this forces processing of Invokes.
Option 2: Do not block the event thread: Call your form callbacks via BeginInvoke. Note that you might get events after the C++ object is destroyed, so add additional logic to the event handlers to ensure the C++ object has not been destroyed.
FYI, BeginInvoke and Invoke both use this function. BeginInvoke sets synchronous to false. Note that I hacked this method up a bit to remove the uninteresting portions:
private object MarshaledInvoke(Control caller, Delegate method, object[] args, bool synchronous)
{
ThreadMethodEntry entry = new ThreadMethodEntry(caller, method, args, synchronous, executionContext);
lock (this.threadCallbackList)
{
if (threadCallbackMessage == 0)
threadCallbackMessage = SafeNativeMethods.RegisterWindowMessage(Application.WindowMessagesVersion + "_ThreadCallbackMessage");
this.threadCallbackList.Enqueue(entry);
}
UnsafeNativeMethods.PostMessage(new HandleRef(this, this.Handle), threadCallbackMessage, IntPtr.Zero, IntPtr.Zero);
// BeginInvoke just takes this branch instead of waiting for completion
if (!synchronous)
return entry;
if (!entry.IsCompleted)
this.WaitForWaitHandle(entry.AsyncWaitHandle);
if (entry.exception != null)
throw entry.exception;
return entry.retVal;
}
A: There is no possibility of responding to the form closing event and wait for the thread to finish. There's an unsolvable threading race condition. And very good odds for deadlock, DoEvents would break it but is too ugly.
Implement the FormClosing event and tell the class to stop running its thread. And cancel the close. The thread should raise an event just before it exits. Use BeginInvoke() in the event handler to marshal that call to the main thread.
Now you have a guarantee that all invokes are completed since they are ordered. Furthermore, you have a guarantee that the thread can no longer generate any more events so no more invokes are coming and it is safe to unsubscribe the events (not actually necessary). Set a flag that a real close is now possible and call Close() to actually close the form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySql get updates since last NOW() asynchronous problem I am having trouble, I am trying to get updates from a messages table for my web chat. To do this I store the last datetime in a session and try to get messages sent between last datetime and now.
However, it is missing some messages and I cannot figure out why. Is there something wrong with my mysql datetime comparison?
If I refresh the page it resets the session variable and all messages display. In javascript I call the web method every 2 + callback seconds.
private string LastNow
{
get
{
return Session["last_now"] as string ??
(string)(Session["last_now"] = string.Empty);
}
set
{
Session["last_now"] = value;
}
}
[WebMethod(EnableSession=true)]
public object GetMessages(int id, int roomId)
{
string lastDt = LastNow;
/* EDIT */
string now = MySqlHelper.ExecuteScalar(
connstr, "SELECT CAST(NOW() AS CHAR);") as string;
// if the session variable is null or empty,
// get all messages up to now, else most recent
string dtclause =
!string.IsNullOrWhiteSpace(lastDt) ?
string.Format(" AND sent_dt > '{0}' AND sent_dt <= '{1}'", lastDt, now) :
string.Format(" AND sent_dt <= '{0}'", now);
string sql =
string.Format(
"SELECT user_id, type, message FROM Chat.Message WHERE room_id={0}{1};",
roomId, dtclause);
object ret = null;
try // with a finally, always store last update time
{
using (DataSet msgset =
MySqlHelper.ExecuteDataset(Common.SupportDatabase, sql))
{
DataTable msgtable = msgset.Tables[0];
if (msgtable != null)
{
DataRow[] rows = msgtable.Select();
if (rows != null && rows.Length > 0)
{
ret = from msg in rows
select new
{
id = msg["user_id"],
type = msg["type"],
message = msg["message"]
};
}
}
}
}
finally
{
LastNow = now;
}
return ret;
}
A: There shouldn't be any reason to do the date parsing in your code. MySQL will already output the now() function in yyyy-mm-dd hh:mm:ss format, so just store the raw string that MySQL returns. DateTime parsing will potentially induce things like timezone and daylight savings conversions, which WILL screw up the timstamps. Instead, just suck out the timestamp, and stuff it back in, unconverted.
A: I suspect that because you are calculating NOW() slightly earlier than doing the query, you're missing some messages that come in between. Try getting the date out of the db in the same query as you are getting the messages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you yank X number of characters in vim? I know I can cut 5 characters in vim by typing 5x, and I often use this to copy and paste text by doing 5xu then pasting them somewhere else.
I am lazy and would rather just yank the 5 characters so I don't have to undo the cut action.
How can I do this?
A: Found this post because I too wanted to yank x number characters without cutting and learned this while testing.
There may be times when is easier to look for certain characters than to count the number of characters to yank.
Enter the motions t and T.
Think ytx as yank forward to character x
Think yTx as yank backward to character x
A: This is complementing the answer of voithos:
You can also use 5ySpace or y5Space (ty @hauleth for suggestion)
This is useful for me especially when I want to yank just one character:
ySpace
Is easier (for me at least) to find and hit Space than l.
A: Yank supports standard movement commands. Use y5l (<- that's a lowercase L)
And if you want to yank 5 characters backwards, use y5h.
Now, if you're feeling really lazy, remap this particular sequence to a key-combination, like so:
:nnoremap <C-l> y5l
In this case, "yank 5 to the right" gets mapped to Ctrl+L (lowercase L).
If you'd like, you can also use Space instead of L to yank characters in the forward direction (examples: ySpace for a single character or 5ySpace for 5). Some people may find it to be quicker or easier than hitting L.
A: y5 will do it. yy yanks lines, y yanks characters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "68"
} |
Q: load image after upload in asp.net 4.0 My question is image uploading , uploading and image load method are working perfect but im showing images below the upload control, after click upload button new image must be added to line.. what is the reason?
this is uploading code:
DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(@"~/Bailiffs/BailiffImages/"));
string cukurNumber = txtCukurNumber.Text;
int sequence = 0;
string fileName = string.Empty;
FileInfo[] fileInfos = directoryInfo.GetFiles(cukurNumber + "*");
if (afuImage.HasFile)
{
if (fileInfos.Length != 0)
{
for (int i = 0; i < fileInfos.Length; i++)
{
string fileNumber = fileInfos[i].Name.Substring(fileInfos[i].Name.LastIndexOf("-") + 1, fileInfos[i].Name.LastIndexOf(".") - fileInfos[i].Name.LastIndexOf("-") - 1);
sequence = int.Parse(fileNumber) + 1;
}
fileName = cukurNumber + "--" + sequence + ".jpg";
}
else
{
fileName = cukurNumber + "--1.jpg";
}
afuImage.PostedFile.SaveAs(Server.MapPath(@"/Bailiffs/BailiffImages/" + fileName));
CreateImages(); // recreates images
}
thx...
A: Use ajax to call a page method which retrieves the url of the image just uploaded and shows it in an img tag. Ajax and Jquery are your tools and friends.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to get a custom control to display the correct language in the VS Editor when a different language is selected I know this sounds knit picky but I have several custom controls that have been translated. When I use those controls on a Form and then change the language they still display the default language. When the application is running, the correct language is shown, but this gives the impression that parts of the form are not translated, plus in some circumstances it affects the layout of the form that can not be seen until run time.
A: One way is overriding the OnPaint event of the Custom Control. Or you will have to translate the resx by using a proper resx Editor like this or this.
For example...
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
this.Text = CustomGlobalResources.GetItem(this.Tag.ToString());
}
Here is an interesting addin for visual studio.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: IIS7 URL rewrite error This is my url: http://www.domain.com/advertenties/advertentie-delen/?id=23&t=1&url=ad-placed-for-simons-company-by-me
With the rewrite rule below I get this error: "The page cannot be displayed because an internal server error has occurred"
<rule name="share ad">
<match url="^advertenties/advertentie-delen?/?$" />
<action type="Rewrite" url="share_email.aspx?id={R:1}" appendQueryString="true" />
</rule>
A: Found it. It says this "id={R:1}",which means it expects a variable on the match url tag. Since there was no variable it throws an error, this is what I have now:
<rule name="share ad">
<match url="^advertenties/advertentie-delen?/?$" />
<action type="Rewrite" url="share_email.aspx" appendQueryString="true" />
</rule>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: syntax error with KeyError in python 3.2 I'm a beginner using python 3.2 and i have a book whos code is all in python 2.6. i wrote part of a program and keep getting:
Syntax Error: invalid syntax
Then python's IDLE highlights the comma after KeyError in my code:
from tank import Tank
tanks = { "a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Carol")}
alive_tanks = len(tanks)
while alive_tanks > 1:
print
for tank_name in sorted( tanks.keys() ):
print (tank_name, tanks[tank_name])
first = raw_input("Who fires? ").lower()
second = raw_input("Who at? ").lower()
try:
first_tank = tanks[first]
second_tank = tanks[second]
except KeyError, name:
print ("No such tank exists!", name)
continue
A: Instead of
except KeyError, name:
try
except KeyError as name:
Its a difference between Python 2.x and Python 3.x. The first form is no longer supported.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Include or require a vfsStream file Using vfsStream, am I able to require or include a virtual file?
$structure = array(
'classes' => array('Foo.php' => '<?php class Foo {} ?>')
);
\vfsStream::create($structure);
require_once(\vfsStream::url('classes').DIRECTORY_SEPARATOR.'Foo.php');
The code above fails silently under PHPUnit.
Thanks.
A: Have you tried
require_once(\vfsStream::url('root/classes').DIRECTORY_SEPARATOR.'Foo.php');
? The call to vfsStream::create($structure); creates the root directory, and does not use the first entry in $structures as the root directory as there might be more then one element in this array. See also documentation at https://github.com/mikey179/vfsStream/wiki/Createcomplexstructures.
A: In addition to Frank's answer about the incorrect use of url(), there may be a configuration issue. In a stock PHP installation, you have to make sure allow_url_fopen is enabled in your php.ini and allow_url_include is enabled in configuration or your script.
In my case, however, I'm running the Suhosin extension, which ignores these parameters and completely disables url_fopen by default. In order to include/require a vfsStream file, you need to add the vfs:// scheme to Suhosin's whitelist in php.ini: suhosin.executor.include.whitelist = "vfs://"
Thanks to Frank Kleine, the vfsStream maintainer, for helping me track this down.1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: sed: Can my pattern contain an "is not" character? How do I say "is not X"? How do I say "is not" a certain character in sed?
A: [^x]
This is a character class that accepts any character except x.
A: For those not satisfied with the selected answer as per johnny's comment.
'su[^x]' will match 'sum' and 'sun' but not 'su'.
You can tell sed to not match lines with x using the syntax below:
sed '/x/! s/su//' file
See kkeller's answer for another example.
A: There are two possible interpretations of your question. Like others have already pointed out, [^x] matches a single character which is not x. But an empty string also isn't x, so perhaps you are looking for [^x]\|^$.
Neither of these answers extend to multi-character sequences, which is usually what people are looking for. You could painstakingly build something like
[^s]\|s\($\|[^t]\|t\($\|[^r]\)\)\)
to compose a regular expression which doesn't match str, but a much more straightforward solution in sed is to delete any line which does match str, then keep the rest;
sed '/str/d' file
Perl 5 introduced a much richer regex engine, which is hence standard in Java, PHP, Python, etc. Because Perl helpfully supports a subset of sed syntax, you could probably convert a simple sed script to Perl to get to use a useful feature from this extended regex dialect, such as negative assertions:
perl -pe 's/(?:(?!str).)+/not/' file
will replace a string which is not str with not. The (?:...) is a non-capturing group (unlike in many sed dialects, an unescaped parenthesis is a metacharacter in Perl) and (?!str) is a negative assertion; the text immediately after this position in the string mustn't be str in order for the regex to match. The + repeats this pattern until it fails to match. Notice how the assertion needs to be true at every position in the match, so we match one character at a time with . (newbies often get this wrong, and erroneously only assert at e.g. the beginning of a longer pattern, which could however match str somewhere within, leading to a "leak").
A: From my own experience, and the below post supports this, sed doesn't support normal regex negation using "^". I don't think sed has a direct negation method...but if you check the below post, you'll see some workarounds.
Sed regex and substring negation
A: In addition to all the provided answers , you can negate a character class in sed , using the notation [^:[C_CLASS]:] , for example , [^[:blank:]] will match anything which is not considered a space character .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
} |
Q: Force StandardOutputEncoding to UTF8 I'm looking to parse UTF8 characters from the standard output stream of another application in my C# project. Using the default approach, characters outside of the ANSI spectrum are corrupted when read from the process' standard output stream.
Now according to Microsoft, what I need to do is set the StandardOutputEncoding:
If the value of the StandardOutputEncoding property is Nothing, the process uses the default standard output encoding for the standard output. The StandardOutputEncoding property must be set before the process is started. Setting this property does not guarantee that the process will use the specified encoding. The application should be tested to determine which encodings the process supports.
However, try as I might to set StandardOutputEncoding to UTF8/CP65001 the output as read, when dumped to a binary file, shows the same castration of foreign language characters. They are always read as '?' (aka 0x3F) instead of what they're supposed to be.
I know the assumption at this point would be that the application whose output I'm parsing is simply not sending UTF8 output, but this is definitely not the case as when I attempt to dump the output of the application to a file from the commandline after forcing the codepage of the commandprompt to 65001, everything looks fine.
chcp 65001 && slave.exe > file.txt
By this, I know for a fact that the application slave.txt is capable of spitting out UTF8-encoded standard output, but try as I might, I'm unable to get StandardOutputEncoding to do the same in my C# application.
Each and every time I end up dealing with encoding in .NET, I wish I were back in the C++ world were everything required more work but was so much more transparent. I'm contemplating writing a C application to read the output of slave.txt into a UTF8-encoded text file ready for C# parsing, but I'm holding off on that approach for now.
A: The only effect that StandardOutputEncoding has no impact whatsoever on the stdout of the executed application. The only thing it does is set the encoding of the StreamReader that sits on top of the binary stdout stream captured from the application being run.
This is OK for applications that will natively output UTF8 or Unicode stdout, but most Microsoft utilities do not do so, and instead will only encode the results per the console's codepage. The codepage of the console is manually set with the WIN32 API SetConsoleOutputCP and SetConsoleCP, and needs to be manually forced to UTF8 if that's what you'd like to read. This needs to be done on the console the exe is being executed within, and to the best of my knowledge, cannot be done from the host's .NET environment.
As such, I have written a proxy application dubbed UtfRedirect, the source code of which I have published on GitHub under the terms of the MIT license, which is intended to be spawned in the .NET host, then told which exe to execute. It'll set the codepage for the console of the final slave exe, then run it and pipe the stdout back to the host.
Sample UtfRedirector invocation:
//At the time of creating the process:
_process = new Process
{
StartInfo =
{
FileName = application,
Arguments = arguments,
RedirectStandardInput = true,
RedirectStandardOutput = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8,
UseShellExecute = false,
},
};
_process.StartInfo.Arguments = "";
_process.StartInfo.FileName = "UtfRedirect.exe"
//At the time of running the process
_process.Start();
//Write the name of the final slave exe to the stdin of UtfRedirector in UTF8
var bytes = Encoding.UTF8.GetBytes(application);
_process.StandardInput.BaseStream.Write(bytes, 0, bytes.Length);
_process.StandardInput.WriteLine();
//Write the arguments to be sent to the final slave exe to the stdin of UtfRedirector in UTF8
bytes = Encoding.UTF8.GetBytes(arguments);
_process.StandardInput.BaseStream.Write(bytes, 0, bytes.Length);
_process.StandardInput.WriteLine();
//Read the output that has been proxied with a forced codepage of UTF8
string utf8Output = _process.StandardOutput.ReadToEnd();
A: modern .NET option:
Console.OutputEncoding = System.Text.Encoding.UTF8;
Source
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Set custom attached property on StoryBoard I have a storyboard and would like to set the attached property VisualStateUtility.InitialState. I've tried various combinations, but the property never gets resolved.
I get the following error: Cannot resolve TargetProperty (VisualStateUtility.InitialState)
How can I set the value of my custom attached property on the Storyboard?
<ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="(Fully.Qualified.Namespace.VisualStateUtility.InitialState)" Storyboard.TargetName="ExpanderButton">
public static string GetInitialState(DependencyObject obj)
{
return (string)obj.GetValue(InitialStateProperty);
}
public static void SetInitialState(DependencyObject obj, string value)
{
obj.SetValue(InitialStateProperty, value);
}
// Using a DependencyProperty as the backing store for InitialState. This enables animation, styling, binding, etc...
public static readonly DependencyProperty InitialStateProperty =
DependencyProperty.RegisterAttached("InitialState", typeof(string), typeof(VisualStateUtility), new PropertyMetadata(null,OnInitialStatePropertyChanged));
A: This should do the trick
<ObjectAnimationUsingKeyFrames x:Name="animation" Duration="0" Storyboard.TargetProperty="xmlnsAlias:VisualStateUtility.InitialState" Storyboard.TargetName="ExpanderButton">
Notice how a name is added to the animation, the parentheses are removed from the target property name, which is then prefixed with the xmlns alias from the xaml header.
In your code behind you'll have to add this:
InitializeComponent();
Storyboard.SetTargetProperty(animation, new PropertyPath(Fully.Qualified.Namespace.VisualStateUtility.InitialState));
Apparently this last step is required for animating custom attached properties. A real pain if you'd ask me.
A: I ran into this:
http://forums.silverlight.net/t/182227.aspx
Which another user says it's un-supported.
Frank Lan Writes:
Hi,
It's a known issue. And the workaround seems to be: animate the custom attached property from code instead of xaml.
Sorry for any inconvenience caused by the issue.
Frank Lan
Microsoft Online Community Support
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What is the default database mapping type for a String in Grails? If I have a domain object that looks like this:
class Note {
Long id
String content
}
What kind of datatype is "content" going to be mapped to in a database, by default? Is it a varchar? How many characters?
A: varchar(255) is the default without any constraints for a String.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone - change UINavigationController's bar traslucent on stack view I'm trying to change the style of my navigation bar from a not-root view. How can I do that?
I use the:
self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
but doesn't work!
A: This code is fine. It would have to be a problem with another part of the code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ajax create action: partial doesn't update without a page refresh I have a text field in a form_tag on my index page that should create a new "gallery" with ajax. Unfortunatly my partial (which loops through all the galleries) doesn't update without a page refresh.
If I submit two times the form it renders feed until the next to last.
I saw several SO posts but it doesn't seem to give me any answer in this case:
rails-3-ajax-update-partial-doesnt-work-without-page-refresh
rails-3-ajax-newsfeed
Please see my code:
Controller
controllers/admin/galleries_controller.rb
def create
@galleries = Gallery.all
@gallery = Gallery.create(:name => params[:name])
respond_to do |format|
if @gallery.save
format.html { redirect_to admin_galleries_path }
format.js
else
flash[:notice] = "Gallery failed to save."
format.html { redirect_to admin_galleries_path }
end
end
end
Views
create.js.erb
# alert("ajax works"); rendered the alert box correctly
$("#galleries").html("<%= escape_javascript(render(@galleries)) %>");
admin/galleries/index.html.erb
<%= render "form" %>
<ul id="galleries">
<%= render @galleries %>
</ul>
admin/galleries/_form.html.erb
<%= form_tag(admin_galleries_path, :method => :post, :remote => true) do %>
<%= text_field_tag(:name) %>
<%= submit_tag("Create") %>
<% end %>
admin/galleries/_gallery.html.erb
<li><%= gallery.name %></li>
logs
Rendered admin/galleries/_gallery.html.erb (0.6ms)
Rendered admin/galleries/create.js.erb (1.4ms)
Completed 200 OK in 18ms (Views: 7.9ms | ActiveRecord: 3.6ms)
Thanks a lot for your help!
A: I think you need to swap these two lines:
@galleries = Gallery.all
@gallery = Gallery.create(:name => params[:name])
Otherwise, @galleries will not include the newly created Gallery.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: concurrent access to MySQL database using stored procedure I have a stored procedure that will read and then increment a value in the database. This particular procedure is used by many programs at the same time. I am concerned about the concurrency issues, in particular the reader-writer problem. Can anybody please suggest me any possible solutions?
thanks.
A: First, as stated in another post, use InnoDB. It is the default storage engine as of MySQL 5.5 and is more robust.
Second, look at this page: http://dev.mysql.com/doc/refman/5.5/en/innodb-locking-reads.html
You should use a SELECT ... FOR UPDATE to prevent other connections from reading the row you are about to update until your transaction is complete:
START TRANSACTION;
SELECT value INTO @value
FROM mytable
WHERE id = 5
FOR UPDATE;
UPDATE mytable
SET value = value + 1
WHERE id = 5;
COMMIT;
This is better than locking the table because InnoDB does row level locks. The transaction above would only lock the rows where id = 5... so another query working with id = 10 wouldn't be held up by this query.
A: if possible you can lock the table just before calling the SP then unlock immediately after.
i had i similar problem and this is how i circumvented this issue.
example
LOCK TABLES my_table LOW_PRIORITY WRITE;
CALL my_stored_procedure('ff');
UNLOCK TABLES;
A: Use Innodb.
Inside the stored procedure start transaction before do anything else. At the Commit and end the transaction. This will resolve the read/write problem.
But be aware of the fact that it will slow down concurrent operation. It is fine for the case only a few concurrent request are expected at a given time.
A: Create a separate table (or reuse the original if appropriate) for all of the incremental inserts and use a SUM() for retrieval.
If there's still a concern about the number of eventual rows, then use a transaction to sum them into a single row back in the original table periodically. Most likely the trade-off of eventual consistency in the sum (reads lagging the writes) or performance hit in summing rows is less of an issue when compared to the stalls on multiple writers waiting on a lock to a single row.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How do I decompose a Predicate Expression into a query? I have the following class Person, with a custom Where method:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Where(Expression<Func<Person, bool>> predicate)
{
return String.Empty;
}
}
How can I retrieve the Expression parameter names and values in an enumerable manner?
Person p = new Person();
p.Where(i => i.Name == "Shlomi" && i.Age == 26);
For the purpose of building a string query with parameters attached according to the name and value of the expression.
// Eventually I will convert the above into the following:
string Query = "select * from person where name = @Name AND Age = @Age";
SqlParameter[] param = new SqlParameter[] {
new SqlParameter("@Name","Shlomi"),
new SqlParameter("@Age","26")
};
A: The problem is that the Expression is actually a tree.
For example, you have the following predicate:
Expression<Func<Person, bool>> expr = x => x.Name == "Shlomi" && x.Age == 26;
If you inspect expr, you'll see that it's body has "AndAlso" NodeType and it also has two properties for operands -- Left and Right each pointing to another Expression object with "Equal" NodeType which in turn again have two properties Left and Right which point to Expression of type MemberAccess and Constant respectively.
While you can process that tree and extract all information you need, you'll end up implementing your own LINQ2SQL provider, e.g. reinventing a wheel. If you feel so, I hope I provided enough information to start digging...
A: I certainly think you should follow StriplingWarrior's advice and use LINQ to Entities or LINQ to SQL, but for the sake of reinventing the wheel (poorly) I'll build off of a prior answer of mine.
// Start with a method that takes a predicate and retrieves the property names
static IEnumerable<string> GetColumnNames<T>(Expression<Func<T,bool>> predicate)
{
// Use Expression.Body to gather the necessary details
var members = GetMemberExpressions(predicate.Body);
if (!members.Any())
{
throw new ArgumentException(
"Not reducible to a Member Access",
"predicate");
}
return members.Select(m => m.Member.Name);
}
Now you need to walk the expression tree, visiting each candidate expression, and determine if it includes a MemberExpression. The GetMemberExpressions method below will walk an expression tree and retrieve each of the MemberExpressions found within:
static IEnumerable<MemberExpression> GetMemberExpressions(Expression body)
{
// A Queue preserves left to right reading order of expressions in the tree
var candidates = new Queue<Expression>(new[] { body });
while (candidates.Count > 0)
{
var expr = candidates.Dequeue();
if (expr is MemberExpression)
{
yield return ((MemberExpression)expr);
}
else if (expr is UnaryExpression)
{
candidates.Enqueue(((UnaryExpression)expr).Operand);
}
else if (expr is BinaryExpression)
{
var binary = expr as BinaryExpression;
candidates.Enqueue(binary.Left);
candidates.Enqueue(binary.Right);
}
else if (expr is MethodCallExpression)
{
var method = expr as MethodCallExpression;
foreach (var argument in method.Arguments)
{
candidates.Enqueue(argument);
}
}
else if (expr is LambdaExpression)
{
candidates.Enqueue(((LambdaExpression)expr).Body);
}
}
}
A: What you're wanting to do is very complicated, and there are entire frameworks that are built to do this, so you don't have to write the logic yourself. Take a look at LINQ to Entities and LINQ to SQL, e.g.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Opening links in Chrome Extension I have a very small Google Chrome Extension that uses Google Feed API to grab some data.
But the problem is visitors are not able to click on any links. I'd love to get some ideas about how to fix this. Basically any links within the popup.html are not openning in a new tab.
We have manifest.json, popup.html, and 3 icon files
Here is my manifest.json
{
"name": "Gujarati Suvichar",
"version": "0.0.1",
"description": "Gujarati Suvichar from GujaratiSuvichar.com",
"icons": { "16": "gujarat - 16.jpg",
"48": "gujarat - 48.jpg",
"128": "gujarat - 128.jpg" },
"browser_action": {
"default_icon": "gujarat.jpg",
"popup": "popup.html"
}
}
Here is the actual code from popup.html
<style>
body {
min-width:350px;
height:100px;
overflow-x:hidden;
}
#footer {
color: #F30;
}
#footer a{
color: #F30;
}
</style>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0" type="text/javascript"></script>
<body style="font-family: Arial;border: 0 none;">
<script type="text/javascript">
/*
* How to use the Feed Control to grab, parse and display feeds.
*/
google.load("feeds", "1");
function OnLoad() {
// Create a feed control
var feedControl = new google.feeds.FeedControl();
// Add two feeds.
feedControl.addFeed("http://www.gujaratisuvichar.com/feed", "Gujarati Suvichar");
// Draw it.
feedControl.draw(document.getElementById("content"));
}
google.setOnLoadCallback(OnLoad);
</script>
<div id="header">
<div class="container">
<h1>ગà«àªœàª°àª¾àª¤à«€ સà«àªµàª¿àªšàª¾àª°</h1>
</div>
</div>
<style>
.gf-result .gf-author, .gf-result .gf-spacer, .gf-result .gf-relativePublishedDate {
display: none;
}
.gfc-result .gf-title a{
text-decoration:none;
color:#CCC
}
</style>
<div id="content">
<div id="content">Loading...</div>
</div>
<div id="footer">
<span id="footer">More on <a href="http://www.gujaratisuvichar.com/">GujaratiSuvichar.com</a></span> </div>
</body>
A: Put <base target="_blank" /> into popup's <head>.
A: Your popup doesn't have a head. Or <html> tags. Make them.
Then add the
<base target="_blank" />
under your <head>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bulk load data conversion error (truncation) I am getting this error
Bulk load data conversion error (truncation) for row 1, column 12 (is_download)
here is the csv...it only has one row
30,Bill,Worthy,sales,,709888499,bat@bat.com,,"Im a a people person., to work together for this new emerging env.HTTP://applesoftware.com","Bill and Son of Co","Contact Us: Contact Form",0
here is my bulk insert statement...
SE SalesLogix
GO
CREATE TABLE CSVTemp
(id INT,
firstname VARCHAR(255),
lastname VARCHAR(255),
department VARCHAR(255),
architecture VARCHAR(255),
phone VARCHAR(255),
email VARCHAR(255),
download VARCHAR(255),
comments VARCHAR(MAX),
company VARCHAR(255),
location VARCHAR(255),
is_download VARCHAR(255)
)
GO
BULK
INSERT CSVTemp
FROM 'c:\leads\leads.csv'
WITH
(
DATAFILETYPE = 'char',
BATCHSIZE = 50,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
--Check the content of the table.
SELECT *
FROM CSVTemp
GO
The problem is most of the time it works great but in some situations (this being one of them) I get the errors
ANy ideas on what is causing this record to have this error
A:
System.Data.SqlClient.SqlException (0x80131904): Bulk load data conversion error (truncation) for row 97, column 33
For the above error, you can check
*
*Data type size of column(e.g. VARCHAR(255)) is if it is sufficient to import data or not.
*AND the row terminator e.g.
*
*ROWTERMINATOR = '0x0A'
*ROWTERMINATOR = '\n'
*ROWTERMINATOR = '\r\n'
*FIELDTERMINATOR
*
*Make sure the selected field terminator does not occur with in data. If there is a chance of it, then replace it with some other character e.g. | in the file.
A: It's picking up the commas within the comments field as delimiters, because the delimiters are not consistent. The best solution is to insure that all fields are wrapped with double quotes and set FIELDTERMINATOR to '","'. Alternately, replace the commas with something unlikely to be in the comments (like ~) and set FIELDTERMINATOR = '~'.
A: In addition to Wil's comments, it seems like it is seeing all 12 columns, so it may just be that your rowterminator is incorrect. First, make sure that the program that puts these files together is in fact putting a carriage return at the end of the last line; I've had to correct many programs where this wasn't the case. Once you are sure there is a carriage return there, you may have to experiment to see what type of carriage return it is. Sometimes it is char(10) only, sometimes char(13) only, and sometimes it may have both but be in the wrong order. So experiment with:
ROWTERMINATOR = '\n'
ROWTERMINATOR = '\r'
ROWTERMINATOR = '\n\r'
ROWTERMINATOR = '\r\n'
A: i had the header as first row. after i removing it, it was fine.
A: This can be solved easily by using the following in your bulk insert:
FORMAT ='CSV'
This takes care of the commas in a string.
Please select this as answer if it helped you.
A: Be careful if you export/import data from the '.csv' files. Replace all 'NULL' with an empty string.
A: I had exported format files from SQL 2016 with
bcp database1.dbo.table1 format nul -f FMTFLDR\table1.fmt -w -S SERVERNAME -T
and imported data to SQL 2017 with
BULK INSERT database2.dbo.table1 FROM 'DATAFLDR\table1.data' WITH ( FORMATFILE = 'FMTFLDR\table1.fmt');
on a couple of tables for some reason, the export for one of the columns was as SQLCHAR and the truncation error reported. When i manually updated the format file to use instead SQLNCHAR for that field everything was fine.
the table creations is the same in both instances, but i may have a difference in database1 and database2 that i haven't cottoned on to yet :D
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: MEF Not Importing Metadata So, I have exports decorated with metadata attributes but on the container it seems like the Metadata collection of these parts are empty thus not correctly importing a Lazy collection with metadata.
Any thoughts why this is happening?
A: Make sure you configure assemblies for MEF to probe inside your Bootstrapper:
protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
// Need to add self explicitly, otherwise MEF won't know exports we have here
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
// Also adding Model project - this is some project that you reference but not Module
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Model.ModelService).Assembly));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is Google App Engine's Webapp Framework Open Source? Is it available outside GAE? Google App Engine includes this minimal framework called "webapp". Google Code does not list a project page for webapp. The only documentation/information from Google on webapp is in the Google App Engine documentation. Is webapp not usable outside GAE?
A: You could use webapp outside App Engine - there's very little that's App Engine specific - but it's not designed for it, and thus isn't packaged or documented separately. If you want a webapp-like framework you can use anywhere, check out webapp2. It's a very close copy of webapp, with a lot of improvements and extensions. In fact, we (the App Engine team) like it so much it's the official replacement for Webapp on the Python 2.7 platform!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Array multiplication puzzle in ruby I have an array:
x = [1,2,3,4,5]
I want to get:
output = [1,2,6,24,120]
Hope you see the pattern and what I want to accomplish here. x[1] is
transformed into x[1]*x[0]. x[2] => x[2]*x[1]*x[0], etc.
What's the most efficient way to do this in Ruby?
A: You can use e.g. the following code
a=1;output = x.map{|i|a*=i}
A: arr = [1,2,3]
arr.each_with_index.map do |x,i|
arr[0..i].inject(1) { |total,y| total *= y } }
end
A: Here's how I'd do it
prev = 1
puts [1,2,3,4,5].map { |n| prev *= n }
A: 1.9.2 (main):0 > a
=> [1, 2, 3, 4, 5]
1.9.2 (main):0 > a.inject([]) {|arr, e| arr << a[0..arr.size].inject(:*) }
It's a nice way of doing it.
A: This is a pretty general abstraction, usually called scanl in functional languages. A possible Ruby implementation:
module Enumerable
def scanl(&block)
self.inject([]) do |acc, x|
acc.concat([acc.empty? ? x : yield(acc.last, x)])
end
end
end
>> [1, 2, 3, 4, 5].scanl(&:*)
=> [1, 2, 6, 24, 120]
A: You'd probably want to make a recursive solution.
F(x) = if x < 1 return 0
else return A(x) * F(x - 1)
In the simplest mathematical form, where F is your result array, and A is your source array (with indices as x).
A: just for fun
[1,2,3,4,5].map.with_index{|a,i| ar[0,i+1].inject(:*)}
A: x.inject([]) do |result, arr_element|
last_num = result.last
result << (last_num.nil? ? arr_element : last_num * arr_element)
result
end
use inject and pass array as accumulator
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Drop-down navigation menu being overlapped by lower div Stack,
I'm having difficulty creating a good drop down navigation menu using only css. The menu is simple, it needs to only have a few things in it, and only needs to drop down (no need to go down and over etc).
The menu is somewhat working, but whenever I hover over it to drop it down, the menu gets overlapped by the wrapper div directly below the header div where the menu is located. I've tried setting the z-index of the drop down menu to like 20000 and it is still being overlapped.
Here is a direct link to the test page I am working on:
http://www.lolbrary.com/workspace/dropdownheader.php
Any ideas?
Thanky,
billmalarky
A: In #fullheaderbar and #profilemenu you need to remove overflow:hidden; and in .profile-menu ul you need to change position:relative to position:absolute;
then tweak from there :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Get the value of a datatype from Class of Project2 to Class of Project1? - Visual Studio 2010 C# I have 1 solution consisting of 2 projects. 1 is Windows Application and the other is Class Library. In the class library, there's a class that the value of its datatype is needed by the Windows Application. I came up with this,
//Proj2
public class class1
{
bool data1; //supossed to be true but false in default
public void method()
{
if (condition)
data1 = true;
}
}
//Proj1
public class class2
{
bool data2; //must be equal to data1
public void method()
{
Proj2.Class1 class1 = new Proj2.Class1();
data2 = class1.data1
if (data2 == true)
MessageBox.Show(data2.ToString());
}
}
The Problem is, The output is always showing False instead of true. I'm sure 100% that the condition returns TRUE because I tested it. I think the problem is the new instance, the datatype is reset to default which is false. So how do i get the original value. Note: There are two projects. Thank you!
A: It looks like you're missing the call to proj1.class1.method that would set data1 to true
So it should be
public void method()
{
Proj2.Class1 class1 = new Proj2.Class1();
class1.method();
data2 = class1.data1;
if (data2 == true)
MessageBox.Show(data2.ToString());
}
I think the problem is the new instance
Now perhaps you don't want to call class1.method() every time Class2.method is called. If this is true you'll probably want to look at implementing a singleton. Then it would just be
public void method()
{
data2 = Proj2.Class1.Instance.data1;
if (data2 == true)
MessageBox.Show(data2.ToString());
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use SAX on this xml file I have an XML file that I am trying to parse with Sax (this is my first time doing this). I've researched how to implement the parser, and that all makes sense, but I'm unsure of the best way to tackle this problem.
I have scattered pieces of related data (two Facts are associated by a FactKey). In the example below, Foo has a value of 5.34.
Sax calls StartElement() on every new element, so that is one call for Facts and one call for Value....so my questions are: Do I have to store FactKey from the Facts element so I can associate it with the Value element on the next pass, or is there a way for Sax to do that automatically?
And is there any facility built in for associating two different Facts with the same FactKey, perhaps if I used DOM instead of Sax? Or is that just wishful thinking, and I actually just need to maintain a multimap or something.
...
<Facts FactKey="2832154551" FieldId="73250">
<Value xsi:type="xs:double">5.3499999</Value>
</Facts>
...
<Facts FactKey="2832154551" FieldId="410288">
<Value xsi:type="xs:string">Foo</Value>
</Facts>
A: You can use SAX to do this sort of thing, but you will probably find it gets tedious quickly. SAX is a basic building block sort of tool. Assuming your documents are less than 20 MB or so, you will almost certainly find it more convenient to load the entire document in memory and process it using more powerful tools. DOM is a bit tedious to program against too, mostly because its API is poorly designed, but has the virtue that you can run XPath expressions against it, effectively letting you find all nodes with a certain key value. You might find that other tree APIs like JDOM, XOM and DOM4J are more to your liking. However ultimately you will probably end up wanting to use a richer programming language like XSLT or xquery. XSLT has a built in "key" directive that will let you define an index for rapid lookup of items based on keys like those you describe, and provides a rich programming environment for processing XML.
A: For your first question: yes, you have to maintain any context that is used by the parser (ie, you have to keep track of the fact that you are in/not-in a Facts element).
As for associating different Fact elements by key, yes, with caveats. You can load the file into DOM (assuming that you have enough memory), then use XPath to extract all elements with a specific FactKey.
//Facts[@FactKey="2832154551"]
However, if you want to read the file and accumulate Facts with the same key, then a multimap is your best bet. A DOM parser may still be useful, as you could have a multimap that associates the string keys to Element values.
A: I've used dom and from just reading up about sax I don't think that either can do what you're asking.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Enum type naming conventions in DTO's I'm creating an application facade in front of my domain model and using dto's for the exchanges between the consumer and the facade.
In order to avoid having to fully qualify my namespaces where I'm mapping between dto's and the domain model, I've suffixed all my dto's with Dto. Ie. CustomerDto, AddressDto etc.
I need to define an enum type as part of my dto's as well and am struggling with whether I should use the Dto suffix on my enum type.
I'm curious what others have done with enum types that reside in their dto's. Any feedback is appreciated.
Thank You
A: Assuming you're talking about an enum type when you say "enumeration," I wouldn't suffix it with Dto, since that's not really what it is. For example, I wouldn't say CustomerTypeDto since it's not a DTO representing a customer type. However, it is an enum representing the type for a CustomerDto, so maybe CustomerDtoType would be appropriate.
A: Personally I would just use a seperate namepspace and the same name for the enumeration type. I think it's important keep the two seperate so that the external one is just a use case projection of the model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How can I apply classes to images based on their aspect ratio with PHP? I'm working on a drupal6 site and I've got a page that shows thumbnail images (linked to full node content).
The images are currently allowed to have a dynamic width based on the parent div, and are both vertical and horizontal.
the problem I'm having is that there is a max-width applied to these images, which crushes my horizontal images.
the question I have is: how can I use PHP to get the image element which has a unique ID, discover if it is horizontal or vertical and apply a CSS class based on the image's aspects.
I'd need to either put this in my template.php as a pre-process, or in my page.tlp.php.
I can't use Jquery/javascript because I can't risk the FOUC. I also and developing this site as a multi-site drupal instal per instructions, and I'm not allowed to have anything outside my own site directory folder.
I've looked at getimagesize() and getElementsByTagName() but I'm just not sure how to put it together as my PHP is pretty limited. I'm hoping that someone here can point me in the right direction VS giving my the answer.
Thanks
Stephanie
A: Basically use getimagesize to extract the width and the height of the image. Then compare the two. If width is bigger than height, print image-horizontal, else print image-vertical. Here is a sample code that will do the job. It uses list to get just the first two elements of the returned by getimagesize array which are the widht and the height. Then inside the echo statement, we do the check and print the appropriate class:
list($width, $height) = getimagesize($your_full_path_to_image);
echo '<img src="'.$your_url_to_image.'" class="'.(($width > $height) ? 'image-horizontal' : 'image-vertical').'" />';
A: As a follow up, I'm sorry to say I never got this working in the way I'd laid out in my original question.
I'm not sure if it wasn't possible, not possible in my specific instance, or if I was simply unable to figure it out.
I ended up using straight css to do the scaling and faked a consistant width by adding backgrounds
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: xslt 1.0 string replace function I have a string "aa::bb::aa"
and need to turn it in to "aa, bb, aa"
I have tried
translate(string,':',', ')
but this returns "aa,,bb,,aa"
How can this be done.
A: A very simple solution (that will work as long as your string value doesn't have spaces):
translate(normalize-space(translate('aa::bb::cc',':',' ')),' ',',')
*
*translate ":' into " "
*normalize-space() to collapse multiple whitespace characters into a single space " "
*translate single spaces " " into ","
A more robust solution would be to use a recursive template:
<xsl:template name="replace-string">
<xsl:param name="text"/>
<xsl:param name="replace"/>
<xsl:param name="with"/>
<xsl:choose>
<xsl:when test="contains($text,$replace)">
<xsl:value-of select="substring-before($text,$replace)"/>
<xsl:value-of select="$with"/>
<xsl:call-template name="replace-string">
<xsl:with-param name="text"
select="substring-after($text,$replace)"/>
<xsl:with-param name="replace" select="$replace"/>
<xsl:with-param name="with" select="$with"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
You can use it like this:
<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="'aa::bb::cc'"/>
<xsl:with-param name="replace" select="'::'" />
<xsl:with-param name="with" select="','"/>
</xsl:call-template>
A: You can use this
Syntax:- fn:tokenize(string,pattern)
Example: tokenize("XPath is fun", "\s+")
Result: ("XPath", "is", "fun")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Permission on facebook fan page I am a newbie with facebook applications.
Ok. I should create a fanpage. This should connect to my Rails application.
So If user is a fan I should show "fan page 1", else i should show "fan page 2".
How could ask permissions on facebook fan page?
Thanks in advance and excuse if you don´t understand my question.
A: You have a couple of options.
The easy one is to use on of the FB apps like Static HTML Tab that lets you put in some HTML (usually an iframe) for the fan, and another for the non fan. Here ar some of the apps:
Static HTML App
http://www.facebook.com/apps/application.php?id=190322544333196
Or a round up (some paid)
http://www.socialmediaexaminer.com/top-10-facebook-apps-for-building-custom-pages-tabs/
Then your second option is to develop it your self. It is not that hard.
In your App Settings there is a field fot your TAB URL. Point that to a file you would like to use as a tab somewhere in the directory of your app. in PHP you_domain.com/app/tab.php
When Facebook loads that URL in a tab it will pass it a signed request that contains basic information about the user Liker or not, Locale etc.
You can extract that data and depending on that information show one piece of content or the other.
Here is a post on how toparse the signed request with rails:
http://qugstart.com/blog/ruby-and-rails/facebook-base64-url-decode-for-signed_request/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: setBackgroundImage forBarMetrics image size? I am fairly new in iOS programming and I am creating my first app.
I have been trying to use the following code to change the navigation bar background image (this is using the new iOS 5 method):
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"gradientBackgroundPlain.png"] forBarMetrics: UIBarMetricsDefault];
It works fine, but my image is 640 x 88 and it looks too big for the bar. It's like the system doesn't want to scale it, or do I need to do it manually? If I scale the image and create a smaller one it looks pixelated in the retina display.
Any thoughts on this?
Any help or response will be appreciated.
Thanks,
Jorge.-
A: Your image gradientBackgroundPlain.png should be 320x44, and create a second image named gradientBackgroundPlain@2x.png with a size of 640x88. Include the @2x image in your bundle, but continue to specify gradientBackgroundPlain.png for the name of the image. The platform automatically chooses the correct size image for use depending on whether there is a retina display present or not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: SQL query to update list of records by looping through a table records and check some logic? I do not want to use cursors for performance reasons.
Input Parameters for stored procedure: arg1, arg2,arg3 & arg4
For example:
Table A > A1 Column and A2 Column,
Table B > B1 Column (A.A1 <=>B.B1) foreign n primary key relation and B2 Column.
I want to update A.A2 value based on the following if condition,
if(arg1 == B.B2 && arg2 == B.B2)
{
Update A set A.A2 = 1 where A.A1 = arg4
}
else{
if(arg1 == 1 && arg3 == B.B2){
Update A set A.A2 = 0 where A.A1 = arg4
}
}
this is simple for one record but the Table A has 1000's records that match A.A1 = arg4 so i have to apply the above logic or case for all records and want to avoid using cursors...how do i do it?
A: Try the below query.
UPDATE tmp
SET tmp.A2 =
(CASE WHEN (tmp1.B2 == arg1 && tmp1.B2 == arg2) THEN 1 WHEN (arg1 == 1 && tmp1.B2 == arg3) THEN 0 ELSE tmp.A2)
FROM
A tmp
INNER JOIN
B tmp1
ON tmp.A1 = tmp1.B1
WHERE
tmp.A1 = arg4
Hope this Helps!!
A: In general, non-specific SQL-92 you could do this:
UPDATE A
SET A.A2 = CASE WHEN B.B2 IN (@Arg1,@Arg2) THEN 1
WHEN @arg1 = 1 AND B.B2 = @arg3 THEN 0 END
FROM A
JOIN B ON A.A1=B.B1
WHERE A.A1 = @arg4
You may need an ELSE before END if you don't want any values falling through (without the ELSE it would set A.A2 to NULL).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's a good architecture/pattern for developing server-side node.js? What's a good architecture/pattern for developing server-side node.js?
I will be using a backbone.js MVC architecture on the front-end, transporting over websockets.
Examples/explanations would be great! Thanks!
A: MVC on the server-side works great, too. Try Express and Socket.IO. Express has an executable called express that should be available if you install from npm. When you run express, it makes a skeleton file structure of a skeleton app. Here's a simple example of an MVC model using Express.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Send server multiple messages? C# I have a quick and dirty question. So as it stands, i have two clients and a server running. I can communicate messages from the clients to the server without any problem. my problem appears when i want to read two messages from the client - rather than just one message.
The error which i receive is: IOException was unhandled. Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Here is my code on the server side:
private static void HandleClientComm(object client)
{
/** creating a list which contains DatabaseFile objects **/
List theDatabase = new List();
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
do
{
bytesRead = 0;
try
{
// Blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception)
{
// A socket error has occured
break;
}
if (bytesRead == 0)
{
// The client has disconnected from the server
break;
}
// Message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("To: " + tcpClient.Client.LocalEndPoint);
Console.WriteLine("From: " + tcpClient.Client.RemoteEndPoint);
Console.WriteLine(encoder.GetString(message, 0, bytesRead));
if (encoder.GetString(message, 0, bytesRead) == "OptionOneInsert")
{
byte[] message2 = new byte[4096];
int bytesRead2 = 0;
**bytesRead2 = clientStream.Read(message, 0, 4096);** //ERROR occurs here!
Console.WriteLine("Attempting to go inside insert)");
Menu.Insert(theDatabase, bytesRead2);
}
Here is my client code:
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("OptionOneInsert");
Console.ReadLine();
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
NetworkStream clientStream2 = client.GetStream();
String text = System.IO.File.ReadAllText("FirstNames.txt");
clientStream2.Write(buffer, 0, buffer.Length);
clientStream2.Flush();
ASCIIEncoding encoder2 = new ASCIIEncoding();
byte[] buffer2 = encoder2.GetBytes(text);
Console.WriteLine("buffer is filled with content");
Console.ReadLine();
When the client sends the message "optionOne" it is received by the server just fine. It's only when i attempt to send the string called "text" that the issues appears!
Any help would be greatly appreciated - I'm not all that familiar with Sockets, hence i've been struggling with trying to understand this for sometime now
A: You've got a big problem here - there's nothing to specify the end of one message and the start of another. It's quite possible that the server will receive two messages in one go, or half a message and then the other half.
The simplest way of avoiding that is to prefix each message with the number of bytes in it, e.g. as a fixed four-byte format. So to send a message you would:
*
*Encoding it from a string to bytes (ideally using UTF-8 instead of ASCII unless you're sure you'll never need any non-ASCII text)
*Write out the length of the byte array as a four-byte value
*Write out the content
On the server:
*
*Read four bytes (looping if necessary - there's no guarantee you'd even read those four bytes together, although you almost certainly will)
*Convert the four bytes into an integer
*Allocate a byte array of that size
*Loop round, reading from "the current position" to the end of the buffer until you've filled the buffer
*Convert the buffer into a string
Another alternative is simply to use BinaryReader and BinaryWriter - the ReadString and WriteString use length-prefixing, admittedly in a slightly different form.
Another alternative you could use is to have a delimiter (e.g. carriage-return) but that means you'll need to add escaping in if you ever need to include the delimiter in the text to transmit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP MySQL max() function producing 5 I am working on a survey created by PHP and MySQL. So the issue is, I am trying to create a ResponseID, which is an ID specific for every person submitting the survey. So the code was created to add 1 to the existing max value from the ResponseID column. Here's the code:
//Response ID creation
$query = "SELECT max(ResponseID) FROM survey";
$res = mysql_query($query);
$RID = $res+1;
I know I can condense it, but here's the problem: I already entered one item on the table with the ResponseID of 1. When I tested the survey with different answers, the next ResponseID was 5. It should have been 2. So I tested again to see if it would produce 6 next time.
Unfortunately, it produced 5 again. I had my PHP guru looked it over and he said the coding was correct and it should be something from the database. I didn't set anything in the ResponseID except for it being an int. So why is it producing a 5? If anyone could please tell me how to go about fixing it, that would be super cool of you.
I am somewhat new to PHP.
A: $res is a resource, not the value of the query, please read the manual: http://nz.php.net/manual/en/function.mysql-query.php
A: $res will be a mysql statement handle, NOT the result of the query. you still have to actually FETCH a row from this $res result to access the value of the max() function in the query.
This handle probably internally has identifier #5, which is why you're getting that "odd" result.
The code should be:
$sql = "SELECT MAX(responseID) AS max ...";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$RID = $row['max'] + 1;
A: Why don't you use an AUTO_INCREMENT column and retrieve the new value using mysql_insert_id?
A: You need to use an AUTO_INCREMENT column for this. The problem is that if two instances of the PHP script are running at the same time (extremely likely assuming you're using a multithreaded server like Apache), then you could have a case like this:
|PHP #1 | PHP #2 |
=================================
|Accept client |(waiting) |
|SELECT MAX... |(waiting) |
|Send to MySQL | Accept client |
|(waiting) | SELECT MAX... |
|(waiting) | Send to MySQL |
|Get response 4 |Get response 4 | //Nothing inserted yet, max is still 4
|Try to insert 5| (waiting) |
|Succeeded | (waiting) |
|(waiting) |Try to insert 5|
| ... | Failed! |
(This in addition to what Dagon said)
A: Use $row = mysql_fetch_assoc($res) to get the resulting row from your query.
See mysql_fetch_assoc().
A: The reason why you are not getting the correct value is because mysql_query doesn't return a value, it returns a resource.
Try this instead:
//Response ID creation
$query = "SELECT max(ResponseID) FROM survey";
$res = mysql_query($query);
if($res !== FALSE) $res = mysql_fetch_array($res); // If $res === FALSE, something went wrong
$RID = $res[0] + 1;
Also I suggest you to use AUTO_INCREMENT on the ResponseID field, this makes your life a lot easier :)
A: i'm not really sure if i understood ur problem but if u wanna generate a response ID specific to every user or every survey posted, then what u can do is use auto_increment for the response ID. the response id will be incremented every time a new survey is posted. also get the last id posted using mysql_insert_id to get the last id posted.
so u can get the last id using
$last_id = mysql_insert_id ();
u need to put that statement right after ur query. that way u can get the last id.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery - What does this syntax mean? I am looking at jquery.ui-1.8.11.js:
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: 'hasDatepicker',
/* Debug logging (if enabled). */
log: function () {
if (this.debug)
console.log.apply('', arguments);
},
What is that log: function() syntax? What's it called? How can it be used?
A: The second argument to an $.extend call is an Object. They're defined using curly braces {} and take key: value pairs. The value can be a function, which is what is happening for the log.
This is analogous to the following:
var myObject = {
prop1: 'some value',
prop2: 'some other value',
method1: function () {
// some code here.
}
}
You can later call myObject.method1() to perform whatever the code inside the function is.
A: It is extending the object properties on the Datepicker.prototype object.
For example, after that statement is run, you could do:
alert(new Datepicker().markerClassName); // alert('hasDatepicker');
// OR
new Datepicker().log(); // calls the function
Basically, $.extend() allows you to modify an object with additional properties (or overwrite them). Consider the following object:
var obj = { Text: 'Hello World' };
alert(obj.Text); // Hello World
$.extend(obj, {
Text: 'Something Else',
func: function() { alert('Stuff'); }
});
alert(obj.Text); // Something Else
obj.func();
A: This syntax uses JavaScript prototyping to extend a Datepicker object and add additional attributes and functions. This adds Datepicker.log as a function and Datepicker.markerClassName.
A: The second argument (begun with an opening curly brace { and ended with a closing curly brace }) to the $.extend() call is an Object literal. Generally speaking, it's shorthand for explicitly creating an object with new Object. These are roughly equivalent:
var foo = new Object;
foo.bar = 'bar';
and
var foo = {
bar: 'bar'
};
It's also worth noting that the way functions are assigned, they are anonymous functions being assigned as values to properties of the object. As in:
var foo = new Object;
foo.method1 = function() { ... };
It is also possible to use named functions:
function fn1() { ...}
foo.method2 = fn1;
Or:
foo.method3 = function fn2() { ... };
Or:
var foo = {
method4: function fn3() { ... }
};
There are other literals useful for shorthand in JavaScript, such as the Array literal:
var arr = ['members', 'are', 'separated', 'by', 'commas'];
And the RegExp literal (note that parsing a RegExp literal does not have the same escaping rules as passing a string to new RegExp()):
var exp = /some pattern/g; // Modifiers are after the closing slash
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How Google App Engine Java Task Queues can be used for mass scheduling for users? I am focusing GAE-J for developing a Java web application.
I have a scenario where user will create his schedule for set of reminders. And I have to send emails on that particular date/time.
I can not create thread on GAE. So I have the solution of Task Queues.
So can I achieve this functionality with Task Queues. User will create tasks. And App Engine will execute it on specific date and time.
Thanks
A: Although using the task queue directly, as Chris suggests, will work, for longer reminder periods (eg, 30+ days) and in cases where the reminder might be modified, a more indirect approach is probably wise.
What I would recommend is storing reminders in the datastore, and then taking one of a few approaches, depending on your requirements:
*
*Run a regular cron job (say, hourly) that fetches a list of reminders coming up in the next interval, and schedules task queue tasks for each.
*Have a single task that you schedule to be run at the time the next reminder (system-wide) is due, which sends out the reminder(s) and then enqueues a new task for the next reminder that's due.
*Run a backend, as Chris suggests, which regularly scans the datastore for upcoming reminders.
In all the above cases, you'll probably need some special case code for when a user sets a reminder in less than the minimum polling interval you've set - probably enqueuing a task directly. You'll also want to consider batching up the sending of reminders, to minimize tasks and wallclock time consumed.
A: You can do this with Task Queues - basically when you receive the request 'remind me at date/time X by sending an email', you create a new task with the following basic structure:
if current time is close to or past the given date/time X:
send the email
else
fail this task
If the reminder time is far in the future, the first few times the task is scheduled, it will fail and be scheduled for later. The downside of this approach is that it doesn't guarantee that the task will run exactly when the reminder is supposed to be sent - it may be a little while before or afterwards. You could slim down this window by taking into account that your task can run for 10 minutes, so if you're within 10 minutes of the reminder time, sleep until the right time and then send the e-mail.
If the reminders have to be sent out as close in time as possible then just use a Backend - keep an instance running forever and dispatch all reminders to it, and it can continuously look at all reminders it has to send out and send them out at exactly the right time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error receiving data from a WCF Service i have a WCF with several methods: GetAccount, UpdateAccount, DeleteAccont and ListAccount, the first three work well, but ListAccount doesn't.
I get an error:
The ListAccount return a List of Account:
[DataContract]
public class Account
{
private int id;
private String name;
private AccountType accountType;
private Account upperAccount;
private Dictionary<Business, double> porc;
public Account()
{
porc = new Dictionary<Business, double>();
}
[DataMember]
public int Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public String Name
{
get { return name; }
set { name = value; }
}
[DataMember]
public AccountType AccountType
{
get { return accountType; }
set { accountType = value; }
}
[DataMember]
public Account UpperAccount
{
get { return upperAccount; }
set { upperAccount = value; }
}
[DataMember]
public Dictionary<Business, double> Porc
{
get { return porc; }
set { porc = value; }
}
public override string ToString()
{
return name;
}
}
[DataContract]
public enum AccountType : byte
{
[EnumMember]
[Description("Account Type One")]
One = 0,
[EnumMember]
[Description("Account Type Two")]
Two = 1,
}
[DataContract]
public enum Business : byte
{
[EnumMember]
[Description("Business One")]
BusinessOne = 0,
[EnumMember]
[Description("Business Two")]
BusinessTwo = 1,
}
One observation, the list contains 45 items.
Any help will be well received. Thanks
A: You're likely hitting one of the quotas in WCF - the way to find out for sure is to enable tracing at the server, and look at the traces which will contain an exception telling why the server disconnected the client. Without this information there's just a bunch of guesswork we can do: maybe you're hitting the MaxItemsInObjectGraph quota (can increase using the <dataContractSerializer> endpoint or service behavior; maybe the graph has a cycle and you need to enable preserveObjectReferences to deal with it, etc. But only with the traces we'll be able to know for sure.
A: Is your ListAccount method throwing any errors? Rather than returning a list try using the list's .ToArray method and return an Account[]. I assume your GetAccount method returns a single Account object, which means it is serializable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7520786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.