text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Web Page gets cut off I know a lot of people ask questions on this, but I have a spacing problem with my divs.
My main div tag of my web page is 1024px. The problem is that on smaller screens part of my
page gets cut off and you have to scroll horizontally. How do I fix that so that the page will
fit in any window? (especially the smaller ones)
I do not want to use the width:100% property cause I already defined the width as 1024px.
Here is my main div tag's properties:
<div id="main" style=" margin: 0 auto; padding-top: 50px; width:1024px;">
my content.....
</div>
A: A more common width for a Web page is 960px just to avoid the problem you are encountering. Sorry, the only way to fit your page into those smaller screens is to reduce the width for your main div.
A: If you are using a fixed width, in this case 1024px, you cannot make the page fit in any window.
You should have a read of Responsive Web Design which explains how to incorporate flexibility into your design.
A: I'm assuming you don't want it wider than 1024px? If so, set the max-width property on it:
#main {
max-width: 1024px;
}
then, it will fit the screen, but not go larger than 1024.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to handle generics inside a Java "annotation processor"? I asked before for an example "annotation processor" that would generate a Proxy/Delegate for an interface, but got no answer, and did not find anything on the Internet, so I made my own.
So far it worked well, until I tried to use generics inside a super-interface. If I use generics in the annotated interface, it works fine (more by accident than by design). But if the annotated interface extends another interface that takes a generic type parameter, that parameter is not "bound" to the type that the annotated interface use when extending the super-interface. Example:
public interface TestFragment<E> {
void test(E dummy);
}
@CreateWrapper
public interface TestService extends TestFragment<String> {
double myOwnMethod();
}
This would generate:
// ...
public void test(final E dummy) {
wrapped.test(dummy);
}
// ...
instead of the correct:
// ...
public void test(final String dummy) {
wrapped.test(dummy);
}
// ...
The code that generates the parameters in the generated methods look like this:
int count = 0;
for (VariableElement param : method.getParameters()) {
if (count > 0) {
pw.print(", ");
}
count++;
pw.printf("final %s %s", param.asType().toString(),
param.getSimpleName().toString());
}
Is there a way to do this?
A: Have a look at http://docs.oracle.com/javase/6/docs/api/javax/lang/model/util/Types.html#asMemberOf%28javax.lang.model.type.DeclaredType,%20javax.lang.model.element.Element%29
Might be helpful. I used it to solve a very similar problem.
A: This can be quite simple if you follow Ryan Walls suggestion of using asMemberOf
ExecutableType methodType = (ExecutableType) typeUtil
.asMemberOf((DeclaredType) theAnnotatedClass.asType(), method);
int count = 0;
for (VariableElement param : method.getParameters()) {
if (count > 0) {
pw.print(", ");
}
TypeMirror actualParamType = methodType.getParameterTypes().get(count);
pw.printf("final %s %s", actualParamType.toString(),
param.getSimpleName().toString());
count++;
}
A: What you need is substitution, given a map of type variables to type arguments. In this case, E->String. Replace any E in any type with String
There is no such support in javax.lang.model.util.Types, you need to roll your own. Basically
void print(TypeMirror type, Map<TypeVariable,TypeMirror> substitution)
if(substitution.containsKey(type)) // type is a var, E
print( substitution.get(type) ); // String
else if(type instanceof DeclaredType) // e.g. List<E>
print( type.asElement().getSimpleName() ); // List
for(TypeMirror arg : type.getTypeArguments() ) // E
print(arg, substitution)
etc. something like that
A: Copy-paste of my original answer:
This seems to be a common question so, for those arriving from Google: there is hope.
The Dagger DI project is licensed under the Apache 2.0 License and contains some utility methods for working with types in an annotation processor.
In particular, the Util class can be viewed in full on GitHub (Util.java) and defines a method public static String typeToString(TypeMirror type). It uses a TypeVisitor and some recursive calls to build up a string representation of a type. Here is a snippet for reference:
public static void typeToString(final TypeMirror type, final StringBuilder result, final char innerClassSeparator)
{
type.accept(new SimpleTypeVisitor6<Void, Void>()
{
@Override
public Void visitDeclared(DeclaredType declaredType, Void v)
{
TypeElement typeElement = (TypeElement) declaredType.asElement();
rawTypeToString(result, typeElement, innerClassSeparator);
List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
if (!typeArguments.isEmpty())
{
result.append("<");
for (int i = 0; i < typeArguments.size(); i++)
{
if (i != 0)
{
result.append(", ");
}
// NOTE: Recursively resolve the types
typeToString(typeArguments.get(i), result, innerClassSeparator);
}
result.append(">");
}
return null;
}
@Override
public Void visitPrimitive(PrimitiveType primitiveType, Void v) { ... }
@Override
public Void visitArray(ArrayType arrayType, Void v) { ... }
@Override
public Void visitTypeVariable(TypeVariable typeVariable, Void v)
{
result.append(typeVariable.asElement().getSimpleName());
return null;
}
@Override
public Void visitError(ErrorType errorType, Void v) { ... }
@Override
protected Void defaultAction(TypeMirror typeMirror, Void v) { ... }
}, null);
}
I am busy with my own project which generates class extensions. The Dagger method works for complex situations, including generic inner classes. I have the following results:
My test class with field to extend:
public class AnnotationTest
{
...
public static class A
{
@MyAnnotation
private Set<B<Integer>> _bs;
}
public static class B<T>
{
private T _value;
}
}
Calling the Dagger method on the Element the processor provides for the _bs field:
accessor.type = DaggerUtils.typeToString(element.asType());
The generated source (custom, of course). Note the awesome nested generic types.
public java.util.Set<AnnotationTest.B<java.lang.Integer>> AnnotationTest.A.getBsGenerated()
{
return this._bs;
}
EDIT: adapting the concept to extract a TypeMirror of the first generic argument, null otherwise:
public static TypeMirror getGenericType(final TypeMirror type)
{
final TypeMirror[] result = { null };
type.accept(new SimpleTypeVisitor6<Void, Void>()
{
@Override
public Void visitDeclared(DeclaredType declaredType, Void v)
{
List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
if (!typeArguments.isEmpty())
{
result[0] = typeArguments.get(0);
}
return null;
}
@Override
public Void visitPrimitive(PrimitiveType primitiveType, Void v)
{
return null;
}
@Override
public Void visitArray(ArrayType arrayType, Void v)
{
return null;
}
@Override
public Void visitTypeVariable(TypeVariable typeVariable, Void v)
{
return null;
}
@Override
public Void visitError(ErrorType errorType, Void v)
{
return null;
}
@Override
protected Void defaultAction(TypeMirror typeMirror, Void v)
{
throw new UnsupportedOperationException();
}
}, null);
return result[0];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Trouble using XmlSerializer on a class: Object type not primitive I'm getting this error when trying to serialize a class: "There was an error generating the XML document. The type of the argument object is not primitive."
public class TaskData
{
[XmlAttribute("Date")]
public DateTime Date;
public string Summary;
public string Task;
public int Priority; //1 Next, 2 Today, 3 This week, 4 This month, 5 This year.
public bool InProgress;
public TaskData() {}
public TaskData(DateTime date, string summary, string task, int priority, bool inprogress)
{
Date = date;
Summary = summary;
Task = task;
Priority = priority;
InProgress = inprogress;
}
}
public class Tasks
{
[XmlArray("Tasks")]
public List<TaskData> tasks;
public Tasks(){tasks = new List<TaskData>();}
}
static internal void Save(Tasks task)
{
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Save(task, Path.Combine(path, "tasks.xml"));
}
static private void Save(Tasks task, string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(TaskData));
TextWriter writer = new StreamWriter(path);
serializer.Serialize(writer, task);
writer.Close();
}
Does anyone see my mistake? I'm not sure what is causing the error. I'm writing this in Mono 2.10. The Save functions are in another class (which you can't see in the code here).
A: Change
XmlSerializer serializer = new XmlSerializer(typeof(TaskData));
to
XmlSerializer serializer = new XmlSerializer(typeof(Tasks));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Comparison of items in two ArrayLists and return differences I'm currently writing a simple app to compare two lists and return differences if any are found.
Note - [int] imaginary index for the purpose of this explanation
//---------------Prep----------------------------
ArrayList list1 = new ArrayList();
ArrayList storage = new ArrayList();
ArrayList list2 = new ArrayList();
string path = Application.ExecutablePath;
string root = Path.GetDirectoryName(path);
//---------------END Prep------------------------
//---------------Load content into list1------------------------
StreamReader objReader = new StreamReader(root + "/healthy.txt");
string sLine = "";
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
list1.Add(sLine);
}
objReader.Close();
//---------------END Load content into list1------------------------
//---------------Load content into list2------------------------
string[] files = Directory.GetFiles(root, "*.txt", SearchOption.AllDirectories);
foreach (string file in files)
{
storage.Add(file.ToString());
}
foreach (string sOutput2 in storage)
{
list2.Add(GetMD5HashFromFile(sOutput2));
}
//---------------END Load content into list2------------------------
I tried everything, but it seems that I cannot crack this.. How do I ''loop'' through both lists and compare each item side by side in order then return the one's in list two that do not match the control list(list one)?
Logically the program would return ''More work'' as the wrong entry, because both "music" and "more work" are in the third row of their respective lists, they get checked and do not match. List 1 is control, so list 2's entry gets recorded as the odd one out.
Now I have tried it right and left, but I cannot make it happen.. Anyone out there who would be willing to shed some light on this or perhaps even guide me through to the right answer?
Many thanks
EDIT: Added my code for both arrayLists, im only missing the comparison function...
No particular reason for using ArrayList, any suggestions that would make this process easier are very welcome.
A: For starters, let's use a more modern way to read the lines:
IEnumerable<string> list1 = File.ReadLines("file1");
IEnumerable<string> list2 = Directory.EnumerateFiles("folder",
SearchOption.AllDirectories);
And then the list of files from list2 that are not in list1 :
IList<string> difference = list2.Except(list1).ToList();
A: ArrayList diffs = new ArrayList();
for(int i=0;i<N;i++) {
if(!one.Item(i).equals(two.Item(i)) )
diffs.Add(two.Item(i));
}
N = number of items coomon to both lists.
diffs = the arraylist with the odd ones of list two
If you want only the first odd entry from list two , then add a break into the loop. Here , the type of objects in the list is assumed to have defined an appropriate equals(Object obj)method.
A: Between these you can get the results you want.
IEnumerable<object> result = one.ToArray().Intersect(two.ToArray()); //Gives you what is the same
one.ToArray().Except(two.ToArray()); //Gives you wants in one not two
two.ToArray().Except(one.ToArray()); //Gives you wants in two and not in one
A: Here's a simple loop with integers that should work with any version the the framework.
If you have custom objects, here are guidelines for overriding Equals:
http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
ArrayList left = new ArrayList();
ArrayList right = new ArrayList();
left.Add(1);
left.Add(2);
left.Add(3);
right.Add(1);
right.Add(2);
right.Add(4);
bool areEqual = CompareArrayList(left, right);
private bool CompareArrayList(ArrayList left, ArrayList right)
{
if (left == null && right == null)
{
return true;
}
if (left == null || right == null)
{
return false;
}
if (left.Count != right.Count)
{
return false;
}
for (int i = 0; i < left.Count; i++)
{
if (!left[i].Equals(right[i]))
{
return false;
}
}
return true;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In Scala, would the following pattern match prevent excessive garbage collection? I'm doing some heavy database processing and am getting the error message
GC overhead limit exceeded
Caused by
ResultSet getString
In my code I have checks such as the following
val myVal = result.getString("COLUMN")
if (myVal == ...) {}
What I'm wondering is if I change this
result.getString("COLUMN") match {
case ...
}
Does this save a variable from having to be created and garbage collected? Or is this some internal mechanism which means that this happens anyway?
Edit: result is a JDBC ResultSet
A: It will not prevent object allocation. The object is allocated by getString, not by val myVal =. What it may do is free the object sooner, since it will eligible for garbage collection as soon as no one reference it. If you have a myVal pointing to it, that won't happen until myVal goes out of scope.
This may help you, since very short lived objects are very cheap to garbage collect. But, truth to be told, it seems unlikely.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Link ISR to vector interrupt 80x86 32bit AT&T assembly I work on Intel-Atom 32bits (Assembly AT&T).
I want to link my ISR to a vector interrupt 0x33:
push %ebp //save the context to swith back
movl %esp,%ebp
movl $OSTickISR, %eax //address of int 0x33 = address of OSTickISR
movl $0x33*4, %ebx
movl %eax, (%ebx)
pop %ebp //Return to the calling function
ret
When I try to use my int $0x33, nothing happends !!!
What was wrong ?
A: In x86 32 bit, ISR information is stored in an IDT. The IDT is not simply a list of addresses, and is not necessarily stored at the address 0. For a description of the IDT format, see the OSDev Wiki page. The location of the IDT is determined by the OS, and it might not be accessible to user mode software. Assuming you do have the right to modify it, you can get the location of the IDT using the sidt instruction.
sidt -6(%esp)
In 32 bit mode, sidt will store 6 bytes worth of data at the specified location. I used -6(%esp) for my example, which will store the data just below the current stack. The low two bytes are the length of the IDT, in bytes, and the next 4 (in 32 bit mode) are the address of the IDT. Since each IDT entry is 8 bytes long, the location of the entry you want would be 0x33*8 bytes after the start of the IDT. Before modifying the entry, you should ensure the IDT actually contains that entry (it is at least 0x34*8 bytes long).
Here is an example which finds the IDT, ensures it is long enough, and sets the entry for interrupt 0x33.
sidt -6(%esp) // Get the location and size of the IDT
cmpw $0x34*8, -6(%esp) // Make sure the IDT is long enough
jb IDT_too_short // and handle the error if it isn't
mov -4(%esp), %ebx // Get the IDT's address
add $0x33*8, %ebx // and move to the entry for 0x33
mov $OSTickISR, %eax // Get the ISR's address
mov %ax, (%ebx) // Store the low 16 bits of the ISR's address
movw $ISR_CS, 2(%ebx) // Store the code segment which should be used with this ISR
movb $0, 4(%ebx) // This has to be 0
movb $0xEE, 5(%ebx) // See the OSDev link for information on this byte.
// 0xEE is most common for interrupts available from user mode
shr $16, %eax
mov %ax, 6(%ebx) // Store the high 16 bits of the ISR's address
A: An address on x86 consists of a segment and an offset. In real mode, it's segment*16 + offset. In protected mode there's a bit of indirection: the segment register it's really a selector that points to a segment descriptor, which contains the segment base and limit, along with other segment attributes. Instructions that access memory can take an explicit segment specifier (e.g: DS:BX), or else they take an implicit segment which depends on the register used (e.g: if you use SP the implicit segment is SS).
The IVT in real mode is at address 0000:0000, the IDT in protected mode is at address IDT:0000, where IDT can be accessed via LIDT/SIDT instructions.
You should also take into consideration that if you are running over a Virtual Memory Operating System, you don't have direct access to physical memory, the addresses in your program are virtual addresses that get translated to physical addresses after segmentation and paging.
A: Resolved :), as there is a BIOS, it already built the GDT/IDT, so I found the address of IDT using sidt and sgdt instructions, and i added my ISR to sidt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to avoid saving details in database when a new user tries to create account with existing username? I have a jsp page in my project where user fills up the details for creating an account.
when a user enters username and clicks on the check button, the button looks in the database if the same name exists or not(it is able to check because of the servlet code).
If username exists it shows not available.
Now the problem is even if username is not available when user clicks on sumbit button with existing username the details get saved. how to correct this?
(I'm nt able to post image otherwise it would have been more clear.)
A: First, you serlvet accepting the HTTP POST must validate the data sent to it, when the user clicks a button, if the receiver doesn't validate the information then bad data will get into your system regardless of what you do in the JSP.
Some people send raw HTTP POST messages from time to time just for fun (I don't know why :) ) to see if bad data can get into poorly written web applications.
Once the servlet accepting the POST rejects bad data, you can have it redirect back to the offending web page, filled out with the information that was sent in the bad request, perhaps highlighting the offending field or fields.
Later on, if you have the time, you can write up a bunch of javascript to pre-check the fields and deactivate the submit button. This saves the back end servlet the bother of receiving so many bad requests; however, you cannot use such a technique to avoid fixing the back end servlet. There's too many ways your servlet could get the POST message that don't involve your specific javascript code working.
A: Just add an if-else block to your servlet, something like this:
if (usernameExists) {
showError();
} else {
saveUser();
}
Do not do this:
if (usernameExists) {
showError();
}
saveUser();
I'd also add an UNIQUE constraint on the username column in the DB so that your DAO throws an SQLException or like.
See also:
*
*Our Servlets wiki page - contains a basic Hello world example with server-side validation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: File Association - How to insert file name as a command line argument I know how to associate certain file extensions in a deployment project but when one of those files is opened I want to pass the file name to my application to proceed with the correct action.
I can specify what to send as a command line argument in the File Types tab of my deployment project as seen in Img 1.
How can i get the actual file name of the file that was opened to be used as the value of Arguments?
A: Use "%1" in place of "%FileName". Make sure you surround it in double-quotes, so that you properly get filenames with spaces in the name or path. If your app can accept more than one filename, or need more than one parameter, treat them the same way, using "%2" and so forth. Make sure each one is separated from the others by a space, and surround them with double-quote characters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can't define new page mode correctly in Conkeror I can't seem to get even a basic new page mode working in Conkeror.
In my .conkerorrc I have this:
define_page_mode("bz_mode", "BZ");
auto_mode_list.push([/bugzilla/, bz_mode]);
The documentation suggests (at least to me) that this should be sufficient. But when I visit (say) bugzilla.mycompany.com, I don't see the new mode indicated in Conkeror's mode line.
What's the correct way to do this?
A: So it turns out the trick is to say
define_page_mode("bz_mode", $display_name = "BZ");
instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wordpress Max File Upload Problem I have created a wordpress custom post type. I am using custom field template to create fields. I have created a file field to upload images. When I upload files then It work like a charm but only 20 files get uploaded and other files get ignored. I know Its a php configuration and I have override the configuration by putting a php.ini file on my server root. Here is what I have done in it.
max_file_uploads = 300
When I run this command to check the configuration values:
echo "max_file_uploads: " . ini_get('max_file_uploads');
Then in output I get 300. But still I am unable to upload more then 20files in a single post. Am I missing something?
P.S I have a shared server and the files I am uploading have max size upto 1.5KB
A: Check my comment on your question above. Consider having an upload helper like fileuploader. This way, every upload is a request so no limit is reached.
Uploadify allows you to drag&drop files and select multiples files to upload (although they are sent one by one).
A: I had this same problem, although mine was limited to 25. The issue was the default suhosin.upload.max_uploads setting was set to 25, and like PHP versions before 5.3.4, empty upload fields would count towards this total.
The solution was to override the default suhosin.upload.max_uploads setting after it is included in php.ini. Look for the line extension="suhosin.so" and make sure it is somewhere after that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: microsoft sql server datediff for multiple dates I need to find the length of time between 2 dates (datetime types) based on the unique ID. For example, I have the following data:
ID CallID Starttime
1 56 2011-01-04 10:00:00.000
1 67 2011-03-20 12:20:00.000
1 70 2011-04-08 15:00:00.000
2 57 2011-01-14 11:00:00.000
2 62 2011-02-14 11:00:00.000
2 64 2011-02-15 11:00:00.000
2 75 2011-04-14 11:00:00.000
2 78 2011-05-14 11:00:00.000
I need to find the length of time for all the CallIDs for each ID based on the previous call date (starttime). For example, I need the length of time for all the calls for ID 1 (CallID 67 - CallID 56 and CallID 70 - CallID 67, etc.).
I know I need a loop of some kind that would go through the IDs to find the CallIDs for that ID but do I also need a temporary table where I would organize the CallIDs?
Any suggestions would be appreciated. Thank you.
A: One way.
;WITH T
AS (SELECT ID,
CallID,
Starttime,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Starttime) RN
FROM YourTable)
SELECT t1.ID,
t1.CallID,
t2.CallID,
DATEDIFF(HOUR, t1.Starttime, t2.Starttime)
FROM T t1
INNER JOIN T t2
ON t1.RN = t2.RN - 1
AND t1.ID = t2.ID
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is wrong with this XPath? Given that the path /XML/Staff/Content/ContentXML/StaffProfile/Role is correct, and that I have 5 /XML/Staff with only one Staff member with the Role of "Partner"
Why does this match all 5 staff members?
<xsl:apply-templates select="/XML/Staff[Content/ContentXML/StaffProfile/Role='Partner']" mode="List"/>
A: I haven't seen your XML (which you should post for completeness), but I assume Role is an XML element and if that's the case, comparing it to a string won't work. Try this:
<xsl:apply-templates
select="/XML/Staff[Content/ContentXML/StaffProfile/Role/text()='Partner']"
mode="List" />
If Role is an attribute, you need to do this:
<xsl:apply-templates
select="/XML/Staff[Content/ContentXML/StaffProfile/@Role='Partner']"
mode="List" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is SQLite right for my game? I have been looking into different database libraries for my online card game (PostgreSQL, Oracle, etc) and, while SOCI + pg or Oracle are much more powerful, they also are tricky to compile, integrate, and do a whole lot more than what I need to do.
Quite simply these are my requirements:
Store the username, hash, wins, loses, email. Very simple.
The game itself will actually not communicate with the database that often. When the player logs in, I will log them in by retrieving the row by username, and verifying the hash with the hash generated by the password they enter.
Other than that, the server only accesses the database to add a user, record a win or loss after playing a round, or to update personal information.
Given that SQLite supports limited concurrency, this should be fine for my needs even if I have 100 or so card games running concurrently.
Reflecting on the above, is SQLite right for me or should I seriously think of opting for a more complex solution? Bearing in mind that databases are not my strongest point.
Thanks
A: With that many clients SQLite is a perfect fit. However, I would recommend you wrap up this functionality in a simple and not database specific interface, and implement it for SQLite. Once you will get millions of clients along with concurrency/performance issues, you can simply throw in another implementation that uses more powerful database without changing your application code much.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WordPress: Inner-Page Linking, Pages based on Categories I'm trying to decide which method would be best for an internal linking structure that utilizes 4 main categories, and then pages within those categories using WordPress.
At first I thought I could just use Posts as a method of determining whether or not content belonged within that category... but now I'm second guessing myself. The site structure is like this:
High-level nab:
Category 1
*
*Page 1
*Page 2
*Page 3
*Page 4
Category 2
*
*Page 1
*Page 2
*Page 3
*Page 4
Category 3
*
*etc
Category 4
*
*etc
Obviously, this is a custom theme. But before I start coding, I want to make sure that I'm storing, pulling and organizing the data properly.
What are you thoughts? Greatly appreciated!
A: Wordpress is actually designed to be a blog, not a pure CMS. If you do not use the blog function, I suggest trying another 'real' CMS (Joomla, Drupal, TYPO3, many many others).
But to answer your question, why did you reconsider ? It would make it easier to know why your are second guessing...
If you want to accomplish this with the given categories from wordpress, you can use a category to page plugin like this one here. But there are also some CMS plugins for WP that make wordpress to a proper cms and can help you grouping pages - see the plugin resource.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android theme declaration I have a problem. I created new app and publish it to market, but most part of users get ANR with
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
at android.view.LayoutInflater.createView(LayoutInflater.java:505)
... 39 more
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x2/d=0x7f010019 a=-1}
at android.content.res.Resources.loadDrawable(Resources.java:1699)
at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
at android.view.View.(View.java:1998)
at android.view.View.(View.java:1946)
at android.view.ViewGroup.(ViewGroup.java:304)
at android.widget.RelativeLayout.(RelativeLayout.java:173)
... 42 more
In my app I have a two themes that declared in themes.xml. I think I have a mistake in theme declaration. How properly define themes in styles? What difference between
<style name="DarkTheme" parent="android:Theme.Black.NoTitleBar">
and
<style name="DarkTheme" parent="@android:style/Theme.NoTitleBar">
A: <style name="DarkTheme" parent="@android:style/Theme.NoTitleBar">
That theme declaration is correct. The @android tells your software to look inside the Android package for resources. :style means that inside the android package it should look at the styles of that package for the style named after the /.
A: I'm using something similar to the first way of defining the theme parent, i.e.:
<style name="DarkTheme" parent="android:Theme.Black.NoTitleBar">
It works just fine for me. Perhaps try only using that. I've tried both ways and they seemed to work though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Issues with JButtons and ActionListeners So I have a paint program with multiple JButtons, the only way i know how to relate that button with the action of that button being click is to do something like if (e.ActionCommand().equals("Label of the button here"); and if the label matches I know I have the correct action. But here is my problem. I am trying to change my JButtons to be images, so instead of having JButton first = new JButton("Hello"); I am trying to have JButton first = new JButton(new ImageIcon("c:/.....")) and then have the image, This works. However my problem is, is that after this I don't know how to reference the button to make it actually do something. Thanks!!!
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class PaintProgram extends JPanel implements MouseListener,ActionListener
{
public static int stroke, eraser = 0;
private int xX1, yY1 , xX2, yY2, choice ;
public static void main(String [] args)
{
new PaintProgram();
}
PaintProgram()
{
JFrame frame = new JFrame("Paint Program");
frame.setSize(1200, 800);
frame.setBackground(Color.WHITE);
frame.getContentPane().add(this);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu help = new JMenu("Help");
menuBar.add(help);
JMenuItem about = new JMenuItem("About");
help.add(about);
about.addActionListener(this);
JButton button1 = new JButton("Clear");
button1.addActionListener(this);
JButton color = new JButton("Color");
color.addActionListener(this);
JButton erase = new JButton("Erase?");
erase.addActionListener(this);
JButton button2 = new JButton("Empty Rect");
button2.addActionListener(this);
JButton button3 = new JButton("Filled oval");
button3.addActionListener(this);
JButton button4 = new JButton("Filled Rect");
button4.addActionListener(this);
JButton button5 = new JButton("Empty oval");
button5.addActionListener(this);
JButton button6 = new JButton("Line");
button6.addActionListener(this);
JRadioButton thin = new JRadioButton("Thin Line");
thin.addActionListener(this);
JRadioButton medium = new JRadioButton("Medium Line");
medium.addActionListener(this);
JRadioButton thick = new JRadioButton("Thick Line");
thick.addActionListener(this);
ButtonGroup lineOption = new ButtonGroup( );
lineOption.add(thin);
lineOption.add(medium);
lineOption.add(thick);
this.add(button1);
this.add(color);
this.add(erase);
this.add(button2);
this.add(button3);
this.add(button4);
this.add(button5);
this.add(button6);
this.add(thin);
this.add(medium);
this.add(thick);
addMouseListener(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
if(grid == null){
int w = this.getWidth();
int h = this.getHeight();
grid = (BufferedImage)(this.createImage(w,h));
gc = grid.createGraphics();
gc.setColor(Color.BLUE);
}
g2.drawImage(grid, null, 0, 0);
check();
}
BufferedImage grid;
Graphics2D gc;
public void draw()
{
Graphics2D g = (Graphics2D)getGraphics();
int w = xX2 - xX1;
if (w<0)
w = w *(-1);
int h = yY2-yY1;
if (h<0)
h= h*(-1);
switch(choice)
{
case 1:
check();
gc.drawRect(xX1, yY1, w, h);
repaint();
break;
case 2:
check();
gc.drawOval(xX1, yY1, w, h);
repaint();
break;
case 3:
check();
gc.drawRect(xX1, yY1, w, h);
gc.fillRect(xX1, yY1, w, h);
repaint();
break;
case 4:
check();
gc.drawOval(xX1, yY1, w, h);
gc.fillOval(xX1, yY1, w, h);
repaint();
break;
case 5:
if (stroke == 0)
gc.setStroke(new BasicStroke (1));
if (stroke == 1)
gc.setStroke(new BasicStroke (3));
if (stroke == 2)
gc.setStroke(new BasicStroke (6));
gc.drawLine(xX1, yY1, xX2, yY2);
repaint();
break;
case 6:
repaint();
Color temp = gc.getColor();
gc.setColor(Color.WHITE);
gc.fillRect(0, 0, getWidth(), getHeight());
gc.setColor(temp);
repaint();
break;
case 7:
if (eraser == 1)
{
gc.clearRect(xX1, yY1, w, h);
}
else
{
}
break;
}
}
public void check()
{
if (xX1 > xX2)
{
int z = 0;
z = xX1;
xX1 = xX2;
xX2 =z;
}
if (yY1 > yY2)
{
int z = 0;
z = yY1;
yY1 = yY2;
yY2 = z;
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Color"))
{
Color bgColor
= JColorChooser.showDialog(this,"Choose Background Color", getBackground());
if (bgColor != null)
gc.setColor(bgColor);
}
if (e.getActionCommand().equals("About"))
{
System.out.println("About Has Been Pressed");
JFrame about = new JFrame("About");
about.setSize(300, 300);
JButton picture = new JButton(new ImageIcon("C:/Users/TehRobot/Desktop/Logo.png"));
about.add(picture);
about.setVisible(true);
}
if (e.getActionCommand().equals("Empty Rect"))
{
System.out.println("Empty Rectangle Has Been Selected~");
choice = 1;
}
if (e.getActionCommand().equals("Empty oval"))
{
System.out.println("Empty Oval Has Been Selected!");
choice = 2;
}
if (e.getActionCommand().equals("Filled Rect"))
{
System.out.println("Filled Rectangle Has Been Selected");
choice = 3;
}
if (e.getActionCommand().equals("Filled oval"))
{
System.out.println("Filled Oval Has Been Selected");
choice = 4;
}
if (e.getActionCommand().equals("Line"))
{
System.out.println("Draw Line Has Been Selected");
choice = 5;
}
if (e.getActionCommand().equals("Thin Line"))
{
stroke = 0;
}
if (e.getActionCommand().equals("Medium Line"))
{
stroke = 1;
}
if (e.getActionCommand().equals("Thick Line"))
{
stroke = 2;
}
if(e.getActionCommand().equals("Erase?"))
{
eraser = 1;
choice = 7;
}
if (e.getActionCommand().equals("Clear"))
{
System.out.println("Clear All The Things!!!");
choice = 6;
draw();
}
}
public void mouseExited(MouseEvent evt){}
public void mouseEntered(MouseEvent evt){}
public void mouseClicked(MouseEvent evt){}
public void mousePressed(MouseEvent evt)
{
xX1 = evt.getX();
yY1= evt.getY();
}
public void mouseReleased(MouseEvent evt)
{
xX2 =evt.getX();
yY2=evt.getY();
draw();
eraser = 0;
}
A: I would use ActionListener and register the event to your button something like:
yourButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{// your logic here;
}});
As well here is a good link to understand how event listeners work http://download.oracle.com/javase/tutorial/uiswing/events/index.html The way you are trying to handle the events makes your code hard to read and hard to maintain.
A: You have several possibilities:
*
*keep the listener code as is, and call setActionCommand on each button
*use e.getSource() and test if the source is button1, or button2, etc.
*use one separate listener for each button, as shown by Bartzilla
This last method is usually the best one, because each button should be doing something different from the other ones. Having one giant method for all the buttons, with lots of if statements, is not very clean.
Also, naming your buttons fillOvalButton, drawLineButton, etc. would make the code much clearer than with button1, button2, etc.
A: If you want to have an ImageIcon on the JButton and a way to identify it:
JButton b = new JButton(ImageIcon i, String name);
then use
JButton c = (JButton) e.getSource();
if (c.getText()).equals(name);
thats pseudocode but hope it helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iPhone Enterprise App Distribution - Internet Connection Required? I am trying to distribute my Enterprise Application using the method described in the Apple documentation listed here: http://developer.apple.com/library/ios/#featuredarticles/FA_Wireless_Enterprise_App_Distribution/Introduction/Introduction.html
I am hitting the specially crafted itms-services URL, and it prompts me to install my application. If I say yes, the application icon appears and it says "Loading..." and it never finishes. I can hit my ipa file from the plist if I just bring up Safari and manually navigate to the URL. I checked the device log and saw the following errors:
Oct 8 16:28:08 unknown imagent[23] : [Warning] Async loading of bag failed: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x1ed337c0 {NSErrorFailingURLStringKey=http://init.ess.apple.com/WebObjects/VCInit.woa/wa/getBag?ix=1, NSErrorFailingURLKey=http://init.ess.apple.com/WebObjects/VCInit.woa/wa/getBag?ix=1, NSLocalizedDescription=The request timed out., NSUnderlyingError=0x1ed32a00 "The request timed out."}
Oct 8 16:28:08 unknown imagent[23] : [Warning] Bag loading failed! Error (NSURLErrorDomain:-1001): The request timed out. http://init.ess.apple.com/WebObjects/VCInit.woa/wa/getBag?ix=1
I'm not sure if it's related, but my iOS device is on a closed network with no Internet connectivity. Does anyone have any experience with this and know if the iOS device's inability to reach this URL could be what is making my app install hang in the "Loading..." stage?
Thanks for any help you can provide.
A: Yes, your device needs to have access to the internet. iOS reaches out to Apple to verify that your developer certificate and profile are valid.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Transposing music using javascript or jquery I have a chord chart application that I wrote and I would like to allow users to transpose the key of the chart using an onClick handler.
My chart looks like this
{C}My name is Blanket, {F}And I can run fast
The chords inside the brackets appear above the letter it preceeds.
I would like to use javascript or jquery in order to do this. How would I go about creating this transpose button? Any help is appreciated. Thank you in advance.
EDIT
So here's what I came up with...
$('.transposeUp').click(function(){
$('.chord').each(function(){
var currentChord = $(this).text(); // gathers the chord being used
if(currentChord == $(this).text()){
var chord = $(this).text().replace("F#", "G")
}
//... the if statements continue though every chord
//but I didn't place them here to save space
});
});
So here is the problem...
I have a slash chord in the mix (G/B), It changes the be on transpose but because it changes the "B" the chord is now (G/C) which is not the same as the "currentChord" so it doesn't change the G when it gets to its respective if condition. Until I have transposed enough where the Chord is eventualy (G/G) then the first "G" starts transposing leaving the last "G" the same. Any ideas? Again your knowledge and help is greatly appreciated. Thanks in advance.
A: You need to match the chords sequentially so that you can update them one at a time. If you try to match everything at once you'll run into problems like you described, because you keep matching the same chord over and over again.
A good way to accomplish this would be with regular expressions to parse and split the chord. Once you have the matching chord values, use an array of chords to find the next/previous chord to transpose. Here is some sample code I have developed as a demo:
<p><span class="chord">{C}</span>My name is Blanket,</p>
<p><span class="chord">{G / B}</span>And I can run fast</p>
<p>
<input id="transposeDown" type="button" value="Down" /> |
<input id="transposeUp" type="button" value="Up" />
</p>
var match;
var chords =
['C','C#','D','Eb','E','F','F#','G','Ab','A','Bb','B','C',
'Db','D','D#','E','F','Gb','G','G#','A','A#','C'];
var chordRegex = /C#|D#|F#|G#|A#|Db|Eb|Gb|Ab|Bb|C|D|E|F|G|A|B/g;
$('#transposeUp').click(function() {
$('.chord').each(function() {
var currentChord = $(this).text();
var output = "";
var parts = currentChord.split(chordRegex);
var index = 0;
while (match = chordRegex.exec(currentChord))
{
var chordIndex = chords.indexOf(match[0]);
output += parts[index++] + chords[chordIndex+1];
}
output += parts[index];
$(this).text(output);
});
});
$('#transposeDown').click(function() {
$('.chord').each(function() {
var currentChord = $(this).text();
var output = "";
var parts = currentChord.split(chordRegex);
var index = 0;
while (match = chordRegex.exec(currentChord))
{
var chordIndex = chords.indexOf(match[0],1);
output += parts[index++] + chords[chordIndex-1];
}
output += parts[index];
$(this).text(output);
});
});
Sample demo: http://jsfiddle.net/4kYQZ/2/
A couple of things to notice:
*
*I took @gregp's idea of having multiple copies of the key list so that I can handle both sharps and flats. The first scale includes the preferred #/b which will be used during transposing. The second scale includes the other formats so that if the music includes them, they will transpose correctly. For instance, since Eb is in the first scale, it will be used instead of D# as you are transposing up and down; however, if there is a D# in the music to begin with, it will correctly move to D/E (with the caveat that if you move back, it will become an Eb again). Feel free to modify the preferred scale - I used my educated judgment based on personal music experience.
*The regular expression has to have the sharped/flatted keys first, otherwise a C# would be just as easily matched as a C when that's not correct.
*I have C at the beginning and the end of the array so that I can start at any location and move both directions without passing the end of the array. In order for this to work, the transposeDown code has an extra parameter in the call to chords.indexOf to start at position 1 so it matches the last C in the array instead of the first C. Then when it attempts to move to the previous element, it doesn't pass the beginning of the array.
*I'm splitting the chord as well using the regular expression, which is redundant, but it makes it super-easy to recompose the final string back together - by interleaving the original string parts with the updated chord keys (don't forget the last piece at the end!).
*I'm using elements instead of classes for your buttons.
Hope this helps!
Update 1: Per comment by OP, the use of indexOf on arrays is not supported by pre-ie9. This can be solved by using a helper function that does the same thing:
function arrayIndexOf(arr, match)
{
for (var i = 0; i < arr.length; i++)
if (arr[i] == match)
return i;
return -1;
}
And this line
var chordIndex = chords.indexOf(match[0]);
would be replaced with:
var chordIndex = arrayIndexOf(chords, match[0]);
See updated sample demo: http://jsfiddle.net/4kYQZ/11/
A: Using jQuery, you're spoiled for choice for binding click handlers. There's .click(), .delegate(), .live(), and many others. It wouldn't make sense to reproduce what the APIs already tell you, but I can say this: learning how to bind the click is the smallest part of the overall problem, and even capturing the chord name with .text() is going to be trivial once you've had a look at the jQuery API.
The tricky part is going to be the logic of transposing itself. You'll need to take the knowledge you already have (for example, going from E to F is only a half-step; there's no E# or Fb) and make it work as code.
My apologies for general advice rather than code samples, but my advice is to have two arrays, one containing all the chords in terms of sharps, one with all the chords in terms of flats.
You could do a bit of cheating, too: instead of logic to wrap around to the beginning (say, C in position 0), just have your arrays duplicated:
["C","C#","D","D#","E","F","F#","G","G#","A","B","C","C#","D","D#","E","F","F#","G","G#","A","B"]
Then find the first occurence of the chord name, move ahead the desired number of stops, and you'll still have the right string.
A: Call function transpose for up:
text = transpose(text, 1);
Call function transpose for down:
text = transpose(text, -1);
Function:
function transpose(text, amount){
var lines = new Array();
var chord = new Array();
var scale = ["C","Cb","C#","D","Db","D#","E","Eb","E#","F","Fb","F#","G","Gb","G#",
"A","Ab","A#","B","Bb","B#"];
var transp = ["Cb","C","C#","Bb","Cb","C","C","C#","D","Db","D","D#","C","Db","D",
"D","D#","E","Eb","E","F","D","Eb","E","E","E#","F#","E","F","F#",
"Eb","Fb","F","F","F#","G","Gb","G","G#","F","Gb","G","G","G#","A",
"Ab","A","A#", "G","Ab","A","A","A#","B","Bb","B","C","A","Bb","B",
"B","B#","C#"];
var inter = '';
var mat = '';
lines = text.split("\n");
for(var i in lines){
if(i%2===0){
chord = lines[i].split(" ");
for(var x in chord){
if(chord[x]!==""){
inter = chord[x];
var subst = inter.match(/[^b#][#b]?/g);
for(var ax in subst){
if(scale.indexOf(subst[ax])!==-1){
if(amount>0){
for(ix=0;ix<amount;ix++){
var pos = scale.indexOf(subst[ax]);
var transpos = 3*pos-2+3;
subst[ax] = transp[transpos+1];
}
}
if(amount<0){
for(ix=0;ix>amount;ix--){
var pos = scale.indexOf(subst[ax]);
var transpos = 3*pos-2+3;
subst[ax] = transp[transpos-1];
}
}
}
}
chord[x]=subst.join("");
}
}
lines[i] = chord.join(" ");
}
}
return lines.join("\n");
}
The first line is transpose and the second does not, and sequentially.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: jQuery read XML and save for data for access in another plugin I have 2 large XML files:
*
*Car data (id, name, image, etc).
*Deals (car_id, miles, speed, etc)
At the moment I firstly read the Car XML using jQuery AJAX and generate the relevant HTML.
The problem is that next I need to read in the Tariff XML which has the car_id, although I would like to get the car image. How can I go about saving the car_id and image in temporary memory without reading the XML file again to find the image?
$.ajax({
type: "GET",
url: carXmlPath,
dataType: "xml",
contentType: "text/xml; charset=utf-8",
success: function(xml){
carCarousel.html("");
$(xml).find("car").each(function(index, value){
var tis = $(this), first = '';
if(index == 0) first = ' class="selected"';
carCarousel.append('<li'+first+' data-id="'+tis.find("id").text()+'">' + tis.find("name").text() + tis.find("thumbnail").text() + '</li>');
});
carCarousel.removeClass("loading");
}
});
I know this should all be implemented on the server but that is not an option here, it has to be done in JS.
A: If you're creating document fragments to attach to the DOM, then I would use data islands.
E.g. data-car-img and data-car-id.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unknown function CoUninitializeE shows up during profiling While using SlimTune to profile a C# application, I find that when profiling native functions is enabled there are lots of entries for a function called "CoUninitializeE." CoUninitialize seems to be related to COM objects, however I'm not directly using any Com objects, and Google has no information about the version ending with an E.
Does anyone have knowledge of what this function is/how to reduce the amount of time spent on it? (For instance, is it related to memory management, so that reducing memory allocations or deallocations would help?)
Edit
It appears the function's name is actually "CoUninitializeEx" and that SlimTune is just chopping off a letter for some reason. I still would appreciate knowledge of what leads to this function being called.
A: CoInitalizeEx() and CoUninitialize() are pretty core in Windows programming. They respectively initialize and shutdown COM on a thread. The CLR calls these functions automatically before and after a Thread runs. It is pretty hard to avoid using COM in a .NET program, it is the basic extensibility model for native Windows code. Quite invisible, thanks to the many wrapper classes in the .NET framework that hides the plumbing.
The generic diagnostic is that you use a lot of threads. Yes, expensive. The thread pool is a workaround.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why is casting arrays (vectors) so slow? I was under the impression that in .NET casting (not converting) is very cheap and fast. However, this does not seem to be the case for array. I'm trying to do a very simple cast here, take a T1[] and cast as T2[]. where T1:T2.
There are 3 ways to do this and I'm calling them the following::
DropCasting: T2[] array2 = array;
CastClass: (T2[])array;
IsInst: array as T2[];
And I created methods to do this, unfortunately, C# seems to create some rather strange code depending on if this is generic or not. (If its generic DropCasting uses the castclass operator. And in both cases refuse to emit an 'as' operator when T1:T2.
Anyway, I wrote some Dynamic methods and I tested it to some surprising results (string[]=>object[]):
DropCast : 223ms
IsInst : 3648ms
CastClass: 3732ms
Dropcasting was ~18 times faster than either of the cast operators. Why is casting so slow for arrays?
For normal objects like string=>object, the difference was much less severe.
DropCast : 386ms
IsInst : 611ms
CastClass: 519ms
Benchmark code below:
class Program
{
static readonly String[] strings = Enumerable.Range(0, 10).Select(x => x.ToString()).ToArray();
static Func<string[], object[]> Dropcast = new Func<Func<string[], object[]>>(
() =>
{
var method = new DynamicMethod("DropCast", typeof(object[]), new[] { typeof(object), typeof(string[]) },true);
var ilgen = method.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_1);
ilgen.Emit(OpCodes.Ret);
return method.CreateDelegate(typeof(Func<string[], object[]>)) as Func<string[], object[]>;
})();
static Func<string[], object[]> CastClass = new Func<Func<string[], object[]>>(
() =>
{
var method = new DynamicMethod("CastClass", typeof(object[]), new[] { typeof(object), typeof(string[]) },true);
var ilgen = method.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_1);
ilgen.Emit(OpCodes.Castclass, typeof(object[]));
ilgen.Emit(OpCodes.Ret);
return method.CreateDelegate(typeof(Func<string[], object[]>)) as Func<string[], object[]>;
})();
static Func<string[], object[]> IsInst = new Func<Func<string[], object[]>>(
() =>
{
var method = new DynamicMethod("IsInst", typeof(object[]), new[] { typeof(object), typeof(string[]) },true);
var ilgen = method.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_1);
ilgen.Emit(OpCodes.Isinst, typeof(object[]));
ilgen.Emit(OpCodes.Ret);
return method.CreateDelegate(typeof(Func<string[], object[]>)) as Func<string[], object[]>;
})();
static Func<string[], object[]>[] Tests = new Func<string[], object[]>[]{
Dropcast,
IsInst,
CastClass
};
static void Main(string[] args)
{
int maxMethodLength = Tests.Select(x => GetMethodName(x.Method).Length).Max();
RunTests(1, false, maxMethodLength);
RunTests(100000000, true, maxMethodLength);
}
static string GetMethodName(MethodInfo method)
{
return method.IsGenericMethod ?
string.Format(@"{0}<{1}>", method.Name, string.Join<Type>(",", method.GetGenericArguments())) : method.Name;
}
static void RunTests(int count, bool displayResults, int maxLength)
{
foreach (var action in Tests)
{
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
action(strings);
}
sw.Stop();
if (displayResults)
{
Console.WriteLine("{0}: {1}ms", GetMethodName(action.Method).PadRight(maxLength),
((int)sw.ElapsedMilliseconds).ToString().PadLeft(6));
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
}
Edit before anyone asks the same hold true for things like int[]->uint[] which the clr specs should be cast without conversion.
A: It makes sense to me that casting would be (almost) exactly as expensive as using the as operator. In both scenarios, a runtime check on the type of the object must be made, and it must be determined whether it is compatible with the target type. The check is required to allow the cast operation to throw an InvalidCastException if necessary.
To put it another way, the as operator is a cast operation -- it just also has the virtue of allowing the cast to fail without throwing an exception (by returning null). This could also be done with a combination of the is operator and a cast, but that would double the workload.
A: Because you are casting arrays.
The difference between the 3 snippets of IL code is that the latter two add an IsInst and a CastClass operation. Very little is known about the types, so the CLR has to check whether it is a valid operation. This takes time.
The slight difference between CastClass and IsInst can be explained by the fact that CastClass does a null check first and succeeds right away if the argument is null.
I suspect that the slowdown is because you are casting between arrays. A lot more work may need to be done to make sure that an array cast is valid. It may be necessary to look at each element to see if it can be cast to the target element type. So I would guess that, rather than do all this in 'inline' machine code, the JIT emits a call to a validation function.
In fact, if you run a performance analysis, you can see that is indeed what is happening. Almost 90% of the time is spent in a function called "JIT_ChkCastArray".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Core Foundation objects and retain/release messages Let's say we have some Core Foundation objects, such as CGColorRef, that are added to an NSArray like this:
CGColorRef color = ...;
NSArray *array = [NSArray arrayWithObject:(id)color];
Since arrays retain their contents, color receives a retain message (not CFRetain(), right?). What happens in this case from memory management point of view?
A: From Core Foundation Design Concepts:
Note from the example that the memory management functions and methods are also interchangeable—you can use CFRelease with a Cocoa object and release and autorelease with a Core Foundation object.
It doesn't specifically mention retain, but, in practice, that works as well, as do copy (various classes' CFFooCreateCopy) and description (CFCopyDescription). The last is how you can pass CF objects as the value for a %@ formatting specification when using NSLog and other string-formatting functions and methods.
The result is the same: retain does the same as CFRetain, release does the same as CFRelease, etc.
A few things to be aware of:
*
*Prior to iOS 7 and OS X 10.9, there is no CF counterpart function to NSObject's autorelease method. (7 and 10.9 brought the CFAutorelease function.) If you're not using ARC, then, as mentioned in the documentation quoted above, you can send autorelease to a CF object, and it works the same as on an NSObject.
*You can send a message to nil, but you can't call CF functions on NULL (you'll crash). Quartz has some class-specific functions, such as CGContextRetain/Release, that include a NULL check; whether you want to use those or always do your own NULL checks is a matter of style.
*CF's retain and release functions work under garbage collection, whereas retain and release messages are no-ops (as if sent to nil). Doesn't matter unless you're working on a GC'd Mac app, in which case you will need to use CFRetain and CFRelease on CF objects.
*Similarly, under ARC, retain and release messages will be illegal and CF objects won't be automatically reference-counted. You will need to use CFRetain and CFRelease on CF objects.
*Collections always do the right thing, as documented. Usually, this means a strong reference. Outside of GC, that means the collection (array, dictionary, etc.) will retain and release its objects, whether automatically (by assignments, if its code is ARCified) or manually (by explicit retain and release messages).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: When is __proto__ useful? When is __proto__ useful?
A lot of browsers support it, but because not all do, programmers seem to be scared of using it. I've never seen it in any code (such as the libraries jQuery and backbone.js).
When is __proto__ useful? Is it just a geeky thing for completeness?
A: __proto__ is deprecated and should not be used. Use Object.getPrototypeOf instead. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/Proto - But Opera supports __proto__ and not Object.getPrototypeOf, so beware.
That said, Object.getPrototypeOf is, like the name says, used to get the prototype of an object. I've never found this useful yet.
Edit 2012-02-06 Opera supports Object.getPrototypeOf as of 11.60.
A: It is useful if you are going to modify an objects prototype and need to find out if it has been already modified.
Note that __proto__ is deprecated, instead you should is Object.getPrototypeOf.
MDN Documentation on proto
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: GRAILS: groovy.lang.MissingPropertyException: No such property. I'm trying to debug a Grails application. Unfortunately, I have no prior experience in said language.
When I do grails generate-all org.example.Book, I get back a vague error:
Generating controller for domain class org.example.Book ...
groovy.lang.MissingPropertyException: No such property: Event for class: SimpleTemplateScript6
at SimpleTemplateScript6.run(SimpleTemplateScript6.groovy:22)
at _GrailsGenerate_groovy.generateForDomainClass(_GrailsGenerate_groovy:88)
at _GrailsGenerate_groovy$_run_closure1.doCall(_GrailsGenerate_groovy:48)
at GenerateAll$_run_closure1.doCall(GenerateAll.groovy:42)
at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
at gant.Gant.withBuildListeners(Gant.groovy:427)
at gant.Gant.this$2$withBuildListeners(Gant.groovy)
at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
at gant.Gant.dispatch(Gant.groovy:415)
at gant.Gant.this$2$dispatch(Gant.groovy)
at gant.Gant.invokeMethod(Gant.groovy)
at gant.Gant.executeTargets(Gant.groovy:590)
at gant.Gant.executeTargets(Gant.groovy:589)
Error running generate-all: No such property: Event for class: SimpleTemplateScript6
After looking at the generated org.example.BookController.groovy source, I noticed that it was not fully generated (stopped at List fields = []):
package org.example
// import needed for export plugin
import org.codehaus.groovy.grails.commons.ConfigurationHolder
class BookController {
...
def exportService
def export = {attrs ->
def response = attrs.response
List fields = []
This error appears to be caused by the following code in templates/scaffolding/Controller.groovy:
<%=packageName ? "package ${packageName}\n\n" : ''%>
// import needed for export plugin
import org.codehaus.groovy.grails.commons.ConfigurationHolder
class ${className}Controller {
static allowedMethods = [save: "POST", update: "POST", delete: "POST"]^M
def exportService
...
def export = {attrs ->
def response = attrs.response
List fields = []
<% excludedProps = Event.allEvents.toList() << 'version'
allowedNames = domainClass.persistentProperties*.name << 'id' << 'dateCreated' << 'lastUpdated'
props = domainClass.properties.findAll { allowedNames.contains(it.name) && !excludedProps.contains(it.name) && !Collection.isAssignableFrom(it.type) }
Collections.sort(props, comparator.constructors[0].newInstance([domainClass] as Object[]))
props.eachWithIndex {p, i -> %>fields.push("${p.name}"<%="\n"%><% } %>
Map labels = [:]
<% props.eachWithIndex { p, i -> %>labels.putAt("\${p.name}", "\${p.naturalName}")<%="\n "%><% } %>
Map formatters = [:]
Map parameters = [:]
response.setHeader("Content-disposition", "attachment; filename=${domainClass.propertyName}s.\${attrs.extension}")
if("\${attrs.extension}" == "xml") {
exportService.export(attrs.format, response.outputStream, attrs.exportList, fields, [:], formatters, parameters)
} else {
exportService.export(attrs.format, response.outputStream, attrs.exportList, fields, labels, formatters, parameters)
}
}
...
}
It appears that the def export {} block seems to be causing problems. Is there something wrong with the above code?
A: What is the Event class? Is there an import for it?
A: Check your domain class for syntax errors. Make sure that in your domain class, you've included necessary packages, in your case, package org.example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why does an instance of Random in a serialized class repeatedly produce the same set of numbers? So I'm a c# noob. I have a quick question that I can't find an answer to anywhere else.
[Serializable()]
public class Dictionary
{
private Random m_RandomGenerator = new Random();
public int GetNext()
{
return m_RandomGenerator.Next(100);
}
}
The Dictionary instance is loaded each time the program starts, and this code will return the exact same sequence of numbers each time it is run. By which I mean, each time the executable is run. Surely the time value it's seeded with should be different (DateTime.Now.Ticks I assume?).
A couple of points:
*
*There is only one instance of Dictionary, deserialized from a previously-exported file at startup.
*If I make m_RandomGenerator static then the problem is fixed.
Does anyone know why? I did double check that I'm not creating a new instance of Dictionary each time, so that's not the issue.
Well, colour me embarrassed. As it turns out the culprit was the [Serializable()] attribute. The dictionary class I was using was loaded from a previously exported file, which was obviously loading the seed back into Random(). Changing the variable to static meant that the seed value was no longer loaded from the previously serialised instance - hiding the issue.
Thanks to all the people offering constructive advice!
A: (CW because this is way too big for a comment)
This test will only ever repeat when Random is seeded. You should post the code calling Dictionary because there may be something fishy there (assuming the code posted is the actual code) or even better post your own test that reproduces the issue.
[Test]
public void TestDictionary()
{
var dictionary = new Dictionary();
for(int i = 0; i < 10; i++)
{
Console.WriteLine(dictionary.GetNext());
}
}
[Serializable] // added after the fact
public class Dictionary
{
//private Random m_RandomGenerator = new Random(12);
private Random m_RandomGenerator = new Random();
public int GetNext()
{
return m_RandomGenerator.Next(100);
}
}
This test does repeat your results but that's because of the answer here:
[Test]
public void TestDictionary2()
{
var alpha = new Dictionary();
var bravo = new Dictionary();
for(int i = 0; i < 10; i++)
{
Console.WriteLine("{0} - {1}", alpha.GetNext(), bravo.GetNext());
}
}
For completeness, here's a serialization test:
[Test]
public void SerializationPerhaps()
{
var charlie = new Dictionary();
Dictionary delta = null;
// Borrowed from MSDN: http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx
//Opens a file and serializes the object into it in binary format.
using (var stream = File.Open("data.xml", FileMode.Create))
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, charlie);
}
//Opens file "data.xml" and deserializes the object from it.
using (var stream = File.Open("data.xml", FileMode.Open))
{
var formatter = new BinaryFormatter();
delta = (Dictionary) formatter.Deserialize(stream);
stream.Close();
}
for(int i = 0; i < 10; i++)
{
Assert.AreEqual(charlie.GetNext(), delta.GetNext());
}
}
A: The source of your problem must be somwhere else than in the code you posted. Here is the same code, embedded in a test harness:
using System;
namespace RandomTest
{
public class Dictionary
{
private Random m_RandomGenerator = new Random();
public int GetNext()
{
return m_RandomGenerator.Next(100);
}
}
class Program
{
static void Main(string[] args)
{
Dictionary d = new Dictionary();
for (int i=0;i<10;i++)
{
int r = d.GetNext();
Console.Write("{0} ",r);
}
Console.WriteLine();
}
}
}
It returns a different sequence every time it is run.
A: Well without further code samples the answer to your question is simple.
It is not repetitive.
I plugged your code sample into a console application and the result is completely random.
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
Dictionary dict = new Dictionary();
for (int count = 0; count < 100; count++)
Console.WriteLine(dict.GetNext());
Console.ReadLine();
}
}
public class Dictionary
{
private Random m_RandomGenerator = new Random();
public int GetNext()
{
return m_RandomGenerator.Next(100);
}
}
}
Result:
http://www.codetunnel.com/content/images/random.jpg
A: I don't know this is what you exactly want but this help me to solve my problem.
Your post and other answer, comments bring me to this.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SerializeRandom
{
[Serializable] // added after the fact
public class RandomGenerator
{
const string fileName = "random.bin";
private Random random = new Random();
public int GetNext()
{
return random.Next(100);
}
public static void Save(RandomGenerator obj)
{
using (var stream = File.Open(fileName, FileMode.Create))
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
}
}
public static RandomGenerator Load()
{
RandomGenerator randomGenerator = null;
//create new object if file not exist
if (!File.Exists(fileName))
{
randomGenerator = new RandomGenerator();
}
else
{
//load from bin file
using (var stream = File.Open(fileName, FileMode.Open))
{
var formatter = new BinaryFormatter();
randomGenerator = (RandomGenerator)formatter.Deserialize(stream);
stream.Close();
}
}
return randomGenerator;
}
}
}
and test class
using System.Collections.Generic;
using NUnit.Framework;
namespace SerializeRandom
{
public class RandomGeneratorTest
{
[Test]
public void TestDictionary1()
{
var randomGenerator = RandomGenerator.Load();
var randomResult1 = new List<int>();
for (int i = 0; i < 10; i++)
{
randomResult1.Add(randomGenerator.GetNext());
}
RandomGenerator.Save(randomGenerator);
randomGenerator = RandomGenerator.Load();
var randomResult2 = new List<int>();
for (int i = 0; i < 10; i++)
{
randomResult2.Add(randomGenerator.GetNext());
}
CollectionAssert.AreNotEqual(randomResult1, randomResult2);
}
}
}
A: Thats because it (Random()) is a pseudorandom number generator.
A seed is required to initialize the random number generator to make it not repetitive.
An acceptable choice is to use the computer time as the seed.
However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.
http://msdn.microsoft.com/en-us/library/system.random.aspx
I'd be careful with the default constructor with no parameters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: WPF datagrid - value of the edited cell I am working on WPF datagrid control. Binding the data from code behind using a dataset/XML. I want to edit the cell of the grid and capture the new value which the user has entered. Is there a code sample to show how to do that?
What event should I use and which property of datagrid (if any) should I use, selecteditem or selectedcell?
(I am kind of new to WPF datagrid control, so I apologize if this is kind of kiddish...)
A: You can use CellEditEnding and RowEditEnding. You can access the respective row and its Item from the event arguments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: cannot access Rails server I've installed a fresh version of ruby and RoR on a Win XP. I run WEBRick server and everything seems Ok but I can not access http://0.0.0.0:3000 from the browser. I've tried to change the port to 80 but still have the same problem, even ping gives a "cannot find host" error. Any clue guys?
A: Try http://localhost:3000, that should work.
A: Have you tried http://127.0.0.1:3000/ or http://localhost:3000/ instead?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: multiple inheritance in objective-c with superclasses already made Say I want to create my view controller class with 2 superclasses; UIViewController and UIView.
is this possible? or is there another way of getting round this?
A: Multiple inheritance is not supported by Objective-C (hopefully, because multiple inheritance is generally synonym of bad design and also lead to potential complex problems like the diamond problem).
Use protocols instead if you need the concept of "common programming interface" (common API for multiple classes)
Note anyway that making a ViewController inherit UIView is nonsense anyway as this is not the same objects at all and in separate parts of the MVC pattern. (UIViewController being in the "Controller" part, probably holding behavior stuff, whereas UIView is the "View" part and not the Controller part, and only have to manage the display/visible representation of your stuff).
There is obviously some misunderstanding of the MVC pattern (omnipresent in Cocoa framework) and I suggest you take some time to read more about MVC. This may not be straightforward at the beginning if you are new to OOP but this is worth understanding as it would be easier for you once you understand it fully.
A: No multiple inheritance in Obj C. However you can achieve your goals using Protocols, composition and message forwarding. And might I add, just searching for the above 3 keywords in Apple's dev documentation pages is an excellent way to learn and get started.
A: One of the tasks of a view controller is to carry enough state so that the view can be released and rebuilt to handle low memory situations. So it is a likely a bad idea.
In general, the iOS framework uses delegates as a neat way to combine the behavior of 2 superclasses: you subclass one (or both) and have an instance of the other class as member variable. Neat and simple and probably a better design anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android/Phonegap navigator.contacts.list(...) finds a contact that doesn't exist Where does Phonegap/Android search for contacts more than in the contacts list?
I just played around with Phonegap on my Android phone (Samsung galaxy s2 if that makes a difference) and when calling navigator.contacts.list I got a contact that isn't in my contacts list.
I know the contact and have him on chat and whatnot but not in the contacts list. I double checked with google contacts online and made sure they where synced and didn't find him there either.
A: Android aggregates contacts from multiple sources including chat. Read more here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: editing packages.config by hand i'm a .net/c# noob (long time java/servlet programmer)
i inherited an mvc 3 project and have been working on it for about 2 months. just opened packages.config for the first time and see jquery stuff in it:
<package id="jQuery" version="1.5.1" />
<package id="jQuery.vsdoc" version="1.5.1" />
<package id="jQuery.Validation" version="1.8.0" />
<package id="jQuery.UI.Combined" version="1.8.11" />
my project has never used NuGet for anything. i understand this file is used by NuGet.
if i were to simply edit this file and remove lines from it, would there be any bad side-affects.
A: It is the file used by nuget to track what dependencies were installed.
A: It's information about the NuGet packages that have been installed in the project via Visual Studio. It should not be edited manually.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Facebook Connect Login Button breaks when presented in iFrame I have a Facebook Login button setup on a test page which allows FB users to connect w/ my application:
<fb:login-button show-faces="true" width="200" max-rows="1" perms="user_photos"></fb:login-button>
It works fine if I go to to it directly in a web browser. (e.g. mysiteDOTcom/facebook_login).
If I put the same code (along w/ the FB.init , xmlns:fb= etc.) on a different page in the same domain, it also works.
The problem comes if I have a javascript overlay and within that overlay there's an iFrame which contains mysiteDOTcom/facebook_login
In this case, the login button only shows as a blue "Facebook" rectangle, and if I click on this rectangle, I receive the following error:
"An invalid api key was specified."
Since I'm in a dev environment, I've added entries in my /etc/hosts file to redirect to my local box. For example, normally I'd hit production machines when I go to wwwDOTmysiteDOTcom/ , but now http://wwwDOTmysitedevDOTcom (only defined locally) is what is returned. Obviously I couldn't specify wwwDOTmysitedevDOTcom in the facebook configuration b/c it's internal only, so FB wouldn't be able to find it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to return a website and automatically redirect to another side which takes long to load I ask the user to input some data, after that I redirect him to a 'result' website which takes several seconds to load.
I don't like this, because there is no user feedback telling him, that the server has not crashed and that his result is coming. So I was thinking about showing the user a 'loading' website stating 'please wait' and then automatically redirect him to the 'result' page. The user would see the "please-wait"-website the whole time the other one is loading, as Flask does not serve the site before it is finished with the calculations.
[Attempt to clarify]
One of the pages takes so long, because it waits for a file upload. The other side takes so long because its functions wait for data from a third party api.
How would I do that in Flask?
A: I was going to suggest Celery for this, but someone just posted this on the Flask mailing list, and this might be a more simpler solution: Hello-Redis-Tasks. If you still want to use Celery though, this is what you should check out: Custom states in celery
A: Flask's documentation for file uploads includes a section on implementing progress bars for file uploads. Choose one of the many client-side solutions to display the progress of the upload and then redirect once the upload is complete.
For the long-running server side process you have several options:
*
*Pre-fetch (and cache) the data from the slow-to-respond API.
*Hijack your link's action with JavaScript and make an ajax request for the data - update the DOM with a status message to let the user know that everything is still working.
*Have a three step process. Page #1 has a link to the "Please wait ... " page (Page #2). Page #2 has a meta refresh tag pointing at Page #3 (<meta http-equiv="refresh" content="0; url=/path/to/page3">)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL Server OUTER JOIN multiple linked fields I am trying to query data from two tables into one tables using OUTER JOIN. The thing is that to uniquely identify the rows, three fields are needed. This brings me to query containing this expression:
FROM Data1 DB
RIGHT OUTER JOIN Data2 FT on (DB.field1 = FT.Value1
and DB.field2 = FT.field2
and DB.field3 = FT.field3)
However, the query runs for pretty much forever. To test the whole thing I used WHERE conditions and FULL OUTER JOIN and in the case of WHERE conditions it is done almost instantly whereas using the FULL OUTER JOIN I had the same trouble and usually ended up cancelling the whole thing after 5 minutes or so.
Can anyone see what I am doing wrong with my query? Thanks for any help!
A: Your best bet is to view the execution plan (and if you are comfortable with it, post a screenshot of it in your question). That'll tell you where the most expensive portion of the query is happening.
A: Do you really need all the records back from the query? Some WHERE criteria could cut execution time down considerably.
Yes, and indexes. Check the plan and create recomended indexes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sql server : count records I have a tableA (ID int, Match varchar, tot int)
ID Match Tot
1 123
2 123
3 12
4 12
5 4
6 12
7 8
Now, I want to calculate Tot which is total number of match exists in the table. for example 123 occured twice, 12 exist thrice and so on. Also note that I want the count only at first match. here is the expected result.:
ID Match Tot
1 123 2
2 123
3 12 3
4 12
5 4 1
6 12
7 8 1
Another case:
ID Match Count Tot
1 123 2
2 123 1
3 12 10
4 12 10
5 4 3
6 12 5
7 8 7
Now I want to add the count for the same match. expected result:
ID Match Count Tot
1 123 2 3
2 123 1
3 12 10 25
4 12 10
5 4 3 3
6 12 5
7 8 7 7
Thanks
A: WITH tableA(ID, Match) AS
(
SELECT 1,123 UNION ALL
SELECT 2,123 UNION ALL
SELECT 3,12 UNION ALL
SELECT 4,12 UNION ALL
SELECT 5,4 UNION ALL
SELECT 6,12 UNION ALL
SELECT 7,8
)
SELECT *,
CASE
WHEN ROW_NUMBER() OVER (PARTITION BY Match ORDER BY ID) = 1
THEN COUNT(*) OVER (PARTITION BY Match)
END AS Tot
FROM tableA
ORDER BY ID
A: SELECT match, COUNT(match ) as Tot
FROM tableA
GROUP BY match
A: Solution 1:
DECLARE @MyTable TABLE
(
ID INT PRIMARY KEY
,Match VARCHAR(10) NOT NULL
,Tot INT NULL
);
INSERT @MyTable(ID, Match)
SELECT 1, 123
UNION ALL
SELECT 2, 123
UNION ALL
SELECT 3, 12
UNION ALL
SELECT 4, 12
UNION ALL
SELECT 5, 4
UNION ALL
SELECT 6, 12
UNION ALL
SELECT 7, 8;
--SELECT
SELECT *
,CASE
WHEN ROW_NUMBER()OVER(PARTITION BY a.Match ORDER BY a.ID ASC)=1
THEN COUNT(*)OVER(PARTITION BY a.Match)
END TotCalculated
FROM @MyTable a;
--UPDATE
WITH MyCTE
AS
(
SELECT a.Tot
,CASE
WHEN ROW_NUMBER()OVER(PARTITION BY a.Match ORDER BY a.ID ASC)=1
THEN COUNT(*)OVER(PARTITION BY a.Match)
END TotCalculated
FROM @MyTable a
)
UPDATE MyCTE
SET Tot = TotCalculated;
SELECT *
FROM @MyTable;
Solution 2:
UPDATE @MyTable
SET Tot = NULL;
SELECT x.ID, y.Num
FROM
(
SELECT b.Match, MIN(b.ID) ID
FROM @MyTable b
GROUP BY b.Match
) x INNER JOIN
(
SELECT a.Match, COUNT(*) AS Num
FROM @MyTable a
GROUP BY a.Match
) y ON x.Match = y.Match
ORDER BY x.ID
UPDATE @MyTable
SET Tot = t.Num
FROM @MyTable z
INNER JOIN
(
SELECT x.ID, y.Num
FROM
(
SELECT b.Match, MIN(b.ID) ID
FROM @MyTable b
GROUP BY b.Match
) x INNER JOIN
(
SELECT a.Match, COUNT(*) AS Num
FROM @MyTable a
GROUP BY a.Match
) y ON x.Match = y.Match
) t ON z.ID = t.ID;
SELECT *
FROM @MyTable;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Upload large CSV file approx 10,000,000 records in mysql table also it contain duplicate rows I want to upload a large csv file approx 10,000,000 records in mysql table which also contain same or more no. of records and also some duplicate records.
I tried Local data infile but it is also taking more time.
How can I resolve this without waiting for a long time.
If it can't be resolved then how can I do it with AJAX to send some records and process it at a time and will do it till the whole csv get uploaded/proccessed.
A: LOAD DATA INFILE isn't going to be beat speed-wise. There are a few things you can do to speed it up:
*
*Drop or disable some indexes (but of course, you'll get to wait for them to build after the load. But this is often faster). If you're using MyISAM, you can ALTER TABLE *foo* DISABLE KEYS, but InnoDB doesn't support that, unfortunately. You'll have to drop them instead.
*Optimize your my.cnf settings. In particular, you may be able to disable a lot of safety things (like fsync). Of course, if you take a crash, you'll have to restore a backup and start the load over again. Also, if you're running the default my.cnf, last I checked its pretty sub-optimal for a database machine. Plenty of tuning guides are around.
*Buy faster hardware. Or rent some (e.g., try a fast Amazon ECC instance).
*As @ZendDevel mentions, consider other data storage solutions, if you're not locked into MySQL. For example, if you're just storing a list of telephone numbers (and some data with them), a plain hash table is going to be many times faster.
If the problem is that its killing a database performance, you can split your CSV file into multiple CSV files, and load them in chunks.
A: Try this:
load data local infile '/yourcsvfile.csv' into table yourtable fields terminated by ',' lines terminated by '\r\n'
A: Depending on your storage engine this can take a long time. I've noticed that with MYISAM it goes a bit faster. I've just tested with the exact same dataset and I finally went with PostgreSQL because it was more robust at loading the file. Innodb was so slow I aborted it after two hours with the same size dataset but it was 10,000,000 records by 128 columns full of data.
A: As this is a white list being updated on a daily basis does this not mean that there are a very large number of duplicates (after the first day)? If this is the case it would make the upload a lot faster to do a simple script which checks if the record already exists before inserting it.
A: Try this query:
$sql="LOAD DATA LOCAL INFILE '../upload/csvfile.csv'
INTO TABLE table_name FIELDS
TERMINATED BY ','
ENCLOSED BY ''
LINES TERMINATED BY '\n' "
A: I was realize the same problem and find out a way out. You can check the process to upload large CSV file using AJAX.
How to use AJAX to upload large CSV file?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Setting Background from Image on Android So I have a program, this I want this program to change the background on the linear layout to a new image in the person's gallery every n minutes. Currently I am getting the path using the following...
public String getCurrentImageLocation(){
ContentResolver contentResolver = getContentResolver();
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Cursor c = contentResolver.query(uri, null, null, null, null);
Integer test2 = c.getCount();
Random randomGenerator = new Random();
Integer randomNumber = randomGenerator.nextInt(test2.intValue());
c.moveToPosition(randomNumber);
int rowId = c.getColumnIndex(MediaStore.Images.Media.DATA);
return c.getString(rowId);
}
At the risk of sounding super noob, how do I get this path and turn it into a drawable that I can use for setBackgrounDrawable(Drawable d). Am I thinking about this the wrong way?
Thanks
A: You can just pass the path to createFromPath(String path). This should give you back a drawable resource you can use.
A: Another way to do it is by using
.setBackgroundBitmap(BitmapFactory.decodeFile(path));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xilinx Error: Place 1018 message I am using a Basys2 board to program a simple string detector to read patterns like "0101". I am using the Xilinix Design Suite 13.2 for this project. The .ucf file gives the following message.
ERROR:Place:1018 - A clock IOB / clock component pair have been found that are not
placed at an optimal clock IOB clock site pair.
The clock component <reset_IBUF_BUFG> is placed at site <BUFGMUX_X1Y1>.
The IO component <reset> is placed at site <IPAD73>.
Here's what my user constrains file looks like:
NET "x" LOC = "P11";# input switch
NET "reset" LOC = "K3"; # reset switch
NET "ck" LOC = "B8"; # clock
NET "b1" LOC = "A7"; # button 1
NET "b2" LOC = "M4"; # button 2
NET "z" LOC = "M5"; # output
One of the solutions I found online was to use this in the ucf:
CLOCK_DEDICATED_ROUTE = FALSE;
But unfortunately this didn't work for me. I'd appreciate any help with this problem.
A: The message appears to imply that your reset is being detected as a clock signal. That should be worrying - do you have processes which are sensitive to the edge of the reset signal?
You should (until you really know what you're doing) only use a couple of forms of process.
Asynchronous reset
process (clk, reset)
begin
if reset = '1' then
-- async reset stuff
elsif rising_edge(clk) then
-- sync stuff
end if;
end process;
Synchronous reset
process (clk)
begin
if reset = '1' then
--sync reset stuff
else
-- other sync stuff
end if;
end process;
Also, be careful - you still need to release the reset signal to these processes synchronously.
Here's a good read on various reset strategies:
http://www.xilinx.com/support/documentation/white_papers/wp272.pdf
Finally, using CLOCK_DEDICATED_ROUTE = FALSE; is another no-no for almost every situation.
A: In my case, I got that inscrutable error message because I mistyped:
always @(clk) begin
if (rst) begin
...
instead of
always @(posedge clk) begin
if (rst) begin
...
Apparently since it wasn't using the edge of clk, rst was now being treated like a clock and messing up routing.
I know this is an old question but I just hit this problem using ISE and Spartan 6; hopefully this answer will help someone (most likely me 6 months from now).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JavaScript code works on chrome, doesn't work on IE and firefox I created this script for educational reasons in pure JS. It adds sorting to tables (when a header is clicked). I decided that it's quite useful and tried to use it in my project. It works fine on Google Chrome (I used this browser when I was creating the script), but doesn't on IE and Firefox. Can you help me?
alert("Remember to add LoadSetup function to window.onload event and to remove this alert.\nAlso remember that table you want to sort must have class 'sortable' and an unique id.\nThe table must be build properly using <thead> and <tbody> tags.")
function addLoadEvent(func) {
// Dobra funkcja która radzi sobie z dodawaniem nowych funkcji do zdażenia window.onload
var oldonload = window.onload;
if (typeof window.onload != 'function') window.onload = func;
else {
window.onload = function() {
if (oldonload) oldonload();
func();
}
}
}
window.onload = LoadSetup;
function LoadSetup()
{
//find sortable tables and set sorting state to 0 (not sorted)
tables = document.getElementsByTagName("table");
tablesStates = new Array(tables.length);
for(var i=0;i<tables.length;i++){
tableName = tables[i].getAttribute("id");
if(hasClass(tables[i], "sortable") && tableName != null){
tablesStates[tableName] = new Array();
thead = tables[i].getElementsByTagName("thead")[0];
header = thead.getElementsByTagName("tr")[0].getElementsByTagName("th");
for(var j=0; j<header.length; j++){
if(!hasClass(header[j], 'notsortable')){
tablesStates[tableName][header[j].innerHTML] = 0;
header[j].removeAttribute("onclick");
header[j].setAttribute("onclick", "sortTable('"+tableName+"', '"+header[j].innerHTML+"')");
}
}
}
}
}
function hasClass(ele, cls)
{
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
String.prototype.capitalize = function() {
// fajna funkcja
return this.charAt(0).toUpperCase() + this.slice(1);
}
String.prototype.capitalizeAll = function() {
// fajna funkcja
result = '';
for(var i=0; i< this.length;i++)
result += this.charAt(i).toUpperCase();
return result;
}
function prepareStringForCmp(s){
en = ['a','c','e','l','n','o','s','z','z','A','C','E','L','N','O','S','Z','Z'];
pl = ['ą','ć','ę','ł','ń','ó','ś','ź','ż','Ą','Ć','Ę','Ł','Ń','Ó','Ś','Ź','Ż'];
for(var i=0;i<pl.length;i++){
regex = new RegExp(pl[i],"g");
s = s.replace(regex,en[i]);
}
return s.capitalizeAll();
}
function cmpStr(a, b){
//a=prepareStringForCmp(a);
//b=prepareStringForCmp(b);
if(a == b)return 0;
else if(a > b) return 1;
else return -1;
}
function cmpStrRev(a, b){return cmpStr(b, a);}
function cmpNum(a, b){ return a - b;}
function cmpNumRev(a, b){return cmpNum(b, a);}
function cmp(a,b,type,asc)
{
// returns -1 if a < b ---- in ascending mode ( asc=true)
// returns 1 is a > b ---- in ascending mode ( asc=true)
// returns 0 if a == b
if(type == "number"){
if(asc == true) return cmpNum(a,b);
else return cmpNumRev(a,b);
}
else if(type == "date"){
if(asc == true) return 0;
else return 0;
}
else{
if(asc == true) return cmpStr(a,b);
else return cmpStrRev(a,b);
}
}
/////////////////////////////////////////////////////////////
// Bubble Sort
function bubbleSortTable(tab, col, type, asc) {
for(var i=0; i < tab.length; i++){
for(var j=0; j< tab.length-1; j++){
if(cmp(tab[j].getElementsByTagName("td")[col].innerText, tab[j+1].getElementsByTagName("td")[col].innerText, type, asc) > 0)
{
buf = tab[j].innerHTML;
tab[j].innerHTML = tab[j+1].innerHTML;
tab[j+1].innerHTML = buf;
}
}
}
}
/////////////////////////////////////////////////////////////
// Quick Sort
function partitionTable(l, r, A, col, type, asc)
{
x = A[l].getElementsByTagName("td")[col].innerText;
i = l-1;
j = r+1;
while(true){
while(true){
j = j-1;
if(cmp(A[j].getElementsByTagName("td")[col].innerText, x, type, asc) <= 0) break;
}
while(true){
i = i+1;
if(cmp(A[i].getElementsByTagName("td")[col].innerText, x, type, asc) >= 0) break;
}
if(i<j){
buf = A[i].innerHTML;
A[i].innerHTML = A[j].innerHTML;
A[j].innerHTML = buf;
}
else return j;
}
}
function qsortTable(l, r, A, col, type, asc)
{
//qsort(tablica, 0, tablica.lenght -1);
if(l<r){
q = partitionTable(l, r, A, col, type, asc);
qsortTable(l, q, A, col, type, asc);
qsortTable(q+1, r, A, col, type, asc);
}
}
/////////////////////////////////////////////////////////////
function sortTable(id, colName){
// sorts table
// returns true if sorting done; otherwise false
// works for strings and numbers
if(tablesStates[id][colName] >= 0) asc = true;
else asc = false;
tab = document.getElementById(id);
thead = tab.getElementsByTagName("thead")[0];
header = thead.getElementsByTagName("tr")[0].getElementsByTagName("th");
tbody = tab.getElementsByTagName("tbody")[0];
rows = tbody.getElementsByTagName("tr");
col = -1;
for(var i=0; i < header.length; i++){
if(header[i].innerHTML == colName){
col = i;
colType = header[i].getAttribute("class");
break;
}
}
if(col == -1) return false;
// demanded header found
bubbleSortTable(rows, col, colType, asc);
//qsortTable(0, rows.length-1,rows, col, colType, asc);
if(tablesStates[id][colName] >= 0) tablesStates[id][colName] = -1;
else tablesStates[id][colName] = 1;
}
And also a simple html for this:
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xml:lang="pl" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="sortTable.js"></script>
<link rel="stylesheet" type="text/css" href="x.css" />
</head>
<body>
<div id="content_box">
<table class="sortable" id="tabela1">
<thead>
<tr><th>name</th><th class="number">age</th><th>city</th></tr>
</thead>
<tbody>
<tr> <td>Jan</td> <td>21</td> <td>Gdańsk</td> </tr>
<tr> <td>Andrzej</td> <td>17</td> <td>Warszawa</td> </tr>
<tr> <td>Paweł</td> <td>112</td> <td>toruń</td> </tr>
<tr> <td>Mateusz</td> <td>43</td> <td>Łomża</td> </tr>
<tr> <td>ADAM</td> <td>21</td> <td>Gdańsk</td> </tr>
<tr> <td>ŻANETA</td> <td>17</td> <td>Warszawa</td> </tr>
<tr> <td>Paweł</td> <td>112</td> <td>toruń</td> </tr>
<tr> <td>LEON</td> <td>43</td> <td>Łomża</td> </tr>
<tr> <td>Jan</td> <td>21</td> <td>Gdańsk</td> </tr>
<tr> <td>Andrzej</td> <td>17</td> <td>Warszawa</td> </tr>
<tr> <td>FRYDERYK</td> <td>112</td> <td>toruń</td> </tr>
<tr> <td>Mateusz</td> <td>43</td> <td>Łomża</td> </tr>
<tr> <td>Jan</td> <td>21</td> <td>Gdańsk</td> </tr>
<tr> <td>BALBINA</td> <td>17</td> <td>Warszawa</td> </tr>
<tr> <td>ADAM</td> <td>112</td> <td>toruń</td> </tr>
<tr> <td>TERESA</td> <td>43</td> <td>Łomża</td> </tr>
</tbody>
</table>
</div>
</body>
</html>
More detailed description:
LoadSetup - works (and adds sorting functionality)
When header is clicked it should do the sorting and it does on Chrome.
Than it goes like this: sortTable >> bubbleSortTable >> cmp
in cmp(a,b,type,asc) a and b are 'undefined' in Firefox and IE and than the script somewhere breaks and nothing gets sorted.
A: I'm not going through all your code, especially since your description is rather vague: "doesn't work" is obvious - you wouldn't ask here if everything works, so being a little more specific and trying to narrow the problem down (thus posting less code) is probably a good idea. But from the three second glance that I gave I see you're setting event handlers with setAttribute. Not a good idea (for example, see this post). That doesn't work in some versions of IE (again, versions are something you didn't specify).
To add one more thing: even doing elem.onclick = ... isn't really recommended. It's the old HTML 4.0 method. Using the DOM Event Model is recommended, i.e. (addEventListener etc.). But then there are endless cross-browser issues, which is why there are js libraries. As such, I suggest porting your code to jQuery or some other such library to make things truly portable.
It's a good idea because otherwise you'll just end up reinventing the wheel, and probably not as well as years of experienced developers have already done. Moreover, you will probably add to this code and it will grow. js libraries used properly will help the scalability of the code.
No, this isn't an answer to your question. And if you're looking for a quick fix to the issue, this isn't it. But I strongly feel that this advice, while harder (much harder) to implement in the short term, is your best bet if you want that code to be truly usable and maintainable.
A: One problem is that you are using the innerText property which isn't supported in Firefox. See 'innerText' works in IE, but not in Firefox for (loads) of details.
Edit: I tested your code in Firefox and the only change I made was from innerText to textContent and it worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Select Query With Count And Where Statement I always seem to trip myself up during these types of SQL Statements. Here is what I'm attempting to accomplish.
My Example Table
Name Date Type
Bob 9/28/11 1
Bob 9/27/11 1
Bob 9/28/11 2
Debra 9/28/11 1
I'm trying to write a SQL Statement that would give me all the names, their total count occured, and then a Date Filter. I'll write a rought statement with completely wrong syntax, but I think it'll convey what I'm attempting to do...I think.
SELECT Name, Count(*) As Total
FROM Table
GROUP BY Name, Total
WHERE Date = Today (I'm aware you can't do a WHERE in a GROUP BY) AND Type = 1
Essentially, I would like to get back a set of data that would show the Name, how many instances of Type 1 for today.
I don't think I'm searching for the proper question to actually be able to effectively research this on my own as well, probably because I'm wording it improperly.
Any help would be appreciated!
A: Your WHERE was in the wrong place:
SELECT Name, Count(*) As Total
FROM Table
WHERE Date = Today AND Type = 1
GROUP BY Name
A: You just need to move your WHERE after your FROM.
SELECT Name, Count(*) As Total
FROM Table
WHERE [Date] = CAST(getdate() as Date) -- or 'Jan 1 1990'
AND [Type] = 1
GROUP BY Name
A: WHERE comes before GROUP
SELECT Name, Count(*) As Total
FROM Table
WHERE Date >= @Today --assuming your date passed in has no time
AND Date < DATEADD(d,1,@Today)
AND Type = 1
GROUP BY Name, Total
example you can run
SELECT LEFT(name,1) FROM sysobjects
WHERE name < 'p'
GROUP BY LEFT(name,1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Lightswitch prerequisites on ASP.NET webserver I am trying to deploy a LightSwitch application to a hosted ASP.NET webserver in my company. The application access data stored on a SQL Server. My webserver admin is asking me if there are any special prerequisites needed for it to run. I've been reviewing the deployment guide
http://blogs.msdn.com/b/bethmassi/archive/2010/09/23/configuring-a-machine-to-host-a-3-tier-lightswitch-application.aspx
The article lists that there was a server component, but that it might change when RTM arrived:
NOTE: The team is looking at simplifying this process and possibly making the LightSwitch server component pre-reqs go away so this process will likely change for RTM.
This other MSDN article states that there are prerequisites.
http://msdn.microsoft.com/en-us/library/gg481779.aspx
My webserver admin keeps saying there's nothing to install on the ASP.NET web server other than .NET 4.0.
Am I missing something?
A: Server setup procedures haven't changed since Beta 1 (although of course the runtime has changed). It's pretty simple; the prerequisites article that you cited has the correct information. Basically the process is:
*
*Install the Web Platform Installer if you don't already have it installed
*Fire up the WPI and search for the LightSwitch runtime
*Install!
As mentioned in the article, you'll need to decide whether you want to install a new instance of SQL Server locally with the prerequisites. If you've already planned for a production SQL Server, you'll want to choose the "without local SQL" option.
A: I don't have a specific answer, but I would stand up a VM with the appropriate version of windows server on it and run through an install on a do novo machine. Should confirm or deny what your server admin says . . .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CGPathRef and PDF It there a way to draw a complex shape with an application like CorelDraw or Adobe Flash, etc, save it or export it as a PDF and then open it with Core Graphics in iOS.
The idea is, to draw a shape, a vector, with CorelDraw - for example, and it is just the path. No color or fill. And then be able to open it directly by Core Graphics, add it as a CGPath to the context, and then be able to manipulate it, like fill it with solid color or gradient, or patterns.
The bottom line is, I am looking for a way to draw a complex shape in a user-friendly environment, like Corel or Flash, and export it, as a vactor, which can be manipulated in Core Graphics. And suggestions or help is really appreicated.
Thanks.
A: SVGKit doesn't work the exact same as I need either. Although I should say it is nicely done. There are also other resources, that I found and I'll leave them here for future references, if anyone stops by this post and is looking for a solution.
Converting SVG Paths to Objective-C Paths Good for simple paths; strokes and fills can be manipulated later by using protocols. Complex paths get mixed up.
SVGKit Good for creating images and animate them later through the course of the program. However, strokes, fills, paths can not be manipulated.
Opacity You can export as source code, hence you have more control over strokes, paths, and fills. As the path gets more complex, it is harder to manage the code manually. The other problem is by the time of export, the program adds resolution-dependent codes. It can be a pain to go through about 300+ lines of code to fix it so that it is not resolution dependent. By the final product wouldn't be mixed up, and can be manipulated by protocols. Layers are CGLayers, not CALayers.
A: If, as you say, you've got PDF files (from Corel, or another app), you can display them using CoreGraphics.
Take a look at the:
*
*CGPDFDocument class
*CGPDFPage class
Then, there is a CGContextDrawPDFPage function, that you can use to draw a PDF pages in a given graphic context, typically in the drawLayer: inContext: method of a UIView subclass.
A: There isn't really a built-in way to load CGPaths from files but you might want to take a look at SVGKit. Pretty much every modern vector drawing app can produce SVG files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Preventing Checkin to trigger multiple Build with TFS 2010 I have some Libraries added in my TFS 2010 project in a Lib folder.
Each time I check In a dll in the Lib folder, all the build that reference that Lib folder trig automatically (more than 20 Build).
I can use the ***NO_CI*** to prevent that. But I prefer to have something automatic.
Is it possible to have an event handler on TFS to prevent that.
Ex. If the check in is on that folder, do not scan all the CI Build Workspaces to trig the build.
A: The workspace mapping in the build definitions defines which files/folders are part of that build. You can use cloaked folders to explicitly exclude folders from the workspace.
However, the workspace mapping is used for 2 purposes: to determine which files get downloaded to the build server as part of the build, and to determine which files trigger CI/Rolling/Gated builds.
If you exclude folders from the workspace (e.g. using cloaked folders) it will stop the builds from being triggered but it will also stop those files from being downloaded as part of the build.
If you want to have a build download a certain folder as part of the build but not have builds triggered by check-ins to that folder I don't believe it is possible without customizing the build workflow.
A: When you include a folder in a workspace, you're saying that changes to that folder affect your project. This is the same for changes to shared source code as for shared binary. If it changes, then the affected applications should be built (and their automated tests should be run) so taht it can be determined whether the changed files have broken anything.
A: Make sure each library in the lib folder has it's own folder + version folders beneath
lib
EntityFramework
4.1
EntityFramework.dll
4.2
EntityFramework.dll
Then modify your builds to only reference specific folders for the library a project references.
It takes a lot of work to setup builds, but will ensure the build only triggers when a file needed for the build is changed.
Alternatively a copy of each library in the projects directory, which you could manage with a package manager like NuGet or OpenWrap
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: matlab indexing into nameless matrix
Possible Duplicate:
How can I index a MATLAB array returned by a function without first assigning it to a local variable?
I'm having to build matrices using one of the built in matlab commands and then get a submatrix. For example:
I = eye(10)
I = I(:,2:4)
in order to get columns 2, 3, and 4 of the eye(10) matrix. It's becoming annoying to use two lines and two assignments for something like this, but the following statements are illegal:
I = eye(10)(:,2:4)
and
I = (eye(10))(:,2:4)
Why is this? Is there something in matlab's grammar that would cause ambiguities to arise if such statements were allowed?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does Google Chrome still support __proto__? __proto__ is deprecated. Why do big browsers like Google Chrome still use it? Are there any plans to dump it?
A: One of the hardest thing to do in a language / framework is actually remove a deprecated feature. There is still loads of code in the world which depends on this feature. Removing it will break websites. Chrome has apparently looked at the cost of maintenance vs. the pain /cost of removal and chosen maintenance.
A: __proto__ is not only deprecated, it was actually never part of the standard. Removing the feature from Chrome would mean that some pages would no longer work in Chrome, and there is no reason to break these pages.
The feature has been added to JavaScript (ECAMScript 5) as the 'getPrototypeOf' function, and new JavaScript programs should use that instead.
A: A proto pseudo property has been included in §B.3.1 of the draft ECMAScript ed. 6 specification (note that the specification codifies what is already in implementations and what webites may currently rely on).
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/proto
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Create per user view or container I would like to create a secure container for each of my authenticated users in order to enforce the security( isolation, a user can't see anything outside its container), speed ( the size of its own database is smaller ). These containers will store all the user documents, profile, themes , ....
Does anyone know how to achieve this with asp.net mvc?
Thx
A: Since you are storing documents, I'm guessing your "container" is a means to securely store user-specific data permanently on disk on the server. For this task, you main choices are likely to be:
*
*the server's file system (doesn't scale too well tho)
*a relational database (such as MySQL, SQL Server or Oracle)
*a non-relational database, such as RavenDB or MongoDB
You application will need to provide the means to separate user's data from other users. By using ASP.NET Forms Authentication, and HTTPS, you have a reasonably secure solution - eg. each user's data can be keyed by their username, which is as secure as any web based app with username+password authentication. I.e. to see another user's data you'd have to be able to login as that user or hijack their session, which is difficult with HTTPS.
I don't believe that separating data into silos necessarily is a good way improve performance. Do you actually have a performance problem? Premature optimization is generally a misplaced effort. Organize your data in a way that makes most sense to your application's requirements. Databases can scale up to Terabytes data, and many thousands of concurrent users. There are many techniques to improve performance for large databases, but wait until you actually have a performance problem before diving into that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: PHP and Java for UDP NAT hole punching...? I want to use NAT hole-punching in one of my java applications, but I don't know where to start. I'd like some sample code to start off with....
(I have access to a PHP server with sockets, cURL, and server sockets, so some PHP server code would be appreciated too...)
Thanks in advance.
EDIT: I am sorry, I was not clear enough. I want to know how to create a PHP server that can be "the middleman" for hole punching. I also want to know how to make a java application that can connect to the PHP server, and maintain that connection while another java application connects to the first one on the same port. (Which is my impression of how NAT hole punching works)
A: You need to learn about STUN. You also need to learn about conditions under which nat traversal is possible (and when it is not). You can read chapter 4 of the Practical JXTA II book available online at scribd. If STUN is not possible, then you need to rely on TURN.
I don't have PHP code examples to provide, but when you will understand how it works, you'll see it is not that complicated to implement. You only need to retrieve translated IP addresses and ports from the middleman, and that's basically it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unable to access panel from script In my browser.xul file I have a panel element:
<panel id="panel1">
<!-- Elements -->
</panel>
When I try:
window.document.getElementById("panel1").openPopup(button, "after_start", 0, 0, false, false);
the browser says that:
window.document.getElementById("panel1") is null.
Am I missing anything here?
A: it's my first time I see panel tag in html..
are you sure you don't mean :
<div id="panel1">
....
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: String and Integer inside a multi-level array I'm trying to do a little more than required for an assignment in class. Ultimately I'm going to have the following random for stats. I'm having trouble figuring out how to do math to the number part of my array. Right now, I'm using a String to store the array and the number values are being stored as strings. I've tried doing an Object[][] .... and I can't figure out how to do math on the object.
Is there a way to store some values of a multidimensional (stacked?) array as strings and others as integers?
I know it's not showing only the even objects of the array. I changed the code around so it'd be easier to get help with. I do have this working in my version at home.
I tried using the information found on Initialising a multidimensional array in Java but it does not give a solution that I could make work.
Thank you very much!
import java.util.Random;
public class StackedArrayTest {
public static void main(String[] args) {
String[][] stats = new String[][] { { "Str", "6" }, { "Con", "3" },
{ "Int", "5" }, { "Wis", "8" }, { "Dex", "2" },
{ "pAtk", "0" }, { "mAtk", "0" }, { "AC", "0" },
{ "Mana", "0" }, { "HP", "0" } };
System.out.println("There are " + stats.length
+ " objects in the array.");
System.out.println("The first object in the array is: " + stats[0][0]
+ ".");
System.out.print("Even objects in array are: ");
for (int i = 0; i < stats.length; i = i + 1) {
if (i <= stats.length - 3) {
stats[i][1] = (stats[i][1]);
System.out.print(stats[i][1] + ", ");
} else
System.out.println(stats[i][1]);
}
}
}
A: Either use a Map<String, Integer> or modify
for(int i=0; i < stats.length; i = i + 1) {
if ( i <= stats.length - 3) {
stats[i][1] = (stats[i][1]);
System.out.print(stats[i][1] + ", ");
}
else System.out.println(stats[i][1]);
}
to
for(int i=0; i < stats.length; i = i + 1) {
if ( i <= stats.length - 3) {
try {
System.out.print(Integer.parseInt(stats[i][1]) + ", ");
} catch(NumberFormatException ignore){/* ignore this */}
}
else {
try {
System.out.println(Integer.parseInt(stats[i][1]) + ", ");
} catch(NumberFormatException ignore){/* ignore this */}
}
}
A: I suggest you to use "HashMap" since it can define types for both keys and values
HashMap<String, Integer> stats = new HashMap<String, Integer>();
stats.put("Str", 6);
stats.put("Con", 3);
// And so on...
System.out.println( ""+(stats.get("Str")+1) ); //4
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement my own locking mechanism For an assignment (it's for concurrency if you wonder) - I have to implement my own lock
(more specific: a TaS, a TTas and an Array-Lock, as described in "The Art of Multiprocessor Programming")
There are some test in- and output schemes online that I tried (too bad they take pretty long to try).
Your program is to count 9-digit numbers that pass a certain test
(it's called the elfproef in dutch, I don't know the english equivalence, sorry).
Sometimes I got a slightly different number, which suggests that my lock doesn't work a 100% right.
I have implemented the locks like this:
interface Lock
{
void Lock();
void Unlock();
}
class TaSLock : Lock
{
AtomicBool state = new AtomicBool(false);
void Lock.Lock()
{ while (state.getAndSet(true)); }
void Lock.Unlock()
{ state.getAndSet(false); }
}
The AtomicBool is implemented with an integer, because the Interlocked class doesn't have operations for Boolean variables. This isn't optimal in terms of memory usage but it doesn't (or shouldn't) matter for the speed.
class AtomicBool
{
int value;
static int True = 1, False = -1;
public AtomicBool(bool value)
{
if (value) this.value = True;
else this.value = False;
}
public void set(bool newValue)
{
if (newValue) Interlocked.Exchange(ref value, True);
else Interlocked.Exchange(ref value, False);
}
public bool getAndSet(bool newValue)
{
int oldValue;
if (newValue) oldValue = Interlocked.Exchange(ref value, True);
else oldValue = Interlocked.Exchange(ref value, False);
return (oldValue == True);
}
public bool get()
{
return (Interlocked.Add(ref value, 0) == 1);
}
}
Now in the parallel part I have just used:
theLock.Lock();
counter++;
theLock.Unlock();
But each time I get slightly different results.
Is there something obvious I'm doing wrong?
A: Hans is right. Your atomic get-and-set boolean appears to be correct -- in fact, it appears to me to be somewhat over-engineered. And the lock appears to be correct as well, insofar as you've built yourself a potentially highly inefficient "spin lock". (That is, all the waiting threads just sit there in a tight loop asking "can I go yet? can I go yet?" instead of going to sleep until it is their turn.)
What is not correct is that your lock provides no guarantee whatsoever that any two threads that both have a view of "counter" have a consistent view of "counter". Two threads could be on different processors, and those different processors could have different copies of "counter" in their caches. The cached copies will be updated, and only occasionally written back to main memory, thereby effectively "losing" some increases.
The real implementation of locking in C# ensures that a full-fence memory barrier is imposed so that reads and writes cannot move "forwards and backwards in time" across the fence. That gives a hint to the processors that they need to not be so smart about caching "counter" so aggressively.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: EF 4.1 Code First MVC3 App and Facebook Share Feature I am working on a simple web application made using Entity Framework 4.1 Code First approach and MVC3.
The web application is a simple Quotes website, and on its homepage, the user get a list of quotes. What I would like to do is have a Facebook Share button, like so:
And when a user clicks that button, I want the Quote author image, along with his quote and his name to be posted on the user's Facebook wall. I believe they call this Share Functionality.
A: Sharing Rich Media
https://developers.facebook.com/docs/share/
you should be able to populate the title, image and description tags to get something similar to what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL Pagination - Should sorting be cached? I can't find any information on this, so either MySQL handles this and is therefore a non-issue or I'm using the wrong keywords:
If someone wants to sort MySQL results, should I have a cached version of the sort somewhere or should i make my queries with an ORDER BY clause? IS there a better way to do this so that users are not sorting thousands of rows every time they change the page?
A: You should create an index on the column that wish to order by.
See the documentation ORDER BY Optimization for when MySQL can use an index to improve the performance of a query with ORDER BY.
A: You should create an index "with a sort criteria" on the column that you want to sort.
This is the syntax to create mysql index:
CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name
[index_type]
ON tbl_name (index_col_name,...)
[index_type]
index_col_name:
col_name [(length)] [ASC | DESC]
So, if you usually retrieve some data sorted by some_column ordered DESC, you should:
CREATE INDEX my_index ON my_table (some_column DESC)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generic $_GET validator I want a dead simple generic $_GET-vars validator, and don't have any desire to reinvent the wheel.
Is there any solid and simple script I can use, something like:
function secure($varName,$format = 'int') {
//format: boolean,int,dec,str,date
//add stripslashes if mq
$var = $_GET[$varName];
switch($format) {
case 'int':
$r = floor($var);
break;
case 'boolean':
$r = ($var === true);
break;
case 'dec':
$r = preg_replace("/0-9.-/i", "", $val);
break;
case 'str':
..
case 'date':
//ISO 8601 is enough...
}
regards,
//t
A: filter_input() comes fairly close to what you want to do.
It's got a decent number of validation and sanitation filters.
An example stolen from the manual:
<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL,
FILTER_FLAG_PATH_REQUIRED));
?>
A: Pekka gave a great function I didn't know about, but filter_input_array is what you actually want.
http://www.php.net/manual/en/function.filter-input-array.php
Example:
Edit: Now shows how to validate a DateTime (ie, a timestamp).
/* data that came from GET
$_GET = array(
'id' => '14',
'name' => 'Guidoe'
'archived' => 'on',
'date' => '2006-12-12 10:00:00'
);
*/
$args = array(
'id' => array('filter' => FILTER_VALIDATE_INT,
'options' => array('min_range' => 1, 'max_range' => 1000)
),
'archived' => array('filter' => FILTER_VALIDATE_BOOLEAN,
'flags' => FILTER_NULL_ON_FAILURE
),
'date' => array('filter' => FILTER_CALLBACK,
'options' => 'valid_date_time'
)
'name' =>array('filter'=>FILTER_SANITIZE_STRING,
'flags'=>FILTER_FLAG_ENCODE_HIGH
)
);
function valid_date_time($string) {
$parsed = date_parse($string);
if($parsed['error_count']>0 || $parsed['warning_count']>0)
return false;
return new DateTime($string);
}
$myinputs = filter_input_array(INPUT_GET, $args);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: $.each and problem with it in jQuery I want append some from array by jQuery.each and data hotel_id, number each hotel_id is 4, and this loop $.each(data[0].hotel_id,... }); run 4 times contents inside self, in case that there are or inserted in database rows residence_u and residence_p 3 times (each of they there are 3, not 4(like hotel_id)), when run the following code, this code not have error jus not work. if i remove codes $.each(info_ru.units,... }); and $.each(info_rp.start_date,... }); it worked:
(there are four data[0].hotel_id items but only three data[0].residence_u items. So when the outer loop gets to index === 3, there isn't a data[0].residence_u[index])
See full my js code: http://jsfiddle.net/6sGBd/
This is summary from my js code in ajax call(url: 'get_gr',):
$.each(data[0].hotel_id, function (index, value) {
var $li = $('<li><input name="hotel_id[]" value="' + value.hotel_id + '" style="display:none;"></li>');
var $tooltip = $('<div class="tooltip"></div>').appendTo($li);
$li.appendTo('#residence_name');
var info_ru = data[0].residence_u[index];
$.each(info_ru.units, function (index, value) {
$tooltip.append(value + ' & ' + info_ru.extra[index] + ' & ' + info_ru.price[index] + '<br>');
});
var info_rp = data[0].residence_p[index];
$.each(info_rp.start_date, function (index, value) {
$tooltip.append(value + ' & ' + info_rp.end_date[index] + ' & ' + info_rp.price_change[index] + '<br>');
});
tool_tip()
});
This is output php code(url: 'get_gr',):
[{
"guide": null,
"hotel_id": [{
"hotel_id": ["1"]
}, {
"hotel_id": ["2"]
}, {
"hotel_id": ["3"]
}, {
"hotel_id": ["4"]
}],
"residence_u": [{
"units": ["hello", "how", "what"],
"extra": ["11", "22", "33"],
"price": ["1,111,111", "2,222,222", "3,333,333"]
}, {
"units": ["fine"],
"extra": ["44"],
"price": ["4,444,444"]
}, {
"units": ["thanks", "good"],
"extra": ["55", "66"],
"price": ["5,555,555", "6,666,666"]
}],
"residence_p": [{
"start_date": ["1111", "2222"],
"end_date": ["1111", "2222"],
"price_change": ["1111", "2222"]
}, {
"start_date": ["3333", "444"],
"end_date": ["3333", "4444"],
"price_change": ["3333", "4444"]
}, {
"start_date": ["5555", "6666"],
"end_date": ["5555", "6666"],
"price_change": ["5555", "6666"]
}]
}]
Output js code is this:
1 hello & 11 & 1,111,111 how & 22 & 2,222,222 what & 33
& 3,333,333, 1111 & 1111 & 1111 2222 & 2222 & 2222
2 fine & 44 & 4,444,444 3333 & 3333 & 3333 4444 & 4444 & 4444
3 thanks & 55 & 5,555,555 good & 66 & 6,666,666 5555 & 5555 & 5555 6666 & 6666 & 6666
4
How can fix it and What do i do?
A: you can use 'return' to break out of a loop.
so you can add
if(index === 3){
return false;
}
right at the top of your first $.each
A: The length of the residence_u array is only 3, so when index == 4 and you assign var info_ru = data[0].residence_u[index]; and then accessing an element of the undefined info_ru is an error and stops execution.
You can fix it by checking that info_ru and info_rp are objects that contain the the element you are looking for.
$.each(data[0].hotel_id, function (index, value) {
var $li = $('<li><input name="hotel_id[]" value="' + value.hotel_id + '" style="display:none;"></li>');
var $tooltip = $('<div class="tooltip"></div>').appendTo($li);
$li.appendTo('#residence_name');
var info_ru = data[0].residence_u[index];
if (info_ru && typeof info_ru === 'object' && info_ru.hasOwnProperty('units')) {
$.each(info_ru.units, function (index, value) {
$tooltip.append(value + ' & ' + info_ru.extra[index] + ' & ' + info_ru.price[index] + '<br>');
});
}
var info_rp = data[0].residence_p[index];
if (info_rp && typeof info_rp === 'object' && info_rp.hasOwnProperty('start_date')) {
$.each(info_rp.start_date, function (index, value) {
$tooltip.append(value + ' & ' + info_rp.end_date[index] + ' & ' + info_rp.price_change[index] + '<br>');
});
}
tool_tip()
});
A: I would suggest several things:
*
*If you stay with the same data format, then you should code defensively to guard against different array lengths in your three parallel arrays. You can code to iterate only over the shortest of the three arrays so your index never goes out of bounds.
*You could fix your data structure so that all the data that goes together for a given iteration is in one object and thus you can never have different numbers of different attributes. You make an object with hotel_id, units, price, etc... rather than separate arrays for each of those. Keep all the properties with the object rather than arrays of properties that you then have to associate with an object.
As for your current code, your code logic is just flawed. You have an outer .each() loop that iterates over the hotel_id array which has 4 items, yet you use the index from that loop to reach into two other data structures that don't have the same number of items. Either your data is wrong or your code logic is flawed and, in both cases, your code is not written defensively to protect against mismatched array lengths.
To know what you'd really want to recommend when you have a different number of items in the hotel_id, residence_u and residence_p arrays, we'd have to understand a lot more about what you're really trying to do.
You can code defensively by changing your outer loop to iterate only as many as you have for the other arrays. So, if the shortest array is 3 long, then that's the most you iterate the outer loop so you index never goes out of bounds:
var minLen = Math.min(Math.min(data[0].hotel_id.length, data[0].residence_u.length), data[0].residence_u.length);
for (var index = 0; index < minLen; index++) {
var value = data[0].hotel_id[index];
var $li = $('<li><input name="hotel_id[]" value="' + value.hotel_id + '" style="display:none;"></li>');
var $tooltip = $('<div class="tooltip"></div>').appendTo($li);
$li.appendTo('#residence_name');
var info_ru = data[0].residence_u[index];
$.each(info_ru.units, function (index, value) {
$tooltip.append(value + ' & ' + info_ru.extra[index] + ' & ' + info_ru.price[index] + '<br>');
});
var info_rp = data[0].residence_p[index];
$.each(info_rp.start_date, function (index, value) {
$tooltip.append(value + ' & ' + info_rp.end_date[index] + ' & ' + info_rp.price_change[index] + '<br>');
});
tool_tip()
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing string to popup I'm working with a JSP page and it's displaying a table of a storage objects that was fetched. I want to have a popup to another JSP page when the user clicks on the number that is showing the size of the storage object.
How do I pass the name of the specified storage item to the popup JSP window with Javascript (or any other technique), and then retrieve that name in the popup JSP and be able to use it in that page's code?
The scriptlet for-loop looks like this:
<% for(Storage s : someList){ %>
<tr>
<td> <%= s.getName() %> </td> <td> <%= s.getSize() %> </td>
</tr>
<% } %>
A: Pass it as request parameter.
E.g.
<td onclick="window.open('popup.jsp?name=<%= URLEncoder.encode(s.getName(), "UTF-8") %>', 'windowname')">
with in popup.jsp:
<%= request.getParameter("name") %>
Or, more cleanly, with JSTL and EL:
<c:forEach items="${someList}" var="s">
<c:url value="popup.jsp" var="popupUrl">
<c:param name="name" value="${s.name}" />
</c:url>
<tr>
<td>${s.name}</td><td onclick="window.open('${popupUrl}', 'windowname')">${s.size}</td>
</tr>
</c:forEach>
with in popup.jsp
${param.name}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to show Password in clear text in password input field when label is being used as value? I'm using the code below and also seen in this fiddle http://jsfiddle.net/peter/Xt5qu/ to use labels as input values. What change can I make so that on password fields the label is in clear text but as they type it's hidden?
<form id="new_account_form" method="post" action="#" class="login-form">
<ul>
<li>
<label for="user_email">Email address</label>
<input id="user_email" name="user_email" required="" class="validate[required,custom[email]] clearOnFocus login-itext" type="text">
</li>
<li>
<label for="user_password">Password</label>
<input id="user_password" name="user_password" required="" class="validate[required,minSize[6]] clearOnFocus login-itext" type="password">
</li>
<li>
<input name="Submit" type="submit" class="login-ibutton" value="Sign in"></li>
</ul>
</form>
<script script type="text/javascript">
this.label2value = function(){
// CSS class names
// put any class name you want
// define this in external css (example provided)
var inactive = "inactive";
var active = "active";
var focused = "focused";
// function
$("label").each(function(){
obj = document.getElementById($(this).attr("for"));
if(($(obj).attr("type") == "text", "password") || (obj.tagName.toLowerCase() == "textarea")){
$(obj).addClass(inactive);
var text = $(this).text();
$(this).css("display","none");
$(obj).val(text);
$(obj).focus(function(){
$(this).addClass(focused);
$(this).removeClass(inactive);
$(this).removeClass(active);
if($(this).val() == text) $(this).val("");
});
$(obj).blur(function(){
$(this).removeClass(focused);
if($(this).val() == "") {
$(this).val(text);
$(this).addClass(inactive);
} else {
$(this).addClass(active);
};
});
};
});
};
// on load
$(document).ready(function(){
label2value();
});
</script>
A: You can use the HTML5 placeholder attribute, but quite a few browsers don't support it. As a solution, there's this JSFiddle I wrote, which replaces the password input with a standard text input, and vice versa, on the focus and blur events.
Code:
$(document).ready(function() {
$("input[name='password']").prop("type", "text").val("Password");
});
$("input[name='password']").focus(function() {
if($(this).val() === "Password")
{
$(this).prop("type", "password").val("");
}
});
$("input[name='password']").blur(function() {
if(!$(this).val().length)
{
$(this).prop("type", "text").val("Password");
}
});
This will gracefully degrade for those who have JavaScript disabled.
A: Fiddle: http://jsfiddle.net/WqUZX/
There's no way to do that. Say, * is the character to "hide" the password. When the inputs that character, the script cannot "remember" it. Another problem could occur when the user presses the delete or backspace key within the string. Pasting a string in the input box can also cause issues.
Of course, you could implement such a feature using selectionStart, selectionEnd and a bunch of key event listeners. This approach isn't waterproof, however.
The closest reliable solution is changing the type to text on focus, and back to password on blur.
$("#user_password").focus(function(){
this.type = "text";
}).blur(function(){
this.type = "password";
})
Alternatively, you can use mouseover to show the password. That way, the user can easily choose whether (s)he wants to use the show-password feature, or not.
A: No need to reinvent the wheel if someone has already done it:
http://blog.decaf.de/2009/07/iphone-like-password-fields-using-jquery/
That's just one example I found with a quick Google. I know for sure one of the other web development blogs had an even cleaner example, but I can't remember which one unfortunately.
If you want to homebrew a solution, you could always see how the above plugin is doing it, and develop your own solution based on the principles.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: show element based on class I have html like this
<h2 class="Comprehensive Leadership">Comprehensive Leadership</h2><a href="/topic/comprehensiveleadership">View all Comprehensive Leadership Programs </a>
<br><a href="/programs/pld/Pages/default.aspx" class="Comprehensive Leadership">Program for Leadership Development ></a><br>Dec 2011–Jun 2012<br><a href="/programs/gmp/Pages/default.aspx" class="Comprehensive Leadership">General Management Program ></a><br>Jan–May 2012<br>
<h2 class="Corporate Governance">Corporate Governance</h2><a href="/topic/corporategovernance">
View all Corporate Governance Programs </a><br><a href="/programs/ac/Pages/default.aspx" class="Corporate Governance">Audit Committees in a New Era of Governance ></a><br>Nov 13–15, 2011<br><a href="/programs/cc/Pages/default.aspx" class="Corporate Governance">Compensation Committees ></a><br>Nov 16–18, 2011<br>
<div class="tabbed-content"><ul class="tabs"><li><ul><li><a href="#" class="Comprehensive Leadership">Comprehensive Leadership</a></li><li><a href="#" class="Corporate Governance">Corporate Governance</a></li><div>
If I click Comprehensive Leadership it should only display first h2 tag by matching the class till next h2 tag, that is :
<h2 class="Comprehensive Leadership">Comprehensive Leadership</h2><a href="/topic/comprehensiveleadership">View all Comprehensive Leadership Programs </a>
<br><a href="/programs/pld/Pages/default.aspx" class="Comprehensive Leadership">Program for Leadership Development ></a><br>Dec 2011–Jun 2012<br><a href="/programs/gmp/Pages/default.aspx" class="Comprehensive Leadership">General Management Program ></a><br>Jan–May 2012<br>
I can change the html little bit...i have also paste it here : http://jsfiddle.net/sMCsw/10/
A: A better solution would be not to select by class, but by the actual value of the H2 using this:
function showByText(text){
$("h2:contains('" + text + "')").show();
// added a return false to prevent the a href from actually executing
return false;
}
<a href="/programs/pld/Pages/default.aspx" onclick="return showByText(this.text();">Comprehensive Leadership</a>
A: The way your html is structured does not lend itself to solving this problem easily. I don't think its even worth taking the time trying to figure it out with your current html structure without first knowing whether you can modify it. If you can modify it then this is a very easy problem.
Right now you have structure like so:
<h2>Topic</h2>
... a bunch of content....
<h2>Topic2</h2>
... a bunch of content....
You are asking for a link that hides everything EXCEPT the clicked topic. But you have no containers to define your content. You need to contain your content blocks so that you can hide/show them.
<div class="mytopic">
<h2>Topic</h2>
... a bunch of content....
</div>
<div class="mytopic2">
<h2>Topic2</h2>
... a bunch of content....
</div>
Then you can construct a jQuery constructor to hide everything except for the wanted content. As someone in the comment already pointed out - the class Comprehensive Leadership is illegal the way you are using it. Fix that too.
$('div').not('.mytopic').hide();
On rereading this I think that you may actually want to show the content, not hide it. Hard to tell as your posted code is incomplete and you provided no CSS. Anyways, if you are looking to show then this jQuery line would work instead.
$('div.mytopic').show();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to finish "Activity A" since "Activity B"? (Finish an Activity since other) I'm trying to finish the Activity A since Activity B when it will finish too. The Activity B was launches since Actvity A.
So I've paused the Activity A. How can I do it?
A: You may try using startActivityForResult() on the Activity A to invoke the Activity B.
And then, before calling finish() on the Activity B, you should call setResult() and call finish() on the Activity A in onActivityResult()
Example here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Regex for removing repeating numbers on different lines It's perhaps quite simple, but I can't figure it out:
I have a random number (can be 1,2,3 or 4 digits)
It's repeating on a second line:
2131
2131
How can I remove the first number?
EDIT: Sorry I didn't explained it better. These lines are in a plain text file. I'm using BBEdit as my editor. And the actual file looks like this (only then app. 10.000 lines):
336
336
rinde
337
337
diving
338
338
graffiti
339
339
forest
340
340
mountain
If possible the result should look like this:
336 - rinde
337 - diving
338 - graffiti
339 - forest
340 - mountain
A: Search:
^(\d{1,4})\n(?:\1\n)+([a-z]+$)
Replace:
\1 - \2
I don't have access to BBEdit, but apparently you have to check the "Grep" option to enable regex search-n-replace. (I don't know why they call it that, since it seems to be powered by the PCRE library, which is much more powerful than grep.)
A: since you didn't mention any programming language, tools. I assume those numbers are in a file. each per line, and any repeated numbers are in neighbour lines. uniq command can solve your problem:
kent$ echo "1234
dquote> 1234
dquote> 431
dquote> 431
dquote> 222
dquote> 222
dquote> 234"|uniq
1234
431
222
234
A: Another way find: /^(\d{1,4})\n(?=\1$)/ replace: ""
modifiers mg (multi-line and global)
$str =
'1234
1234
431
431
222
222
222
234
234';
$str =~ s/^(\d{1,4})\n(?=\1$)//mg;
print $str;
Output:
1234
431
222
234
Added On the revised sample, you could do something like this:
Find: /(?=^(\d{1,4}))(?:\1\n)+\s*([^\n\d]*$)/
Replace: $1 - $2
Mods: /mg (multi-line, global)
Test:
$str =
'
336
336
rinde
337
337
337
diving
338
338
graffiti
339
337
339
forest
340
340
mountain
';
$str =~ s/(?=^(\d{1,4}))(?:\1\n)+\s*([^\n\d]*$)/$1 - $2/mg;
print $str;
Output:
336 - rinde
337 - diving
338 - graffiti
339
337
339 - forest
340 - mountain
Added2 - I was more impressed with the OP's later desired output format than the original question. It has many elements to it so, unable to control myself, generated a way too complicated regex.
Search: /^(\d{1,4})\n+(?:\1\n+)*\s*(?:((?:(?:\w|[^\S\n])*[a-zA-Z](?:\w|[^\S\n])*))\s*(?:\n|$)|)/
Replace: $1 - $2\n
Modifiers: mg (multi-line, global)
Expanded-
# Find:
s{ # Find a single unique digit pattern on a line (group 1)
^(\d{1,4})\n+ # Grp 1, capture a digit sequence
(?:\1\n+)* # Optionally consume the sequence many times,
\s* # and whitespaces (cleanup)
# Get the next word (group 2)
(?:
# Either find a valid word
( # Grp2
(?:
(?:\w|[^\S\n])* # Optional \w or non-newline whitespaces
[a-zA-Z] # with at least one alpha character
(?:\w|[^\S\n])*
)
)
\s* # Consume whitespaces (cleanup),
(?:\n|$) # a newline
# or, end of string
|
# OR, dont find anything (clears group 2)
)
}
# Replace (rewrite the new block)
{$1 - $2\n}xmg; # modifiers expanded, multi-line, global
A: find:
((\d{1,4})\r(\D{1,10}))|(\d{1,6})
replace:
\2 - \3
You should be able to clean it up from there quite easily!
A: Detecting such a pattern is not possible using regexp.
You can split the string by the "\n" and then compare.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Two simultaneous Python loops with one result I currently have a Python 2.6 piece of code that runs two loops simultaneously. The code uses the gps (gpsd) module and the scapy module. Basically the first function (gpsInfo) contains a continual while loop grabbing GPS data from a GPS device and writing the location to console. The second function (ClientDetect) runs in a continual loop also sniffs the air for wifi data and prints this data when specific packets are found. I've threaded these two loops with the GPS one running as a background thread. What I am looking to do (and have been struggling for 5 days to work out how) is for, when the ClientDetect function finds a match and prints the respective info, I want the respective GPS coordinates of when that hit was made also printed to console. At present my code doesn't seem to work.
observedclients = [] p = "" # Relate to wifi packet session =
gps.gps(mode=gps.WATCH_NEWSTYLE)
def gpsInfo():
while True:
session.poll()
time.sleep(5)
if gps.PACKET_SET:
session.stream
print session.fix.latitude + session.fix.longitude
time.sleep(0.1)
def WifiDetect(p):
if p.haslayer(Dot11):
if p.type == 0 and p.subtype in stamgmtstypes:
if p.addr2 not in observedclients:
print p.addr2
observedclients.append(p.addr2)
def ActivateWifiDetect():
sniff(iface="mon0", prn=WifiDetect)
if __name__ == '__main__':
t = threading.Thread(target=gpsInfo)
t.start()
WifiDetect()
Can anybody look at my code to see how best to grab the data simultaneously for when there is a wifi hit, for the GPS coordinates to be printed too? Somebody mentioned implementing queuing but I have researched this but to no avail with regards to how to implement it.
As said, the aim of this code is to scan for both GPS and specific wifi packets and when detected, print details relating to the packet and the location where is was detected.
A: A simple way of getting this is store the gps location in a global variable, and have the wifi sniffing thread read that global when it needs to print some data; The gotcha is that since two threads can be accessing the global variable at the same time, you'll want to wrap it with a mutex;
last_location = (None, None)
location_mutex = threading.Lock()
def gpsInfo():
global last_location
while True:
session.poll()
time.sleep(5)
if gps.PACKET_SET:
session.stream
with location_mutex:
# DON'T Print from inside thread!
last_location = session.fix.latitude, session.fix.longitude
time.sleep(0.1)
def WifiDetect(p):
if p.haslayer(Dot11):
if p.type == 0 and p.subtype in stamgmtstypes:
if p.addr2 not in observedclients:
with location_mutex:
print p.addr2, last_location
observedclients.append((p.addr2, last_location))
A: you need to tell python you are using an external variable when you use gps in a function. The code should look like this:
def gpsInfo():
global gps # new line
while True:
session.poll()
time.sleep(5)
if gps.PACKET_SET:
session.stream
print session.fix.latitude + session.fix.longitude
time.sleep(0.1)
def WifiDetect(p):
global p, observedclients # new line
if p.haslayer(Dot11):
if p.type == 0 and p.subtype in stamgmtstypes:
if p.addr2 not in observedclients:
print p.addr2
observedclients.append(p.addr2)
A: I think you should be more specific in your goal.
If all you want to do is get GPS coords when a Wifi network is sniffed, just do (psuedo-code):
while True:
if networkSniffed():
async_GetGPSCoords()
If you want a log of all GPS coords and want to match that up with Wifi network data, just print all the data out along with timestamps, and do post-processing do match up Wifi networks with GPS coords via timestamp.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to mix OpenCV 1.0 and OpenCV 2.0 I want to do a polar transform. But in OpenCV 2.0 there doesn't appear to be a C++ version of the cvLogPolar function. How do I use it with cv::Mat?
Error:
'cvLogPolar' : cannot convert parameter 1 from 'cv::Mat' to 'const CvArr *'
Here is my code:
VideoCapture cap(1);
try {
if(!cap.isOpened()) {
throw "Could not open capture device";
}
} catch(char* e) {
cerr << "Error: " << e << endl;
}
for(;;) {
Mat frame;
cap >> frame;
cvLogPolar(frame, frame, Point(frame.size().width/2, frame.size().height/2),
1.0f, CV_INTER_LINEAR|CV_WARP_INVERSE_MAP);
imshow("Preview", frame);
if(waitKey(30) >= 0) break;
}
Tear it apart, I need to learn something anyway.
A: Try something like
Mat frame;
cap >> frame;
Mat dst(frame.size(), frame.type());
CvMat cvframe = frame;
CvMat cvdst = dst;
cvLogPolar(&cvframe, &cvdst, Point(frame.size().width/2, frame.size().height/2),
1.0f, CV_INTER_LINEAR|CV_WARP_INVERSE_MAP);
imshow("Preview", dst);
I've created new Mat to store results of cvLogPolar because this function can not operate in-place.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I not show the paste bar / Clear the clipboard? I'm writing a Silverlight+XNA game and when the user has something in their clipboard they can see less of the screen. I'd really like to be able to not show this clipbaord but I can't see any way (though it does seem to go away after some amount of time)
I've tried an empty string and Clipboard.SetText(null) but that throws an exception.
A: Unfortunately, there is no way to either clear the clipboard from code or influence the display of the SIP beyond setting an InputScope.
The best you can do for now is to update your design to allow for the amount of space which the SIP may use. :(
A: While more complicated, you could create your own text input keys as buttons, and instead of using a textbox, use buttons templated to look like textblocks, with background as you show above, and all... When the user taps the "button" that is a "textblock", you set a flag that says which textblock the keypad buttons send their numbers to.
Or, if the only spot you are sending inputs to (as it appears now that I look at your UI again), there is no need for the button template as the input space, or the flag. Just create buttons for user to tap for input, and send that input to the textblock that appears to be where your answer is. You could make the buttons whatever size you want, that way, as well, so you control how much of the screen is visible. Another thing you could do is make the buttons semi-transparent, so you could have even more background image showing.
Another thought - send the buttons all to the same event handler (except the backspace button), and have the code for that event handler look like this:
{
Button btn = sender as Button;
textblock.Text += btn.Content;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: .bind() statement not working in jQuery Easy Confirmation plugin Did anyone who used jQuery Easy Confirmation plugin run into this issue - the button upon which the confirm box is bound loses its original click event after the first click? I had to change the plugin code to this to make it work. The difference here is between .bind and .click. Can anyone explain why? Pls. let me know if my question is not clear. Thx!
Original plugin code:
// Re-bind old events
var rebindHandlers = function () {
if (target._handlers != undefined) {
jQuery.each(target._handlers, function () {
//this is the difference
$target.bind(type, this);
});
}
}
Changed (working) code:
// Re-bind old events
var rebindHandlers = function () {
if (target._handlers != undefined) {
jQuery.each(target._handlers, function () {
//this is the difference
if(type == 'click')
$target.click(this);
else {
$target.bind(type, this);
}
});
}
}
A: Try using some alerts to see what's happening...
// Re-bind old events
var rebindHandlers = function () {
if (target._handlers != undefined) {
jQuery.each(target._handlers, function () {
if(type == 'click')
alert('$target.click(' + this + ');');
//$target.click(this);
else {
alert('$target.bind(' + type + ', ' + this + ');');
//$target.bind(type, this);
}
});
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Game Center LEaderboard Questions I am in the process of adding Game Center to one of my apps. What I would like to do is set up a leader board per "continent" (North America, South America, Asia, Europe, etc.).
Question 1: If I do this, does game center have the ability to show all results for all leader boards on one leader board? Meaning, I can allow users to see if they are top in their continent, but then also allow them to check their ranking overall. Possible?
Question 2: Since my app is Universal, is there a way to force the standard GC Leader board on the iPad to full screen? I have played around with the GKLeaderBoardViewController view.bounds and although this does allow me change the size, it still maintains the original border of the default size. Meaning, there is a square box around the middle of the view, but the data is actually expanded like it should be. (I wish I knew how to include pics here) Have also used the modelPresentationStyle but same results with the box around a smaller portion of the screen.
Finally, concerning both questions above, is it just better to create your own custom view? I was hoping to avoid this especially since the newer look from iOS 5 Leader boards are actually very nice.
Thanks in advance for any and all suggestions.
Geo...
A: So yes the do allow for one main combined leader board. Just a matter of creating a combined one and adding the others as you see fit.
As for making Game Center full screen on the iPad, no response and luck with searches.
Geo...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I loop through array of values posted I'm posting an array of ids and want to loop over those values. I'm trying the following to populate an array with key/value pairs but it looks like the array is coming out empty.
$arr = array();
foreach($_POST['ids'] as $id)
{
$arr[$id] = GetStuff($id);
}
UPDATE: Looks like array was populated fine. I'm trying to return contents of array by doing echo json_encode($arr) but response is blank.
Here is output of var_dump($_POST);
array(1) {
["ids"]=>
array(18) {
[0]=>
string(6) "156795"
[1]=>
string(6) "156800"
[2]=>
string(4) "4292"
[3]=>
string(6) "796053"
[4]=>
string(6) "660520"
[5]=>
string(4) "4293"
[6]=>
string(4) "4287"
[7]=>
string(6) "488339"
[8]=>
string(6) "837701"
[9]=>
string(7) "1152093"
[10]=>
string(7) "1186434"
[11]=>
string(7) "1324432"
[12]=>
string(6) "796051"
[13]=>
string(6) "144860"
[14]=>
string(5) "15065"
[15]=>
string(7) "1324434"
[16]=>
string(5) "13066"
[17]=>
string(4) "6969"
}
}
A: foreach($_POST['ids'] AS $i=>$id) {
//do stuff
}
Don't forget about quotes..
A: $arr = array();
foreach($_POST['ids'] as $id)
{
$arr[$id] = GetStuff($id);
}
Notice the tick marks around ids in $_POST.
A: This should work:
foreach($_POST['ids'] as $id)
{
$arr[$id] = $_POST['ids'][$id];
}
or even faster, if you are just wanting an array identical to the posted ids:
$arr = $_POST['ids'];
unless I am misunderstanding the question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What are drop targets in gedit's snippets? There is a plugin for gedit to handle snippets. In the Snippets Manager under "Activation" for every snippet you can set the drop targets. There are some preformatted alternatives to choose between but you seem to able to compose your own alternatives too. The preformatted alternatives are: text, text/plain, text/xml, image, image/png, image/jpeg, audio and video.
What are drop targets? How do they work?
Below is a screenshot, the "Drop targets" field is visible under "Activation" in the lower right:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the IP format returned by ServletRequest.getRemoteAddr() The Javadoc of ServletRequest.getRemoteAddr() does not mention anything about the format of returned IP addresses. This is annoying when implementing filters. What can we count on? Is there any official specification one can rely on? Thanks.
A: Let's start at ServletRequest#getRemoteAddr() javadoc:
getRemoteAddr
java.lang.String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client or last proxy that sent the request. For HTTP servlets, same as the value of the CGI variable REMOTE_ADDR.
(emphasis mine)
Okay, let's read CGI REMOTE_ADDR spec:
4.1.8. REMOTE_ADDR
The REMOTE_ADDR variable MUST be set to the network address of the client sending the request to the server.
REMOTE_ADDR = hostnumber
hostnumber = ipv4-address | ipv6-address
ipv4-address = 1*3digit "." 1*3digit "." 1*3digit "." 1*3digit
ipv6-address = hexpart [ ":" ipv4-address ]
hexpart = hexseq | ( [ hexseq ] "::" [ hexseq ] )
hexseq = 1*4hex *( ":" 1*4hex )
The format of an IPv6 address is described in RFC 3513 [15].
There, you've all possible formats.
A: It's an IPv4 or IPv6 address in standard textual notation.
*
*For IPv4, it's the familiar "dot-decimal notation", e.g. 192.168.254.1. I couldn't find an RFC that defines it. Wikipedia mentions that it's acceptable to use octal, binary or hexadecimal notation for any of the quads (and even to mix-and-match), but I've never seen anything but decimal.
*For IPv6, it's specified in RFC-2373.
A: I was always getting IPv4 addresses in normal dot-decimal notation. But recently I noticed that for some clients HttpServletRequest.getRemoteAddr() returns strings that look like this: static.(IPv4 in dot-decimal notation).mydomain.net
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Loading a UIImage in a UIImageView that is part of a UIViewController So I have things nested like this in a nib:
UIViewController
|
|-UIView (container for some about text UILabel)
| |
| UILabel
|
UIScrollView (makes image scalable)
|
UIImageView
I'm trying to load the image of the UIImageView programmatically in another view controller, then pushing the new UIViewController onto a UINavigationController. Everything works fine, but when I assign the image, nothing appears on the new view.
So in a connectionDidFinishLoading: I do this:
UIImage* image = [UIImage imageWithData:imageData];
MyImageController* imageController = [[MyImageController alloc] init];
imageController.title = expandImage.title;
imageController.imageView.image = image;
[self.navigationController pushViewController:imageController animated:YES];
Nothing shows up besides what I designed in the nib. Any help?
A: Try these solution for your problem:
1.First of all, be sure that you get an image and you have an image data in the imageData variable.
2.most likely this solution is what you are looking for. declare a variable in the MyImageController of type UIImage, and set the propriety and synthesize for it, then in your connectionDidFinishLoading code, set the returned image to the variable that you declare, and in the MyImageController assign the variable to the imageController.imageView.
i hope that help you, and tell me what you got from these solution
good luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to remove ' ' using JQuery..? I have two buttons in a row and they are shown in two td's, and its not lined up correctly in IE, I doubt that hidden spaces( ) in the td's somewhere mayby after the input or before the input button, unfortunately I cant access the html code, its automatically generated. The only way is to control by using jQuery I have a jQuery something like this..
$("td:contains(' ')").css("display", "none");
Is this a right way to get rid of that   in the td?
A: No, you would do something along these lines:
$("td").html(function (i, html) {
return html.replace(/ /g, '');
});
A: Rather than answering the OP's specific scenario, if we take the question title ("Is it possible to remove ' ' using JQuery..?") and answer this in a general way (which I think is useful), then any answers using .html() have one fundamental flaw: replacing the html this way also removes any data and event handlers associated with the old html - not desirable! It may work for the OP's specific scenario, but I think it's useful to answer the question in a more general way...
The better way is to replace the .textContent of individual text nodes within the element. So given the following markup:
<div class="container">
<a href="www.google.com">Here is a link </a>
<p>Here is a paragraph with another link inside: <a href="www.facebook.com"> another link </a> </p>
And some final text
</div>
We can remove all (which is unicode \u00A0 - see more about this here) like so:
$('.container, .container *').contents().each(function() {
if (this.nodeType === 3) { // text node
this.textContent = this.textContent.replace(/\u00A0/g, '');
}
});
$('.container, .container *') selects the container and all elements inside it, then .contents() selects all the children of those elements, including text nodes. We go through each of those nodes, and for every text node we encounter (nodeType === 3), we replace the (\u00A0) with an empty string.
A: NBSP is not an element, so you can't hide it.
What you could do is to rewrite the element which contains NBSP... like this:
$('#container').html( $('#container').html().split(' ').join('') );
Also detecting where NBSP using jquery.contains and setting it's parent element a class with font size 0 or display none could do the trick.
Note than if you choose to rewrite the HTML to erase unwanted NBSP all events previously attached will be removed.
A: Use this:
var td = $("td:contains(' ')");
var html = td.html();
html = html.replace(" ","");
td.html(html);
A: I've been struggling with this, at the end the solution was quite obvious, instead of using .html() had to use .text()
Example:
var text = $(label).text();
text.replace(/ /gi,'');
A: try this
$('#div').text($('#div').text().replace(/ /g, ' '));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: How do I connect to an Oracle database using Objective-C (iPhone application)? I am new to Objective-C and xCode and have tried to find example code on how to connect my iPhone application to an Oracle database (remote server). Does anybody have advice, or better yet, an example? Thanks in advance!
A: You would not want to connect to a database using the App. You should connect with a webservice which is connected to the database.
Data being transferred from the iDevice to whatever location is possibly being captured. Always take the safe approach
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: memcache 1.2.2 versus 1.4.7 log messages The following log output on memcached 1.2.2:
<8 new client connection
<8 set mynamespace:views/show 0 47 20499
>8 STORED
can be interpreted as, expires_in = 47 seconds and size = 20499.
How do we interpret the following memcached 1.4.7 log output for expires_in and size?
<40 GET views/show
>40 Writing an error: Not found
>40 Writing bin response:
>40 0x81 0x00 0x00 0x00
>40 0x00 0x00 0x00 0x01
>40 0x00 0x00 0x00 0x09
>40 0x00 0x00 0x00 0x00
>40 0x00 0x00 0x00 0x00
>40 0x00 0x00 0x00 0x00
<40 Read binary protocol data:
<40 0x80 0x01 0x00 0x38
<40 0x08 0x00 0x00 0x00
<40 0x00 0x00 0x00 0x46
<40 0x00 0x00 0x00 0x00
<40 0x00 0x00 0x00 0x00
<40 0x00 0x00 0x00 0x00
<40 SET views/show Value len is 6
>40 Writing bin response:
>40 0x81 0x01 0x00 0x00
>40 0x00 0x00 0x00 0x00
>40 0x00 0x00 0x00 0x00
>40 0x00 0x00 0x00 0x00
>40 0x00 0x00 0x00 0x00
>40 0x00 0x00 0x00 0x01
A: https://github.com/memcached/memcached/blob/master/memcached.c
search for "settings.verbose" Or you can search for "Writing bin response" and it will show you the actual code.
Memcache++ open source code!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CellDingbat is below the first line of the Cell According to the Documentation, "Dingbats are placed to the left of the main contents of a cell, aligned with the first line of the contents." But when I evaluate
CellPrint@Cell[BoxData["Text"], CellDingbat -> "CellDingbat"]
in a Notebook with the "Default" stylesheet I get
One can see that the CellDingbat is placed lower than the first line of the Cell. Why this happens? Is there a way to align CellDingbat with the first line of the Cell?
A: It looks like the baseline of the dingbat and cell contents don't change in the same way when the cell contents are wrapped in BoxData. As Sjoerd pointed out, removing the BoxData from the cell contents makes things line up, but adding BoxData to the CellDingbat does not seem to change anything.
The baseline can be shifted using an AdjustmentBox and after playing around for a while, I found that the baseline is out by CurrentValue["FontAxisOffset"]/CurrentValue["FontMWidth"].
Both of these terms change with the Magnification but it turns out that the observed offset is the constant value obtained when Magnification->1. In this case, the ratio is 0.20833 == 5/24.
I'm not sure if the problem really is with the baseline and whether there is a good underlying reason for the behaviour. I'm also not sure why the required shift does not depend on the magnification of the Cell, Notebook or $FrontEnd. But it seems to work and I've spent enough time playing around with it!
So to test that everything is (basically) ok, try
Do[CellPrint@Cell[BoxData["TxyT"],
CellDingbat -> BoxData[AdjustmentBox["TxyT", BoxBaselineShift -> -5/24]],
Magnification -> mag], {mag, 1, 5}]
And also test how
CellPrint@Cell[BoxData["TxyT"],
CellDingbat -> BoxData[AdjustmentBox["TxyT", BoxBaselineShift -> -5/24]],
Magnification -> Inherited]
looks for various magnifications of the containing notebook and frontend, e.g.,
SetOptions[EvaluationNotebook[], Magnification -> 4.]
and/or
SetOptions[$FrontEnd, Magnification -> 4.]
A: CellLabel instead of CellDingbat
Dingbats are normally little icons, not text. By design, they are positioned somewhat under the baseline of the contents of the first line of the cell. To my eye, they look fine that way.
If you want a label for the cell, instead of a Dingbat, use CellLabel:
CellPrint@Cell[BoxData["Text"], CellLabel -> "Example"]
You can handle the left allignment through CellMargins.
If you prefer the label on the left, have the cell formatted as Output, but notice that the alignment will depend on the screen magnification as the following 3 examples show:
A: I noticed that if you replace BoxData with TextData (or remove BoxData, leaving "Text") the dingbat and the cell contents are aligned.
A: Provided you don't want the CellDingbat on a standard "Input" or "Code" cell style, then as pointed out by Sjoerd, the cell's contents and dingbat automatically align. It's only when you wrap the cell contents in BoxData that they become misaligned.
If the cell you want is a "Text" or "Section" (etc) cell, then you can still have formatted text provided the cell contents are contained in TextData[...]. For example
Note that I've started the text and ended the dingbat with a capital T so that the alignment is clear.
If you hand make your "Input" cells to have their contents wrapped in TextData (which does not happen by default) then the code will run, but the styling is not quite right. The spacing is wrong and syntax highlighting not active. Compare the following
The first printed cell has syntax highlighting but the cell dingbat is misaligned, while the second printed cell has no syntax highlighting and poor spacing, but the dingbat is perfectly aligned!
Finally, I should have realised that a solution like this would work, because I've been using cell dingbats for automatic section numbering for ages and have never had alignment problems. E.g., here's the outline of a notebook I was working on last week that contains supporting code for a chapter in my thesis:
The section and subsection cells are given dingbats in the stylesheet, e.g.,
CellDingbat->TextData[{CounterBox["Section"], ". "}].
A: Does specifying the CellBaseline have any effect?
As in
CellPrint[
Cell[BoxData["Text"], CellDingbat -> "CellDingbat",
CellBaseline -> Bottom]]
rather than the default CellBaseline -> Baseline
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: alphabetical pagination in rails I'm searching a gem for Rails for alphabetical pagination. I wish I could have a list of first letters found in the result (I mean, if there is no row beginning with 'a', I don't want the 'a' to be display on the pagination links). Is this kind of gem already exists?
Thanks in advance!
A: To get a dynamic select from the appropriate table, you can use a dynamic SQL finder.
In this example, we select from a table named 'albums', and fabricate a column 'name' to hold the values. These will be returned in the 'Album' model object. Change any of these names to suit your needs.
Album.find_by_sql("SELECT DISTINCT SUBSTR(name,1,1) AS 'name' FROM albums ORDER BY 1")
Note that you can't use the Album model objects for anything except querying the 'name' field. This is because we've given this object a lobotomy by only populating the 'name' field - there's not even a valid 'id' field associated!
A: I've created an alphabetical pagination gem here:
https://github.com/lingz/alphabetical_paginate
For anyone still having issues in this domain.
A: This wouldn't be too hard to create at all, for example if you had a find, maybe like:
@all_words = Word.select("words.word")
…which returned a result a result set such as a list of words like this:
["alphabet", "boy", "day", "donkey", "ruby", "rails", "iPad"]
…the you could do this:
@all_words.collect {|word| word[0,1]}.uniq.sort
which would return:
["a", "b", "d", "r", "i"]
The .collect {|word| word[0,1]} stores the first letter of each word into a new array whilst uniq filters out the unique letters and sort sorts these alphabetically.
Simply assign this to a variable and you can use it in your view like so:
<ul>
<% @first_letters.each do |letter| %>
<%= content_tag :li, link_to(letter, words_pagination_url(letter), :title => "Pagination by letter: #{letter}") %>
<% end %>
</ul>
Your controller action could then decide what to do with the param from the pagination if one is passed in:
def index
if params[:letter]
@words = Word.by_letter(params[:letter])
else
@words = Word.all
end
end
And then the scope in your model would look something like:
scope :by_letter,
lambda { |letter| {
:conditions => ["words.word LIKE ?", "#{letter}%"]
}}
Your routes require something like:
match "words(/:letter)" => "words#index", :as => words_pagination
I haven't tested this all the way through but it should set you on the right path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: java.util.Iterator to Scala list? I have the following code:
private lazy val keys: List[String] = obj.getKeys().asScala.toList
obj.getKeys returns a java.util.Iterator<java.lang.String>
Calling asScala, via JavaConverers (which is imported) according to the docs..
java.util.Iterator <==> scala.collection.Iterator
scala.collection.Iterator defines
def toList: List[A]
So based on this I believed this should work, however here is the compilation error:
[scalac] <file>.scala:11: error: type mismatch;
[scalac] found : List[?0] where type ?0
[scalac] required: List[String]
[scalac] private lazy val keys : List[String] = obj.getKeys().asScala.toList
[scalac] one error found
I understand the type parameter or the java Iterator is a Java String, and that I am trying to create a list of Scala strings, but (perhaps naively) thought that there would be an implicit conversion.
A: I dislike the other answers. Hell, I dislike anything that suggests using asInstanceOf unless there's no alternative. In this case, there is. If you do this:
private lazy val keys : List[String] = obj.getKeys().asScala.collect {
case s: String => s
}.toList
You turn the Iterator[_] into a Iterator[String] safely and efficiently.
A: You don't need to call asScala, it is an implicit conversion:
import scala.collection.JavaConversions._
val javaList = new java.util.LinkedList[String]() // as an example
val scalaList = javaList.iterator.toList
If you really don't have the type parameter of the iterator, just cast it to the correct type:
javaList.iterator.asInstanceOf[java.util.Iterator[String]].toList
EDIT: Some people prefer not to use the implicit conversions in JavaConversions, but use the asScala/asJava decorators in JavaConverters to make the conversions more explicit.
A: Note that starting Scala 2.13, package scala.jdk.CollectionConverters replaces deprecated packages scala.collection.JavaConverters/JavaConversions when it comes to implicit conversions between Java and Scala collections:
import scala.jdk.CollectionConverters._
// val javaIterator: java.util.Iterator[String] = java.util.Arrays.asList("a", "b").iterator
javaIterator.asScala
// Iterator[String] = <iterator>
A: That would work if obj.getKeys() was a java.util.Iterator<String>. I suppose it is not.
If obj.getKeys() is just java.util.Iterator in raw form, not java.util.Iterator<String>, not even java.util.Iterator<?>, this is something scala tend to dislikes, but anyway, there is no way scala will type your expression as List[String] if it has no guarantee obj.getKeys() contains String.
If you know your iterator is on Strings, but the type does not say so, you may cast :
obj.getKeys().asInstanceOf[java.util.Iterator[String]]
(then go on with .asScala.toList)
Note that, just as in java and because of type erasure, that cast will not be checked (you will get a warning). If you want to check immediately that you have Strings, you may rather do
obj.getKeys().map(_.asInstanceOf[String])
which will check the type of each element while you iterate to build the list
A: As of scala 2.12.8 one could use
import scala.collection.JavaConverters._
asScalaIterator(java.util.Iterator variable).toSeq
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Can I use glu with Android NDK I can't seem to include glu.h in my Android NDK project.
I'm trying to port existing C++ code to NDK, and it uses glu in a few places (notably gluErrorString).
Does OpenGLES not have glu?
Is there a port I can use?
If not I can probably remove the calls to things like gluPerspective and so on, but what do I do about gluErrorString?
A:
Does OpenGL ES not have glu?
No, it doesn't. Look at this: Platform OpenGL Includes collection. Under Android there are only the following headers:
OpenGL ES 1.1:
#include <GLES/gl.h>
#include <GLES/glext.h>
OpenGL ES 2.0:
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
Is there a port I can use?
Yes, there is a partial port of GLU for Android - GLU ES (it supports gluErrorString, gluPerspective and numerous other functions):
GLU 1.3 partitial port (libutil and libtess components only) for
OpenGL ES 1.x (CM - Common profile) and above.
This port supports:
*
*Quadrics: gluNewQuadric(), gluDeleteQuadric(), gluQuadricCallback(),
gluQuadricNormals(), gluQuadricTexture(), gluQuadricOrientation(),
gluQuadricDrawStyle(), gluCylinder(), gluDisk(), gluPartialDisk(),
gluSphere().
*Registry: gluGetString(), gluCheckExtension(),
gluErrorString().
*Projection matrix manipulation: gluOrtho2D(),
gluPerspective(), gluLookAt(), gluProject(), gluUnProject(),
gluUnProject4(), gluPickMatrix(). 2D Mipmaps: gluScaleImage(),
gluBuild2DMipmapLevels(), gluBuild2DMipmaps().
*Tesselation:
gluBeginPolygon(), gluDeleteTess(), gluEndPolygon(),
gluGetTessProperty(), gluNewTess(), gluNextContour(),
gluTessBeginContour(), gluTessBeginPolygon(), gluTessCallback(),
gluTessEndContour(), gluTessEndPolygon(), gluTessNormal(),
gluTessProperty(), gluTessVertex().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Restarting a Sencha Touch App I'm currently working with a Sencha Touch localized app, and all of the string values such as titles, labels and forms are generated on launch, meaning that if I want to switch the language I need to reload the whole app.
Is there a way I can restart/reload the whole application or views without refreshing the browser?
A: You can always fire a launch event in the Ext.Application class, this will invoke all the app initialization code without refreshing the browser
A: Try using the native JavaScript code for reloading the session
i-e
location.reload();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Importance of tools like Ant Maven I am a novice programmer in Java.
I would like to know how important is it working on tools like maven/ant as compared to gaining a lot of hands on expereince in Java.
A: I would stick to first learning java. Tools like Ant and Maven are mostly used for packaging a project and library dependencies.
Both tools are also powered by Java so after learning abit of Java it will definately be easier to master them.
Basically when you feel like you need a solution for building your projects, it is time to have a look at Ant or Maven.
For myself I started using Ant when I got started with Hibernate, Maven came years later.
A: maven/ant could simplify some of your jobs. like building, dependency mgmt, deployment etc. And they are very important in real projects.
However, it only makes sense, if you know how to build/using libraries/deploy without those handy tools. If you have no idea about how to do them by hand, it's hard to use maven/ant correctly.
my 2 cents
A: You definitely need to know both (at some point in your career). Ant/Maven (Gradle anyone?) are indispensable for non-trivial projects, but you also need to know the details of how those tools are working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do solr implement filter search Can anyone point me to the piece of solr source code which performs filter query (excecuting the fq=).
A: Solr's main façade to Lucene is SolrIndexSearcher. In particular the getDocListC function seems to do the actual passing to Lucene.
Filter queries and other parameters are passed via a QueryCommand class, you can see that filter queries is simply a list of org.apache.lucene.search.Query, just like the "main query".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing a method call to a constructor,java Assignment:
Time class:
give it 3 private data members for hour, minute, and second. Use type long or int.
If you use int you must cast inside the ctors.
add a no-arg ctor that uses code like that in Listing 2.6 on p38 to assign values
to hour, minute, and second from the current time.
add another ctor that will take a single long parameter named elapseTime (better
would be elapsedTime), a number for milliseconds since the Unix epoch date.
this second ctor will also use code as per Listing 2.6 to set the data members
for that elapsed time since the epoch.
add a getter for each data member. Each getter will require only a single statement.
Getters are needed because the data members are private.
add a toString method that returns the hours, minutes, and seconds for a Time object.
here is my class Time() code, my setTime() code represents the book reference mentioned above.
package chapter_10;
public class Time {
private long hour;
private long minute;
private long second;
public Time() {
}
public void setTime(long elapsedTime){
long millisecond = System.currentTimeMillis();
second = millisecond / 1000;
minute = second / 60;
hour = minute /60;
//equate for current time.
second = second %60;
minute = minute %60;
hour = hour %24;
}
public long getHour() {
return hour;
}
public long getMinute() {
return minute;
}
public long getSecond() {
return second;
}
public String toString(){
return getHour() + ":" + getMinute() + ":" + getSecond();
}
}
A: public Time() {
setTime(0L);
}
Calling an overridable method inside a constructor is bad practice, though. You should thus make the method private or final, or make the class itself final.
Also, your method is a bit strange, because it takes a time as argument, but doesn't do anything with it.
A: First of all, why would you want to call a class constructor from within a method of the same class?
The thing is that if you are accessing the class, you should have called a constructor before, unless your method is static, so for example, you could do this:
public static void setTime(long elapsedTime){
...
new Time(elapsedTime);
...
}
Then from the invocation part:
Time.setTime(1L);
Although I think this could answer your question (if I understood correctly), the real question is why call a constructor of the same class from a method? Wouldn't it be better to just call the constructor and put all the logic of the method into it?
I hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iOS view "redirect" I'm a web developer tasked with building a basic iOS app for internal use. A number of functions in the app require authentication, and I've successfully built the login view/controller which calls a webservice, authenticates the user etc etc.
I can currently load the "LoginView" with a button click and after authenticating the user, dismiss the view from the view stack returning to the original view, now with established credentials. None of that is my issue.
Now I'm looking for the equivalent of doing a 'redirect' as I would in developing for the web. I need to load the LoginView from any function in my application where authentication is required, and on success, load some other view which would be "passed in" (on the web I would provide a redirect Url) to the LoginView. I feel like this is a simple thing, and must be done all the time, but can not find a good example or explanation of this. I'm certain my obvious newbiness is preventing me from even searching for the right terms.
Hopefully someone can decipher my poor, yet best attempt at explaining what I am looking for. Thank you in advance.
A: One pattern I have used is to pass a success handler block to the authentication view controller.
This has an advantage over the delegate system in that you can set it to perform any action, including moving to any view controller, without modifying each and every view controller to match the delegate protocol.
For instance, one thing I might want to do after successfully authenticating is to pop the view controller stack back to the main menu, or to continue to process a web service request that was already underway. The delegate system doesn't really allow for this, while blocks are more flexible as you can pass in any code you want.
A: Developing for mobile is not the same as developing for the web. In general, apps will have a user login once and then never gain (or at least only when the app is opened, like Mint). If possible, consider changing the design of the app to accommodate mobile design conventions rather than borrowing from the web world. It's a different ball game and your users will appreciate it.
That said, I might attack this by building a custom UIView based off of apple's design for the UIAlertView. Give it a delegate protocol and when it returns with an authenticated user, the controller from which you called it can make the appropriate changes to itself using the delegate method.
A: This is the perfect job for delegates. In your login view controller interface (please note I'm writing this off the top of my head so there might be a few typos/missing semi-colons etc:
@protocol LoginControlDelegate <NSObject>
- (void)loginDidSucceed:(BOOL)success
@end
@interface ...
{
...
}
@property (nonatomic, assign) id<LoginControlDelegate> delegate;
@end
And then in your implementation file, once you have established that the webservice has responded to the login request, you can call:
if (self.delegate != nil)
{self.delegate loginDidSucceed:<YES/NO depending on the webservice response>]
So every time you create an instance of your login view controller, you can assign the "parent" view controller as the delegate and then conform to the <LoginControlDelegate> by implementing the method loginDidSucceed:
LoginViewController *vc = [[LoginViewController alloc] init....];
vc.delegate = self;
[self presentModalViewController:vc animated:YES];
[vc release];
And the loginDidSucceed method:
- (void)loginDidSucceed:(BOOL)success
{
if (success)
// Logged in successfully, push the appropriate view
} else {
// Login failed...
}
A: What @Rog posted will all work fine as stated. I would only suggest that if you already have something akin to a WebRequestManager which dispatches the calls to your web service (creates the connection, manages errors, returns the data) to not worry about delegation of the login, but instead manage that login view in the manager, isolating all of your views from needing this sort of delegate (which becomes a maintenance headache).
This way your views just initiate the request thru the manager and just expect the data to be returned, regardless if a login is required. Notably, the app doesn't even need to (or may not) know what requests require a login, only discovering that as a response from the server. At which point you can launch the login view, get the credentials, and then restart the request with the valid credentials.
And at that point I would keep the credentials, at least for the current run session, so any future requests do not require another login.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: sql - check to see if an entry exists, if so update,is if not insert I was wondering if there was a way that I can do the folloing in one sql statement.
I am parsing an csv file for product insertion into the database. is there a way that I can check to see if an entry in a table with X equaling to N, if so update the rest f the columns else insert it?
regards
Phil
A: This type of operation is sometimes called an "UPSERT". The SQL standard way to do it is to use the MERGE statement, but unfortunately it is not widely implemented yet.
Some databases have added their own ways to do it, such as the non-standard MySQL extensions REPLACE and INSERT ... ON DUPLICATE KEY UPDATE.
A: The MERGE statement will get you there, but it's only available on SQL Server 2008 R2. You would otherwise need to treat this as a Slowly Changing Dimension and either bring the data into a temp table and compare or use an integration services package to do the work.
A: Would something like this work for you?
if(update myTable where x='n')
else{
insert into myTable(x,y,z) values(1,2,3)
}
The update query will run regardless, and will return false if it couldn't update that record, causing it to do the insert.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to store elements of array permanently in VBA in Excel? I wrote macro in Excel that uses dynamic array. Users will add elements to that array.
Is it possible to store elements permanently, so the elements will be available even after workbook was closed?
The trick is that I do not want to store elements on a worksheet and insert them back to array when workbook is open, but to have elements permanently saved in array.
A: One of your best bets is to store the array values in a worksheet and mark the worksheet as hidden using VBA.
Me.Worksheets("ArrayValuesWorksheet").Visible = False
If you use other things like local CSV files, registry, etc then the code will behave differently by simply moving the workbook to different machines and you will lose the ability to have multiple copies of the array.
Edit (Excellent suggestion in @Reafidy's comments below)
A: You can also store an array in a name from the names collection, and this name can be hidden.
Names.Add Name:="StoredArray", RefersTo:=myArray, Visible:=False
A: To answer your question directly: No, there is no way to store an array that has a lifetime beyond the application in memory - you'll have to save it somewhere.
There are several options available but your best is most likely saving it to a sheet. 'Very hidden' sheets are only visible through VBA code so to the user it's the same thing as the array always being there and active in memory.
A: To read/write Array in sheet you can use
Sub WriteArray()
Dim MyArray As Variant
MyArray = Array("x", "y", "z")
Range("A1:C1").Value = MyArray
End Sub
Sub ReadArray()
Dim MyArray As Variant
MyArray = Range("A1:C1").Value
End Sub
After you can use the Visible property of sheet to hide as we have responded.
A: "there is no way..." , >>> yes can do !
some examples : listbox/ComboListBox (on a sheet) = array ...
For 2D variant array : range()=array.
Or store it in a commandbarMenu (those can be made multidimensional)
or whateverthat keeps after reloading workbook...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Component Level Properties In Application.cfc If I have component level properties in my application.cfc will they get evaluated every time a page is it or will they only get evaluated when the application is created?
<cfcomponent>
<cfscript>
this.name = "WARM2_Demo";
this.applicationTimeout = CreateTimeSpan(1,0,0,0);
this.setClientCookies = true;
this.setDomainCookies = false;
this.sessionManagement = true;
this.sessionTimeout = CreateTimeSpan(0,0,30,0);
this.clientManagement = false;
this.scriptProtect = true;
this.appDirectory = getDirectoryFromPath(getCurrentTemplatePath());
this.fileSeparator = createObject("java","java.lang.System").getProperty("file.separator");
....
</cfscript>
<cffunction name="OnApplicationStart" returntype="boolean">
<cfscript>
setupApplication();
return true;
</cfscript>
</cffunction>
....
</cfcomponent>
A: The pseudo-constructor of Application.cfc is executed every request.
Basically behind the scenes an instance of Application.cfc is created every request, and that instantiation behaves just like any other CFC instantiation: the pseudo-constructor bit - the stuff inside the CFCOMPONENT tags but outwith any CFFUNCTION / function declarations - is run.
After the pseudo-constructor is run, any appropriate event handler / interceptor methods are run, eg: onRequestStart().
NB: you could test this very easily yourself by just outputting something in there. It'll show up on the screen on every request (make it a getTickCount() or createUuid() call so you can see it changing).
A: evaluated every time a page is requested, I think.
stick them in Application scope in onApplicationStart()
but honestly, fileSeparator?? Just use /, it'll work on Windows and *nix OS just fine. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: getting min and max values so i have an array of custom objects. i want to go through them to find the maxx, maxy, minx, and miny values. i need the largest of the maxes and smallest of the mins. the following code makes complete sense to me, but i tend to get a random value from the list, my maxes do not get the max or min, and the mins do not get the min or the max.
so, i take the first values from the first object in the array, i then compare each objects values to my current maxx, maxy, minx, miny to see if the object's values are larger or less then, and if so, assign it:
claimCenterBoundary = [dataCenter.claimCenterBoundaryList objectAtIndex:0];
maxx = claimCenterBoundary.maxx;
maxy = claimCenterBoundary.maxy;
minx = claimCenterBoundary.minx;
miny = claimCenterBoundary.miny;
for (int i = 0; i < count; i++)
{
claimCenterBoundary = [dataCenter.claimCenterBoundaryList objectAtIndex:i];
NSLog(@"minx: %@ miny: %@ maxx: %@ maxy: %@", claimCenterBoundary.minx, claimCenterBoundary.miny, claimCenterBoundary.maxx, claimCenterBoundary.maxy);
if (maxx < claimCenterBoundary.maxx)
maxx = claimCenterBoundary.maxx;
if (maxy < claimCenterBoundary.maxy)
maxy = claimCenterBoundary.maxy;
if (minx > claimCenterBoundary.minx)
minx = claimCenterBoundary.minx;
if (miny > claimCenterBoundary.miny)
miny = claimCenterBoundary.miny;
}
here is my output:
count: 8
minx: -98.9139404296875 miny: 48.51737594604492 maxx: -98.90547943115234 maxy: 48.52248382568359
minx: -98.9139404296875 miny: 48.51737594604492 maxx: -98.90547943115234 maxy: 48.52248382568359
minx: -98.92726898193359 miny: 48.51534652709961 maxx: -98.91975402832031 maxy: 48.52249908447266
minx: -98.92726898193359 miny: 48.51534652709961 maxx: -98.91975402832031 maxy: 48.52249908447266
minx: -98.92340850830078 miny: 48.51531219482422 maxx: -98.91383361816406 maxy: 48.52248382568359
minx: -98.92340850830078 miny: 48.51531219482422 maxx: -98.91383361816406 maxy: 48.52248382568359
minx: -98.909423828125 miny: 48.51529693603516 maxx: -98.90548706054688 maxy: 48.51742553710938
minx: -98.96006774902344 miny: 48.51530075073242 maxx: -98.94926452636719 maxy: 48.52977752685547
final minx :-98.92726898193359 miny: 48.51531219482422 maxx: -98.94926452636719 maxy: 48.52977752685547
i can not figure out why this code would not work.
A: This line...
NSLog(@"minx: %@ miny: %@ maxx: %@ maxy: %@", claimCenterBoundary.minx, claimCenterBoundary.miny, claimCenterBoundary.maxx, claimCenterBoundary.maxy);
... implies that the return values of -minx, -miny, -maxx, -maxy are all objects, and most likely NSNumber objects.
If that's the case, then you can't use < and > to compare two NSNumbers. You'd be doing pointer comparison, which is most definitely not what you want.
So what you could do instead is this:
NSArray *objects = dataCenter.claimCenterBoundaryList;
NSNumber *minx = [objects valueForKeyPath:@"@min.minx"];
NSNumber *miny = [objects valueForKeyPath:@"@min.miny"];
NSNumber *maxx = [objects valueForKeyPath:@"@min.maxx"];
NSNumber *maxy = [objects valueForKeyPath:@"@min.maxy"];
This is technically 4 times less efficient than your original proposal, since you're going to iterate the entire list 4 times instead of once, but if your list is a reasonable size, then the difference is probably negligible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get ListView item text from other window I want to make a little application that changes the default playback device in windows 7. The only solution was to interact with the Sound Applet. I succeeded to get the handle to the SysListView32 window that has the devices name but i cant get the text from the ListView.
This is the code used:
IntPtr sListView = (window handle received from another function)
LVITEM lvi = new LVITEM();
lvi.mask = LVIF_TEXT;
lvi.cchTextMax = 1024;
lvi.iItem = 0; // i tried with a loop trought all the items
lvi.iSubItem = 0;
lvi.pszText = Marshal.AllocHGlobal(1024);
IntPtr ptrLvi = Marshal.AllocHGlobal(Marshal.SizeOf(lvi));
Marshal.StructureToPtr(lvi, ptrLvi, false);
SendMessage(sListView, (int)WinMesages.LVM_GETITEMW, IntPtr.Zero, ptrLvi);
string strLvi = Marshal.PtrToStringAuto(lvi.pszText);
The result (strLvi) are some chinese letters. What is wrong in the script?
UPDATE: LVITEM struct is this:
private struct LVITEM
{
public uint mask;
public int iItem;
public int iSubItem;
public uint state;
public uint stateMask;
public IntPtr pszText;
public int cchTextMax;
public int iImage;
public IntPtr lParam;
}
The sLIstView handle is correct... a checked in spy++.
What test do i need to perform to check where is the problem? I could give you all the script if that would help.
A: Have you tried using LWM_GETITEMTEXTW instead?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Using ViewScript Decorator on Nested Subforms (Zend Form) I want to use a view script to render my zend form as it seems to be the best way to
control the layout/design of the form while still using the Zend_Elements classes.
From the view script, I render the element with $this->element->getElement('elementName') .
I'm having problems with the names of the elements. This is actually a sub-form inside a sub-form inside a form.
When I used the FormElements decorators , the fully qualified name of the elements was form[subForm][subForm][element] , which was good.
Wehn I moved to the viewScript decorators, it changed to subForm[subForm][element].
I understood that I need to use the PrepareElements decorator to fix this, but this caused the name to change form[subForm][form][subForm][subForm][elements] (it doubled the first two names in the start).
Any ideas how I should handle this?
Thanks.
UPDATE: I tried to debug PrepareElements and I really don't understand what is doing.
It seems like it works ok in the first iteration, but then it adds again the form[subform] prefix when running on one of the middle subforms.
When I'm not using the PrepareElements decorator, I'm just missing the "form" prefix in the names (i.e., instead of form[subForm][element], I get only subForm[element]).
May be I can just fix this somehow?
I tried to change the belongsTo but that only replaced the "subForm" prefix .
It actually seems like what is missing is a belongsTo method on the subForm.
Again, this is all because of the ViewScript decorator. It works fine with the FormElements decorators.
UPDATE 2: Just to clarify, I wouldn't mind this name change, but it causes my fields to not populate when I call form->populate .
Edit: I think that I've narrowed the problem to this: when I get my values back in setDefaults, they are ordered like this:
array(
\"formElements1-name\" => value1... \"subFormName\" => array(
\"parentFormName\" => array(
\"subFormName\" => subForm-values-array
)
)
...
The main problem here is the "parentFormName" => "subFormNAme".. what does it repeat itself? I'm already in the main form. I'm guessing this is caused because I've set the setElementsBelongTo(formName[subFormName]) , but if I wouldn't do that, then I would get my subform values completely separate from the form,
i.e.
values array = array(
\"formName\" => array(
formValues
), \"subFormNAme\" => array(
subFormValues
)
, while I exepct it to be
array(
formName => array(
subFormNAme => values-array
)
)...
Is it even possible to make this work?
A: Are you just trying to output your form using <?php echo $this->form; ?> from your view script?
That works well for simple forms, but for my more complex forms I tend to render each element individually but don't need to use ViewScript decorator on each individual element to do this. Just try something like this from your view script:
<div class="form">
<fieldset>
<legend>Some Form Name</legend>
<form action="<?php echo $this->escape($this->form->getAction()) ?>"
method="<?php echo $this->escape($this->form->getMethod()) ?>"
enctype="multipart/form-data">
<?php echo $this->form->id; // render the id element here ?>
<div class="half">
<?php echo $this->form->name; // render the user name field here ?>
</div>
<div class="half">
<?php echo $this->form->description; // render the description element here ?>
</div>
<div class="clear"></div>
<div class="half">
<?php echo $this->form->address1; // render the address ?>
</div>
<div class="half">
<?php echo $this->form->address2; // render address2 ?>
</div>
<div class="clear"></div>
<div class="third">
<?php echo $this->form->zip; // render zip code ?>
</div>
<div class="third">
<?php echo $this->form->city; // render city ?>
</div>
<div class="third">
<?php echo $this->form->state; // render state ?>
</div>
<div class="clear"></div>
<div class="half">
<?php echo $this->form->country; // render country ?>
</div>
<div class="clear"></div>
<?php echo $this->form->submit; ?>
</form>
</fieldset>
</div>
That is how I do most of my forms because I want to have some elements take up half the width and others the full width.
Surprisingly, the reference guide doesn't tell you that you can do this. I seem to remember a page about it in the past but cannot find it now. When I got started with Zend Framework, I thought the only way I could get my form to output exactly how I wanted was to create complex decorators, but that is not the case.
Matthew Weier O'Phinney has a great blog post on rendering Zend_Form decorators individually which explains what I did above. I hope they add this to the first page of Zend Form because that was discouraging to me at first. The fact is, 90% of my forms render elements individually instead of just echo'ing the form itself.
Note: To stop ZF from enclosing my form elements in the dt and dd tags, I apply this decorator to all of my standard form elements. I have a base form class that I extend all of my forms from so I don't have to repeat this everywhere. This is the decorator for the element so I can use tags to enclose my elements.
public $elementDecorators = array(
'ViewHelper',
'Errors',
array('Description', array('tag' => 'p', 'class' => 'description')),
array('HtmlTag', array('tag' => 'div', 'class' => 'form-div')),
array('Label', array('class' => 'form-label', 'requiredSuffix' => '*'))
);
For my submit buttons I use
public $buttonDecorators = array(
'ViewHelper',
array('HtmlTag', array('tag' => 'div', 'class' => 'form-button'))
);
A: The current solution is to use the PrepareElements decorator on the subforms with one change - remove the recursive call in the PrepareElements code. Also, no "setElementsBelongTo" is required.
This seem to generate the correct names and ids.
A: The solution would be to use the belongsTo() form element property.
Example :
new Zend_Form_Element_Text('<elementName>', array('belongsTo' => '<subformName>'))
In this way, the render() method will use a form element name like
name="<subformName>[<elementName>]"
A: I had the same problem and i solved it with a decorator
1 : Create a generic subform with elements
2 : Using a specific decorator with PrepareElements
3 : Change form to an array with setIsArray(true)
Example :
Form
$i = 4;
for($i = 0; $i < $nbReclam ; $i++)
{
$rowForm = new Zend_Form_SubForm($i);
$name= new Zend_Form_Element_Textarea('name');
$rowForm->addElement($name);
$this->addSubForm($rowForm, $i);
}
$this->setDecorators(array(
'PrepareElements',
array('ViewScript', array('viewScript' => 'myDecorator.phtml')),
));
$this->setIsArray(true);
Decorator
<table>
<thead>
<tr>
<th>N°</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach ($this->element->getSubForms() as $subForm) : ?>
<tr>
<td> <?php echo $i++?> </td>
<?php foreach ($subForm->getElements() as $row) : ?>
<td><?php echo $row ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</tbody>
</table>
Enjoy
Sorry for my english, i am french
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Google Charts - Trying to add links or any form of custom html in popup Is there any way to have links in any part or a google chart?
Or embeded html?
I would idealy like to format the pop-up with my own html.
some(3) and other(4) should be links.
This is the closest I could get to what I would need Dynamic icons.
By reading on the net I am starting to think that my best option would be to not display google's popup and display a custom div instead.
Edit 1:
Google themselfes have a clickable link "Create new annotation" on their google analytics reports, so anything like that would be great.
A: What you want is the Annotated Time Line from Google Visualizations. Take a look at the first configuration option. :)
http://code.google.com/apis/chart/interactive/docs/gallery/annotatedtimeline.html#Configuration_Options
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Unzip process works on one zip while it doesnt on another? I've been trying to understand why my code doesnt work on a zip and it doesnt on another..
THIS zip unzips , and THIS zip doesnt
Here is the code I use:
String zipFile = Path + FileName;
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
UnzipCounter++;
if (ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(Path
+ ze.getName());
while ((Unziplength = zin.read(Unzipbuffer)) > 0) {
fout.write(Unzipbuffer, 0, Unziplength);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
Can anyone tell me why?
The zip doesnt work means that when it reaches the line "while ((ze = zin.getNextEntry()) != null) {".. ze is always null so it doesnt enter the loop so it doesnt extract anything.. I can open+unzip both files with WinRar..
A: Here's the actual error:
java.io.EOFException
at java.io.RandomAccessFile.readFully(RandomAccessFile.java:383)
at gnu.java.util.zip.ZipFile$PartialInputStream.fillBuffer(ZipFile.java:647)
Looks like your zip file is corrupt. WinRAR tends to ignore some kinds of corruption.
This is a personal gripe of mine - I believe it would be better if tools didn't do that sort of thing, because it means that whoever created the zip file probably doesn't know about the corruption either, and when you tell them, they will be all like, "but it isn't, look .. it opens in [insert broken app here]."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: should I reuse gwt instances (registry objects, loaders) or obtain fresh copy every time? I'm newbie in gwt so sorry for this simple question.
I can call Registry.get("id") every time or I can cache returned value in field, what is better (how fast/slow Registry.get("id") is?)
Similar question for RpcProxy instance and different loader instances.
A: That's actually a good question. You should always try to reuse your instances instead of creating new ones, especially with GWT client Java code which becomes Javascript at runtime. The overhead of instantiating objects in JS (even with all the optimisations you get from GWT) can become quickly unwieldy if you're not carefull. Try it for yourself, have a list of 200 gwt Labels of which you only display 10 at a time versus instantiating only 10 and reusing them each time the values change, you'll see the difference in the time your browser takes to render.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sharing ASP.NET cookies across sub-domains I have two sites, both on the same domain, but with different sub-domains.
*
*site1.mydomain.example
*site2.mydomain.example
Once I'm authenticated on each, I look at the cookies included in subsequent request and they are identical for each site.
However, if I log into the first site, and then navigate to the other, I expect my cookie from site 1 to be sent with the request to site2, but this is not the case. Here are the properties of my cookies.
Logging into Site1, this cookie then exists
Name = MySite
Domain =
Has Keys = False
HttpOnly = False
Path = /
Value = 1C41854066B03D8CC5679EA92DE1EF427DAC65D1BA0E672899E27C57245C1F0B7E93AB01B5563363AB4815A8F4BDE9D293FD261E03F8E60B8497ABBA964D8D315CCE1C8DD220C7176E21DC361935CF6
Expires = 1/1/0001 12:00:00 AM
Logging into Site2, these cookies then exists.
Name = MySite
Domain =
Has Keys = False
HttpOnly = False
Path = /
Value = C8C69F87F993166C4D044D33F21ED96463D5E4EB41E1D986BF508DA0CBD5C2CA7D782F59F3BC96871108997E899FF7401C0D8615705BDB353B56C7E164D2302EE6731F41705016105AD99F4E0578ECD2
Expires = 1/1/0001 12:00:00 AM
I've set the domain on each (doesn't show up in a request cookie as it's only needed on the client).
I've made sure my Forms setting for each are identical
I've made sure my machine key settings are the same in both web configs.
I'm at a loss on why this isn't working. What is it that a cookie contains that the client will send it for one sub-domain and not the other when they are both using the same auth cookies so far as I can tell?
Please comment if there is more info you'd like to see. I've been struggling with this for two days now. According to this article this should be working.
code added
Here is my config file setting for my authentication. This is used in both sites.
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn"
defaultUrl="~/Home/Index"
name="MySite"
protection="All"
path="/"
domain="mydomain.example"
enableCrossAppRedirects="true"
timeout="2880"
/>
And here is my code to create the cookie in Site1.
//Add a cookie that the Site2 will use for Authentication
var cookie = FormsAuthentication.GetAuthCookie(userName, true);
cookie.Name = "MySite";
cookie.HttpOnly = false;
cookie.Expires = DateTime.Now.AddHours(24);
cookie.Domain = "mydomain.example";
HttpContext.Response.Cookies.Add(cookie);
HttpContext.Response.Redirect(site2Url,true);
UPDATE 2:
I noticed something strange while testing. When I add a cookie to the response for site1, it get's added to this directory...
C:\Users\jreddy\AppData\Roaming\Microsoft\Windows\Cookies
When I add a cookie to the response for site, it gets added to this directory...
C:\Users\jreddy\AppData\Roaming\Microsoft\Windows\Cookies\Low
That could be my problem. Could it be that one of my sites is included in the local intranet zone?
UPDATE 3: Problem found, solution unknown
It seems that my problem has to do with my second site being part of the Local Intranet Zone. If I go to Site1 using Firefox it works, but I have to enter my Windows credentials. If I go thru IE, my credentials are picked up automatically, but the cookies can't be read by site2. I may ask this in another question.
A: Add new cookie and specify domain like this
HttpCookie cookie = new HttpCookie("cookiename", "value");
cookie.Domain = "domain.example";
For forms authentication set this in web.config
<forms name=".ASPXAUTH"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
domain="domain.example">
</forms>
The cookie will be accessible to all the subdomains.
In order for each domain to decrypt the the cookie, all web.config files must use the same encryption/decryption algorithm and key. (how to create a machine key)
Example:
// do not wrap these values like this in the web.config
// only wrapping for code visibility on SO
<machineKey
validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75
D7AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281
B"
decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719
F"
validation="SHA1"
decryption="AES"
/>
For easier deployments, these values can be stored in a separate file:
<machineKey configSource="machinekey.config"/>
For added security you can also encrypt the machine key for further protection..
A: If you're using Forms authentication on all of your sub domains, all you need to do is to add domain=".mydomain.example" property to the <forms> node in your web.config
Note the leading period in .mydomain.example
This simple change by itself will make your authentication cookie valid in all sub-domains; no need to manually set any cookies.
A: Set the property of Domain to .mydomain.example in each Cookies of two subdomains websites. Like:
Response.Cookies["test"].Value = "some value";
Response.Cookies["test"].Domain = ".mysite.example";
In Site A:
HttpCookie hc = new HttpCookie("strName", "value");
hc.Domain = ".mydomain.example"; // must start with "."
hc.Expires = DateTime.Now.AddMonths(3);
HttpContext.Current.Response.Cookies.Add(hc);
In Site B:
HttpContext.Current.Request.Cookies["strName"].Value
A: I've created a HttpContext extension method that will write a sub domain safe cookie.
Blog post and discussion
public static class HttpContextBaseExtenstions
{
public static void SetSubdomainSafeCookie(this HttpContextBase context, string name, string value)
{
var domain = String.Empty;
if (context.Request.IsLocal)
{
var domainSegments = context.Request.Url.Host.Split('.');
domain = "." + String.Join(".", domainSegments.Skip(1));
}
else
{
domain = context.Request.Url.Host;
}
var cookie = new HttpCookie(name, value)
{
Domain = domain
};
context.Response.SetCookie(cookie);
}
}
// usage
public class MyController : Controller
{
public ActionResult Index()
{
this.Context.SetSubdomainSafeCookie("id", Guid.NewGuid().ToString());
return View();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
}
|
Q: Splitting elements of a string across multiple columns I would like to split a column containing a string with article references into multiple columns in MySQL. For example, the following string
North American Birds 53(1) 1999: 27-29
would be split into 'North American Birds', 53, 1, 1999, 27-19. I know I can do some of this with substring_index, but this will not work for splitting the journal name (North American Birds) from the volume (53). Any idea how I can do that?
A: You can use the number as a separator.
Slow and ugly code, but I guess it works
SELECT
s.id
,SUBSTRING(s.title,1, PosOfFirstNumber-1) as booktitle
,SUBSTRING(s.title, PosOfFirstNumber) as Remainder
FROM
(SELECT
id
,title
,LEAST(
IFNULL(NULLIF(LOCATE('1',title),0),999)
,IFNULL(NULLIF(LOCATE('2',title),0),999)
,IFNULL(NULLIF(LOCATE('3',title),0),999)
,IFNULL(NULLIF(LOCATE('4',title),0),999)
,IFNULL(NULLIF(LOCATE('5',title),0),999)
,IFNULL(NULLIF(LOCATE('6',title),0),999)
,IFNULL(NULLIF(LOCATE('7',title),0),999)
,IFNULL(NULLIF(LOCATE('8',title),0),999)
,IFNULL(NULLIF(LOCATE('9',title),0),999)
,IFNULL(NULLIF(LOCATE('0',title),0),999)
)) as PosOfFirstNumber
FROM table1 ) s
A: First question to ask is, do you plan to split your string into different columns before OR after inserting it into your database? I suggest splitting before insertion, but this suggestion may be too late.
If splitting BEFORE insertion, you should use regular expressions to parse your data and then build the appropriate SQL INSERT. Here's a Java regular expressions example.
If splitting data after it's already in your database, you will need to create a SQL with pattern matching specific to the string your data. Here's a IBM article describing different SQL code strategies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: extjs4 - How to call an application function from a controller? Given an application:
Ext.application({
name: 'APP',
appFolder: 'app',
funcA: function() {
console.log('called funcA');
},
launch: function() {
...
var funcB = function() {
console.log('called funcB');
}
...
}
});
My controller can call this.application.funcA() but not funcB() within the launch method. How can I call funcB() externally?
A: You can't, as funcB is private to your launch callback, You can move it outside of the callback, just like you did funcA. Basically anything defined inside of a function is private to that function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C Windows API: Polygon accept mouse input Say I create a polygon with the Polygon function, and i'd like it to accept input from the mouse (similar to a button).
How would I do that?
EDIT:
Processing the WM_LBUTTONDOWN and WM_MOUSEMOVE messages, I'm using this code to check if the mouse is in the area of the polygon:
if (LOWORD(lParam) < 375 && LOWORD(lParam) > 340 &&
HIWORD(lParam) < 200 && HIWORD(lParam) > 90)
Problem is, the polygon is not a rectangle, its a polygon. So how would I go about detecting if the mouse was in the polygon only?
EDIT 2: I should also note, its only a triangle lol. Hope that makes this simpler.
A: Polygon() is a function that is used to draw to a device context. As such it cannot receive inupt. You need a windowed control to do that.
Handle the input in your window and use a hit test to check if you are inside the polygon.
A: A polygon can't accept input, it must be done through the window that the polygon was drawn on. Listen for the WM_LBUTTONDOWN message and look at the coordinates delivered with the message; determine if the coordinate is within the polygon or not. The easiest way to do that might be to draw the polygon on a bitmap the same size as the window, and test the point on the bitmap to see if it is the polygon color or not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP Getting certain parts of a string I have the following tire sizes in my database, all formatted in different ways. Here are a few examples:
225/50R17
255/45R18/XL
P155/80R13
What I need is to separate them in 3 parts, and JUST the numbers.
So the first one should be: 225 / 50 / 17 all separate variables.
Second one should be: 255 / 45 / 18 and ignore the XL. And the third one obviously should be 155 / 80 / 13
Does anyone know how I can write a function or whatever needs to be done to just grab those numbers?
Thank you!
A: You probably want something like this:
$ar = array(
'225/50R17',
'255/45R18/XL',
'P155/80R13'
);
foreach ($ar as $a) {
if (preg_match_all('/(\d+)/', $a, $match)) {
print "match=[". print_r($match[0], true) . "]\n";
}
}
?>
Which produces output like this:
match=[Array
(
[0] => 225
[1] => 50
[2] => 17
)
]
match=[Array
(
[0] => 255
[1] => 45
[2] => 18
)
]
match=[Array
(
[0] => 155
[1] => 80
[2] => 13
)
]
A: You could use the preg_split() function:
$str = '255/45R18/XL';
$chars = preg_split('/[^\d]/', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
This results in:
Array
(
[0] => 255
[1] => 45
[2] => 18
)
You'll probably want to have the PREG_SPLIT_NO_EMPTY flag in there, otherwise you'll end up with empty elements in your array.
You're essentially splitting on characters that aren't digits, so preg_split() seems like the natural choice.
A: Assuming the numbers will always have at least 2 digits a regular expression like this will work:
(\d{2,})\/(\d{2,}).*?(\d{2,})
Demo: http://rubular.com/r/l3IDSzU7oH
A: You can use a regular expression to do this:
$text = "255/45R18/XL";
$matches = array();
preg_match_all("/(\d+)/", $text, $matches);
var_dump($matches);
After preg_match_all $matches will look like:
array(4) {
[0]=>
string(12) "255/45R18/XL"
[1]=>
string(3) "255"
[2]=>
string(2) "45"
[3]=>
string(2) "18"
}
A: http://sandbox.phpcode.eu/g/3cb0f
<?php
$string = '225/50R17';
$filtered = preg_replace('~[a-z]+~i', '/', $string);
$exploded = explode('/', $filtered);
foreach($exploded as $one){
if (!empty($one)){
echo "<b> ".$one."</b>";
}
}
A: Providing it's always an R that splits numbers, this code should work (untested):
$string = // Get the current row from the database
// Replace all occurences of `R` with a `/`
str_replace("R", "/", $string);
// Remove any letters
$string = preg_replace("/[a-zA-Z]/i", "");
// Split string into an array
$numbers = explode("/", $string);
// Get rid of any empty elements
foreach($numbers as $index => $value)
{
if(empty($value))
{
unset($numbers[$value]);
}
}
There are probably better ways to do it, but this should work for most if not all cases.
Do bear in mind that this is only for one row and should be put in your MySQL while() loop or whatever. You can then append $numbers to an array holding all tyre sizes or whatever you'd like to do.
A: one way to do it without regexp just in case your strings aren't that predictable
function remove_crap ($crapString) {
//build an alphabet array
for ($character = 65; $character < 91; $character++) {
$potentialCrap[] = chr($character);
}
//throw in slash or whatever other crap there might be with the numbers
$potentialCrap[] = "/";
//strip out all potential crap
$newString = str_replace($potentialCrap, '', $crapString);
//readd the slashes where they go, totally better ways to do this but i'm tired and want to go home
$finalString = $newString[0].$newString[1].$newString[2]."/".$newString[3].$newString[4]."/".$newString[5].$newString[6];
return $finalString;
}
A: This works for me
<?php
$s = "145/80R13";
$x = preg_split('/\/|[a-z]|[A-Z]|-| /', $s);
print_r($x);
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why doesn't `cancelPreviousRequestsWithTarget` cancel an NSTimer? I schedule an NSTimer instance like this:
[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(someMethod) userInfo:nil repeats:YES];
I am able to call invalidate on my NSTimer to stop it from firing, but
[NSTimer cancelPreviousPerformRequestsWithTarget:self];
does not stop the timer. I have checked and [NSRunLoop currentRunLoop] is exactly the same (as expected, these are in responses to user clicks) and of course the self instance is always the same. Why doesn't cancel cancel?
A: cancelPreviousPerformRequestsWithTarget: is an NSObject method, not an NSTimer method, and it is the inverse of NSObject's performSelector: methods.
[NSTimer cancelPreviousPerformRequestsWithTarget:self] is the same as [NSObject cancelPreviousPerformRequestsWithTarget:self], and what it cancels is any previous [self performSelector:… withObject:… afterDelay:…] messages. It has nothing to do with any NSTimer instances.
Sending the message to the NSTimer class rather than the NSObject class works the same way that sending alloc to a class does. No classes override it; it works because NSObject's implementation is inherited, and it does the same thing for the same reason.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Drawing grid with jQuery SVG produces 2px lines instead of 1px I know it's not the jQuery SVG library causing this issue, but when rendering horizontal or vertical SVG lines on integral x,y coordinates, lines are 2px wide instead of 1px. This is probably to do with anti-aliasing In order to get them fixed, and draw a line that's perfectly 1px wide, I need to adjust coordinates by adding 0.5px.
Is there a way to get lines 1px thick without having to tweak them like this?
A: A way to solve the problem is to apply some CSS to the lines:
.thelines{
shape-rendering:crispEdges
}
The spec chapter on shape-rendering property.
Basically it turns off antialiasing for the lines, and the lines that are NOT straight horizontal or vertical may NOT look very pretty.
But probably you'd better stick to adding .5 to the lines' coordinates, because browsers do what they are told to: the line is on exact coordinates and the stroke is painted on both sides of the line, half pixel here and half pixel there.
A: So you want one pixel wide horizontal and vertical lines to be displayed with sharp rather than fuzzy edges.
If all the co-ordinates in your SVG are integers, maybe you can offset the whole image by 0.5, by using a transform element:
// first group has no transform
// lines appear blurred, because they are centered on boundary of two pixels
<g id = "blurred">
<line x1="10" y1="10" x2="110" y2="10" stroke="black" stroke-width="1"/>
<line x1="10" y1="10" x2="10" y2="100" stroke="black" stroke-width="1"/>
</g>
// second group has half pixel transform -
// lines will appear sharp because they are translated to a pixel centre
<g id="sharp" transform="translate(0.5,0.5)">
<line x1="120" y1="10" x2="220" y2="10" stroke="black" stroke-width="1"/>
<line x1="120" y1="10" x2="120" y2="100" stroke="black" stroke-width="1"/>
</g>
But this will not work for horizontal/vertical lines which are not defined with integer coordinates, or where another transformation moves them off the integer coordinates.
So if this idea cannot be used to solve your problem, then you probably need a 'pixel-snapping' technique. This would analyse a line before drawing it. If the line is vertical or horizontal (after transformation) then you need to adjust the coordinates so that they will end up in a pixel center after transformation.
You may be interested in looking at the WPF Pixel Snapping explanation for background information regarding this common problem.
A: Just use a 1px wide rectangle with a fill (only for horizontal/vertical lines of course).
e.g. for a full width horizontal line:
<rect x="0" y="0" width="100%" height="1" fill="#c2c2c2"></rect>
Perfect 1px wide lines every time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: fb:live-stream will not work unless "post to Facebook" is checked? We had a live-stream where we would chat with our users during a live event. 3 weeks ago it stopped working when we un-check "post to Facebook" we no longer can interact with out users meaning no one can see us in the chat. it seems we HAVE to check post to Facebook in order to interact with the livestream however we don't want every comment we make to post to our page,.
Any ideas?
A: We are experiencing the same issue. You may want to subscribe to this thread in the official support forum, in case they resolve it there? They say it's "Assigned" but it is only "Mid-pri" and hasn't been updated since 9/23. http://developers.facebook.com/bugs/172406742840270?browse=search_4e8526363e1cf8f42318199
If you have another app that you know to work in the interim, there are a lot of interested folks. We've gone to an embedded IRC solution until they fix it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to turn on/off DATA programmatically without modifying APN (Gingerbread compatible)? I only found during my research solutions that either involve a modification of the APNs, or are not compatible with Android 2.3 because of its enhanced security.
Nevertheless, I am pretty sure there is a faster/cleaner way than modifying the APNs to enable/disable mobile data connectivity. Indeed, one of the most popular widgets on the market manages to do the switch very quickly and claims it does not touch APNs.
-> Do you know which API/function I should use to get similar functionality in my app ?
A: It is not possible due to security reasons. The only alternative is to modify the APN, and it is not guaranteed to work in every device.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error connecting express node.js app to redis server when using requirepass in redis.conf I'm new to node and redis and am setting up a simple server with express to communicate with redis.
After starting redis-server, I start the node server app.js
app.js starts and runs when I use the redis.conf file without requirepass, but when I add a requirepass the app crashes upon starting. I can run redis-cli in a terminal and the password works there.
I get this Uncaught error stack when running app.js:
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Uncaught, unspecified 'error' event.
at RedisClient.emit (events.js:47:15)
at Command.callback (/node_modules/redis/index.js:232:29)
at RedisClient.return_error (/node_modules/redis/index.js:382:25)
at RedisReplyParser.<anonymous> (/node_modules/redis/index.js:78:14)
at RedisReplyParser.emit (events.js:64:17)
at RedisReplyParser.send_error (/node_modules/redis/lib/parser/javascript.js:265:14)
at RedisReplyParser.execute (/node_modules/redis/lib/parser/javascript.js:124:22)
at RedisClient.on_data (/node_modules/redis/index.js:358:27)
at Socket.<anonymous> (/node_modules/redis/index.js:93:14)
at Socket.emit (events.js:64:17)
Here's the pertinent code in app.js
var REDIS_PASS = "foobar";
var express = require('express');
var app = module.exports = express.createServer();
var io = require('socket.io').listen(app);
var redisStore = require('connect-redis')(express);
var redis = require('redis');
var rdb = redis.createClient();
rdb.auth(REDIS_PASS, function(){ console.log('connected to redis-server');});
rdb.on("error",function(err){
console.log("REDIS CLIENT ERROR:" + err + '\n\n' + err.stack);
});
Here's the redis.conf file
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
#my hackerproof password:
requirepass foobar
I am still trying to get my head around the asynchronous nature of node, so I thought maybe this was a case where the auth command was being called before a connection to the redis-server was established, but when I placed the auth command into a callback for the client.on("connect" event I received the same error stack.
I wondered if catching the exception would allow the server to sweep it under the carpet and continue so I caught it using the process object. The server appears to continue running but won't serve any pages to the browser, so I'm guessing this exception can't be ignored.
A: My problem was caused by configuring my app with a RedisStore object to handle sessions. After enabling the password in the redis.conf file, the RedisStore object needed to be created with the pass option set to the password in redis.conf.
The options array is set like this:
var redisStoreOpts = {'pass':REDIS_PASS};
and the line in the app configuration is changed to look like this:
app.use(express.session({ secret: SESSION_SECRET, store: new RedisStore(redisStoreOpts) }));
I hope this is useful to anybody who runs into this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Joining tables from multiple files I am trying to join data from multiple tables that I have in different tab separated files as an example:
I have the tables:
file1.txt
a 3
b 4
c 8
d 22
e 4
file2.txt
a 10.3 -2
b 4.7 -1
c 8.9 -2
e 22.1 -1
file3.txt
b T
c F
d T
f F
g T
I would like to join them on their common key which is the first column to produce the following table:
a 3 10.3 -2
b 4 4.7 -1 T
c 8 8.9 -2 F
d 22 T
e 4 22.1 -1
f F
g T
How could I easilly achieve this with ruby..
Ted
A: I don't know of another way but this will create a hash with everything in it:
files = ['file1.txt', 'file2.txt', 'file3.txt']
result = Hash.new
files.each_with_index do |file, i|
File.foreach(file) do |line|
key, value = /(\w)\s+(.*)/.match(line).captures
result[key] = Array.new(files.size) unless result.has_key?(key)
result[key][i] = value
end
end
The hash result looks like this:
{"a" => ["3", "10.3 -2", nil],
"b" => ["4", "4.7 -1", "T"],
"c" => ["8", "8.9 -2", "F"],
"d" => ["22", nil, "T"],
"e" => ["4", "22.1 -1", nil],
"f" => [nil, nil, "F"],
"g" => [nil, nil, "T"]}
A: You could do something like this:
require 'csv'
def load(file)
CSV.open(file, :col_sep => "\t").
each_with_object({ }) { |r, h| h[r.shift] = r }
end
# Load it all into hashes with a convenient format.
# The PK will be the key, the rest of the row will be the value as an array.
file1 = load('file1.txt')
file2 = load('file2.txt')
file3 = load('file3.txt')
# Figure out the rows in the final table
rows = (file1.keys | file2.keys | file3.keys).each_with_object({}) { |k,h| h[k] = [] }
# Use the block form of Hash#merge to join.
cols = [file1, file2, file3].inject([]) {|a, f| a.push(a.last.to_i + f.first.last.length)}
joined = rows.merge(file1).
merge(file2) { |k, o, n| (o + [nil] * (cols[0] - o.length)) + n }.
merge(file3) { |k, o, n| (o + [nil] * (cols[1] - o.length)) + n }
# Patch any missing values in the last column.
joined.each { |k, v| v.concat([nil] * (cols[2] - v.length)) }
The result is a hash like this:
{"a"=>["3", "10.3", "-2", nil],
"b"=>["4", "4.7", "-1", "T"],
"c"=>["8", "8.9", "-2", "F"],
"d"=>["22", nil, nil, "T"],
"e"=>["4", "22.1", "-1", nil],
"f"=>[nil, nil, nil, "F"],
"g"=>[nil, nil, nil, "T"]}
You can easily convert that to an array of arrays if desired. Generalizing to multiple files should also be fairly straight forward. There are, of course, other ways to implement the various steps but I'll leave those refinements as an exercise.
If the files were large then you'd be better off slopping them into an SQLite database and doing the join in SQL.
A: You could try using Sequel to load the files via ODBC, or ADO if you are on Windoze, then do the join there, and output the dataset array to text file in the same format.
Or import the files into sqlite (see basic instructions here, you may need to convert tabs to a different delimiter, not sure), then do the same thing in Sequel using the sqlite adapter instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How get the width of an input element in IE? I dont work with a framework, i'm working with JavaScript by default.
I need to know the width of an input text element, in the good browsers i use:
width = document.defaultView.getComputedStyle(el, "").getPropertyValue('width');
But in the f**ing Internet Explorer use:
if (typeof el.currentStyle['width'] == "undefined" || el.currentStyle['width'] == 'NaN') {
width = el.currentStyle['width'];
} else {
width = null;
}
This works, if it is set the width by css or style propertie, but if the size is a default (set by size propertie or dont set) el.currentStyle['width'] is undefined.
I need to know the width of an element without propertie set.
A: var elwidth= el.offsetWidth+'px';
A: Just use Jquery. It has .width and .height functions which work in ie6 as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.