text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How to pass SQL Server Extended Events Activity Id from C#? I have been looking into using Extended Events in a full end-to-end tracing scenario. I am especially interested in the XEvent's activity id that helps follow event execution sequence for a given activity.
You will have guessed, my event session in SQL Server 2008 has the following option set:
TRACK_CAUSALITY = ON
My question to you is, when executing SQL queries from C# code (Linq, Entity Framework, etc...), is it possible to infer the activity id that will be traced by the extended events in SQL Server?
For instance, I would like to be able to propagate the CorrelationManager.ActivityId guid of my executing thread to SQL Server for XEvent tracing.
Many thanks
A: Extended Events doesn't track the activity_id for anything outside of SQL Server currently. TRACK_CAUSALITY is only for tracking what event in SQL Server lead to another event in SQL Server, for example a sql_statement_starting event would have a specific activity_id and seq number 1, then a subsequent file_read event would have the same activity_id and a seq of 2, a wait_info event for PAGEIOLATCH_SH would have the same activity_id and seq of 3, and so on until you got to sql_statement_completed with a final seq number for the activity_id. You find plenty of examples showing this on my blog posts about Extended Events:
http://sqlskills.com/blogs/jonathan/category/Extended-Events.aspx
If you dumped the data into the ETW target, you can merge it with an ETW trace of your application and draw loose correlations of the events based on occurence, but there is causality tracking between the two possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java Generics: How does method inference work when wildcard is being used in the method parameters? Supposedy i have the following:
class x {
public static void main(String [] args) {
List <?> a = new LinkedList<Object>();
List <? extends Object> b = new LinkedList<Object>();
List <? super Object> c = new LinkedList<Object>();
abc(a, "Hello"); // (1) Error
abc(b, "Hello"); // (2) Error
abc(c, "Hello"); // (3) ok
def(b); // (4) ok
// Showing inference at work
Integer[] a = {10, 20, 30}; // (5)
T is inferred to be ? extends Object
Method signature: ppp(? extends Object, ? extends Object[])
Method call signature: ppp(String, Integer[]);
ppp("Hello", a); // ok
}
static <T> void abc(List<T> a, T b) {}
static <T> void def(List<T> a) {}
static <T> void ppp(T t1, T[] t2){}
}
To begin with, look at clause 5 showing inference at work. Now clause 5 section is a working section.
If that is what it is, then why does clause (1) & (2) have errors?
From my view, all these 3 methods calling have the same inference generated since no actual type parameters is used on the abc method call.
method parameter <T> abc (List <T> a, T b>)
inferred <Object> abc (List <Object>, Object) // (4)
Please bear in mind, method abc() and def() is my method. Compiler doesn't know what i want to do with the List in this method. I might just print the list size or might not even do anything at all as shown above. So there is no get or set involved here.
CONTINUATION -->
This is getting very confusing for me.
class y {
public static void main(String [] args) {
List <Integer> a = new LinkedList<Integer>();
List <Object> b = new LinkedList<Object>();
ppp("Hello", new Integer(1)); // (20) ok
qqq("Hello", a); // (21) error
qqq("Hello", b); // (22) ok
}
static <T> void ppp(T t1, T t2) {}
static <T> void qqq(T t1, List <T> t2) {}
}
Note that clause 21 is the same as clause 20 except 2nd parameter is being made to be a List instead of Integer.
Clause 20 is ok cos' T is inferred to be Object.
Clause 22 is ok. Same reason as clause 20.
Clause 21 failed? T could also be inferred to be Object too - would work too?
A: The hard thing about the wildcard is to realize ? extends Foo does not mean "anything that extends Foo", but instead it means "some specific type that extends Foo". And since you are outside that definition, you have no way to know which specific sub-type of Foo it is.
Update:
As I said, it's complicated. Here are some comments on your code.
// a list of some specific type, and you don't know what type that is.
// it's a sub-type ob Object, yes, which means that you can do
// Object foo = a.get(0); , but the compiler has no way of knowing
// whether it's a String so you can't pass in a String
List <?> a = new LinkedList<Object>();
// same here. '?' and '? extends Object' are equivalent
List <? extends Object> b = new LinkedList<Object>();
// this is a list of Objects and superclasses thereof.
// since there are no superclasses of Object, this is equivalent to
// List<Object>. And through inheritance, a String is an Object, so
// you can pass it in.
List <? super Object> c = new LinkedList<Object>();
Update 2:
The problem here is that you are dealing with fixed, but unresolveable variables.
// you can pass in a List<String> and a String,
// but if you pass in a List<?>, the compiler has no idea what
// '?' is and just can't substitute 'String'.
// 'T' doesn't help you here, because 'T' can't match both
// '?' and 'String'.
static <T> void abc(List<T> a, T b) {}
// this works because 'T' substitutes '?' and doesn't have to worry
// about a 2nd parameter
static <T> void def(List<T> a) {}
Read this question, it might shed some light on the problem:
What is PECS (Producer Extends Consumer Super)?
A: You've set up a bit of a straw man by creating a LinkedList<Object> in each case. That can make it difficult to see the problem. What you have to remember is that when the compiler gets to those method invocations, it doesn't know that you created a LinkedList<Object>. It could be a LinkedList<Integer>, for example.
So let's look at your code with more interesting initializations:
List<Integer> integers = new LinkedList<Integer>();
List <?> a = integers;
List <? extends Object> b = integers;
List <? super Object> c = new LinkedList<Object>();
//INVALID. T maps to a type that could be Object OR anything else. "Hello"
//would only be type-assignable to T if T represented String, Object, CharSequence,
//Serializable, or Comparable
abc(a, "Hello");
//INVALID. T maps to a type that could be Object OR anything else. "Hello"
//would only be type-assignable to T if T represented String, Object, CharSequence,
//Serializable, or Comparable
abc(b, "Hello");
//VALID. T maps to an unknown super type of Object (which can only be Object itself)
//since String is already type-assignable to Object, it is of course guaranteed to be
//type-assignable to any of Object's super types.
abc(c, "Hello");
Integer i1 = integers.get(0);
Integer i2 = integers.get(1);
It doesn't take much to see that if the implementation of abc was this:
//a perfectly valid implementation
static <T> void abc(List<T> a, T b) {
a.add(b);
}
That you would get a ClassCastException when initializing i1.
From my view, all these 3 methods calling has the following inference generated since no actual type parameters is used on the abc static method call.
method parameter <T> abc (List <T> a, T b>)
inferred <Object> abc (List <Object>, Object) // (4)
This is categorically wrong. It is not inferred that T is Object in any of your examples, not even in the case of ? super Object. T is resolved to the capture of a, and unless you can assign a String to that capture (as is the case when it's ? super Object) you will have a type error.
Edit #1
Regarding your update (I've replaced your generic array with a List<T> since generic arrays needlessly cloud the issue):
// Showing inference at work
List<Integer> a = Arrays.asList(10, 20, 30); // (5)
T is inferred to be ? extends Object
Method signature: ppp(? extends Object, List<? extends Object>)
Method call signature: ppp(String, List<Integer>);
ppp("Hello", a); // ok
This is not correct. The crucial mistake you're making is here:
Method signature: ppp(? extends Object, List<? extends Object>)
This is not at all what the capture engine does or should translate your invocation into. It resolves T as <? extends Object> but as one specific capture of <? extends Object>. Let's call it capture-1-of<? extends Object>. Thus your method must be like this:
Method signature: ppp(capture-1-of<? extends Object>, List<capture-1-of<? extends Object>>)
This means that there is a binding between the two parameters...they must resolve to the same capture. In general it is very difficult to tell the compiler that two things are the same capture. In fact, even this is not a valid invocation of ppp (even though they are clearly the same capture):
List<? extends Integer> myList;
ppp(myList.get(0), myList);
One way we could invoke ppp is through a generic intermediary:
public static <T> void pppCaller(List<T> items) {
ppp(items.get(0), items);
}
pppCaller(myList);
The only sure-fire way you could invoke ppp with a wildcarded list would be to invoke it like this:
List<? extends Integer> myList = new ArrayList<Integer>();
ppp(null, myList);
That's because the null is the only thing that you can assign to anything. On the other hand, if you had this method:
private static <T> void qqq(T item1, T item2) {}
You could indeed invoke it like this:
List<? extends Integer> myList;
qqq(myList.get(0), myList.get(1));
Because in this case, the inference can generalize T to Object. Since List<? extends Integer> is not covariant with List<Object>, it cannot do the same for ppp().
However, what most people do to get around this is to relax their method signature. Instead, declare ppp as the following:
public static <T> ppp(T item, List<? super T> items) {
}
This follows the guidelines that Sean put in his post of "PECS"
If (your method) produces, use extends, if it consumes, use super.
Edit #2
Regarding your latest edit:
public static void main(String [] args) {
List <Integer> a = new LinkedList<Integer>();
qqq("Hello", a); // (21) error
}
static <T> void qqq(T t1, List <T> t2) {}
Object is not a valid inference for T. I think this is something fundamental you're missing, so I'll say it clear:
A List<Integer> is NOT type-assignable to List<Object>
Not at all. If it were, you could do something like this which obviously violates type safety:
List<Integer> myInts = new ArrayList<Integer>();
List<Object> myObjects = myInts; //doesn't compile!
myObjects.add("someString");
Integer firstInt = myInts.get(0); //ClassCastException!
So T cannot be inferred as Object, since it would require assigning a List<Integer> to a variable of type List<Object>.
A:
A wildcard would then needed to induce subtype covariance
I'd rather say "try to simulate" since even after using wild-cards you can't get the same functionality you get for arrays.
Then the question is why clause (3) works and not clause(2) or (1)?
Consider the first declaration:
List <?> a = new LinkedList<Object>();
This declaration effectively says, I really don't know (or care) what kind of element the collection a contains. This effectively shuts you off from "mutating" the collection since you might end up adding elements of type which are not really compatible with a. You can have List<?> a = new ArrayList<String>() but you still won't be able to put anything in it. Basically, in case an add is allowed, the compiler can't guarantee the type safety of the collection.
List <? extends Object> b = new LinkedList<Object>();
Here you say b is a collection which contains elements which extend an Object. What kind of element, you don't know. This again as per the previous discussion doesn't allow you to add anything since you could end up compromising type safety.
List <? super Object> c = new LinkedList<Object>();
Here you say, c is a collection which contains elements of type Object and it's super-classes or in other words, at least an Object. Since each reference type in Java is assignment compatible with Object, it works in the third case.
A: List<?> a means that a holds a specific type, which is unknown. Consider this more complete example:
List<Float> floats = new ArrayList<Float>();
List<?> a = floats; /* Alias "floats" as "a" */
abc(a, "Hello"); /* This won't compile... */
float f = floats.get(0); /* .. if it did, you'd get a ClassCastException */
static <T> abc(List<T> a, T b) {
a.add(b); /* Absolutely no problem here. */
}
List<? extends Object> means essentially the same thing as List<?>, and would cause the same error.
List<? super Object> means that the list holds a specific, but unknown super-type of Object, and the parameterized method can accept any object that is-a Object for the second parameter. While the method invocation is type-safe, attempting to assign an unsafe value to c will cause an error:
List<Number> numbers = new ArrayList<Number>();
List<? super Object> a = numbers; /* This won't compile... */
abc(a, "Hello");
Number n = numbers.get(0); /* ...if it did, you'd get a ClassCastException */
A: Integer[] is a subtype of Object[], however List<Integer> is not a subtype of List<Object>. This is quite confusing; arrays are more primitive and should be avoided.
If a method parameter type is T[], it accepts all S[] where S is a subtype of T.
To do this with List, the type should be List<? extends T>. It accepts all List<S> where S is a subtype of T.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How can I add a foreword or a preface before the TOC in a (pdflatex) sphinx document? How can I use Sphinx to generate a pdflatex document in which there is some text before the table of contents? The generated LaTeX file always seems to have \tableofcontents before any document-body text.
I have been unable to find any information / documentation on this, and I'd appreciate it if anyone has any tips. I am not interested in 'manual' solutions which require modifying the tex file directly -- I am looking for directives / options which can be specified directly within rst files.
A: Try setting a value for latex_elements['preamble'] in your conf.py file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: MGTwitterEngine with update_with_media Wondering if anyone has found a MGTwitterEngine that has implemented update_with_media? I am using it with OAuth / SAOAuthTwitterEngine
Thanks
A: I'm working on it but having a lot of problems. Check http://github.com/rmd6502/Twitter-OAuth-iPhone
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unable to see the resource files after localization is true I have localized a Form say BanksForm into two languages by setting the Localizable property to true and setting the Language from Default to French.
Visual Studio generated the resource files and compiles them into the application. This is what I expected, but I am not able to see the resource file for my form and it does not generate the resource file for French language.
Would anyone please help on this?
A: The compiled french resources will be stored in a dll named myapp.resources.dll located in the fr subdirectory of your app, e.g. as
c:\mysolution\myapp\bin\release\fr\myapp.resources.dll
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dojo, how destroy a custom widget? I have created a custom dijit widget which contains a grid and some buttons.
What is the right way to destroy it? override uninitialize, destroy, destroyRecursive? which method and in which order?
Thanks.
A: Generally uninitialize is the best place to do this, since it is an extension point called within the destroy function before other teardown occurs.
That said, depending on how you are adding your child widgets, you may not actually have to do anything. For instance, if you are defining your child widgets within a template, widgets declared within a template automatically get added to an array which is iterated through in destroy.
If you wanted to be sure, for testing you could connect to the destroy methods of your child widgets to log a message when they get called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How fixed tag value for text field of custom cell in table view? I am implementing a tab;e in which i have created a custom cell for cell of tableview. On custom cell i am displaying two text field , one button and one image view. Now i want implement an event on text field. That is when i click on text field then appear picker view. With the help of picker view we can change text of text field. I have applied event like as when we click on text filed then appear a picker view. But when i scroll picker view then text field value not changing. so what i will do so that it happens?
In table view i have 10 rows and i want to insert value from single picker view. I have also set tag on text field of custom cell by using this code.
cell_object.txt_time.tag=[indexpath.row];
for selection value from picker view i use this code...
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
if (pickerView == myPicker)
{
if(cell_object.txt_time.tag==0)
{
[cell_object.txt_time setText:[NSString stringWithFormat:@"%@",[array_time objectAtIndex: [pickerView selectedRowInComponent:0]]]];
}
else if(cell_object.txt_time.tag==1)
{
[cell_object.txt_time setText:[NSString stringWithFormat:@"%@",[array_time objectAtIndex: [pickerView selectedRowInComponent:0]]]];
}
}
}
I have do for 10 rows text.tag. But it is not working.
What i do ?
Thanks in advance...
A: A simple implementation would be:
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent(NSInteger)component{
NSString *string = [[NSString alloc] initWithFormat:@"%@",[myArray objectAtIndex:row]];
textfield.text = string;
}
myArray is the datasource for your UIPickerView. With the above code you will be able to tweak it to what you needed to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: django foreign key admin interface and models structure (All code is some kind of pseudocode, just for better reading
I have an Invoice model:
class Invoice(models.Model):
// many fields here
I need to attach some products (with price for unit, and quantity fields) to this invoice, so I made additional table:
class InvoiceProduct(models.Model):
product = models.ForeignKey
quantity = models.IntegerField
unit_price = models.DecimalField
invoice = models.ForeignKey(Invoice)
So, this is almost first question — «Could it be done better way?»
My second problem is, that in django admin I have manage these models by inlines:
Screenshot
But my customer wants otherwise. He wants one button (Add product) then pop-up windows appears, with fields:
product, quantity, unit price. He fills them, press OK. Then pop-up window closes and line with "product fields" appears in main form.
I suppose I need override admin form template? Or I need to write my own widget or smth like that?
Sorry for my English.
A: My suggestion for your customer's request
He wants one button (Add product) then pop-up windows appears, with fields: product, quantity, unit price. He fills them, press OK.
Do NOT use the django admin for this. Only use it for people who want to access the data almost directly. In my head I see it just one half step up from the database itself. This means it is not suitable for users rather than administrators.
Or I need to write my own widget or smth like that?
Yes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to programmatically fire ondblclick event in javascript? I am trying the following simple code (in html, using js on IE8):
<input type="image" src="pic.jpg" id="aa" ondblclick="alert('aa');"/>
<script>
document.getElementById('aa').dblclick();
</script>
and I get an error that: object doesn't support this property or method (regarding the script part). And I don't get the alert.
Whereas when I dblclick on the image, I get the alert message.
So I wish to know how to programmatically fire the dblclick event (without actually double clicking the image).
The same works just fine with onclick (instead of on dblclick).
I also tried it on button, input text. Same error .
A: The property name is ondblclick but you're attempting to call dblclick. You need to call ondblclick.
<script>
document.getElementById('aa').ondblclick();
</script>
Fiddle: http://jsfiddle.net/frwpY/
A: try this:
<input type="image" src="pic.jpg" id="aa" ondblclick="alert('aa');"/>
<script>
document.getElementById('aa').ondblclick();
</script>
http://jsfiddle.net/dnUZY/1/
A: Check out MDNs article about element.dispatchEvent
Sample code from MDN:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("checkbox");
var canceled = !cb.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
This way you can also track the event through the DOM bubble and make sure it wasn't canceled.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: a Cufon problem on a nested menu I'm building a nested navigation bar, here is the jsFiddle:
http://jsfiddle.net/3Y8vB/1/
the nested menus are on the third item, "Collezioni": so far so good. But adding Cufon triggers a strange problem: "hovering" the nested menus and going away from them all the way down, the "Collezioni" link disappears!
http://jsfiddle.net/3Y8vB/2/
Well, it doesn't really disappear: it retains the #fff color (:hover) instead of going back to #111 (normal state), and since the background is white too, it "disappears". Going all the way UP (without "hovering" the nested menus) has no problem.
I'm sure it's a Cufon related problem since the first version (without Cufon) is working nice.
Please, can you help to solve this? Thanks in advance
A: Ok, found the solution here:
https://github.com/sorccu/cufon/wiki/FAQ#wiki-faq-10
And here's the new jsFiddle:
http://jsfiddle.net/3Y8vB/3/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Preparations for Icecream sandwich and ACL usage There was a post about preparations for Andoid Icecream Sandwich release on Android Dev blog and in particular adopting your tablet UI for handsets. What if I do want to make additional resources for handsets (now I have my app for xlarge screen sizes only) and follow their instructions - how can I really test the app until the mentioned OS is shipped? If I would use Android Compatibility Library for this - will I need to re-implement certain things when Icecream is released?
A:
how can I really test the app until the mentioned OS is shipped?
You can't. You can test how it works on older phone Android OS versions (assuming your app is designed to support Android 2.x devices in addition to Ice Cream Sandwich), but you cannot test on Ice Cream Sandwich until the Ice Cream Sandwich SDK and/or devices are available.
If I would use Android Compatibility Library for this - will I need to re-implement certain things when Icecream is released?
Possibly, but hopefully not. It is impossible for us to say at this time, since we do not know what is in Ice Cream Sandwich and how it will behave. That being said, the advice given in the blog post you cited is likely to be solid advice, or else they would not have posted it mere weeks before the SDK should ship.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Perl: Constructing an array of objects Partially related to this question but different, as this is about constructor calls...
I would like to create an array of a fixed number of objects.
I could do this:
my @objects;
push( @objects, new MyPackage::MyObject() );
push( @objects, new MyPackage::MyObject() );
push( @objects, new MyPackage::MyObject() );
# ...
That's several kinds of ugly. Making it a loop is only marginally better.
Isn't there a way to create an array of (constructor-initialized) objects in Perl?
Afterthought question:
These "objects" I want to create are actually SWIG-generated wrappers for C structs, i.e. data structures without "behaviour" (other than the SWIG-generated get and set functions). I just want to pass the array as a parameter to the C function, which will fill the structures for me; do I need to call constructors at all, or is there a shortcut to having the get functions for reading the struct contents afterwards? (Yes, I am awfully new to OOPerl...)
A: There Is More Than One Concise Way To Do It:
my @objects = map { new MyPackage::MyObject() } 1..$N;
my @objects = ();
push @objects, new MyPackage::MyObject() for 1..$N;
A: You can avoid the loop and repeating the same statement by supplying multiple arguments to push:
push(@objects,
new MyPackage::MyObject(),
new MyPackage::MyObject(),
new MyPackage::MyObject());
This is possible because the prototype of push is push ARRAY,LIST.
Or you can do it in a more straightforward way with an array composer (preferable):
my @objects = (
new MyPackage::MyObject(),
new MyPackage::MyObject(),
new MyPackage::MyObject(),
);
A: You can say
@objects = (new MyPackage::MyObject(), new MyPackage::MyObject(), new MyPackage::MyObject());
A: You can construct a list of objects and assign it to your array:
my @objects= (
new MyPackage::MyObject(),
new MyPackage::MyObject(),
new MyPackage::MyObject(),
# ...
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: NSFetchedResultsController - when are delegate methods fired? I have a model with a many-to-many relationship between the following entities:
Meeting >---< Person
I'm using an NSFetchedResultsController to return all the people for a meeting (these are displayed in a custom view). The NSFetchRequest is created so:
NSSortDescriptor * lastNameSort = [NSSortDescriptor sortDescriptorWithKey: @"lastName" ascending: YES];
NSSortDescriptor * firstNameSort = [NSSortDescriptor sortDescriptorWithKey: @"firstName" ascending: YES];
request.entity = [NSEntityDescription entityForName: @"Person" inManagedObjectContext: context];
request.predicate = [NSPredicate predicateWithFormat: @"(ANY %K == %@)", @"meetings", self];
request.sortDescriptors = [NSArray arrayWithObjects: lastNameSort, firstNameSort, nil];
Calling -[Meeting addPeopleObject:] for a single person works fine - the delegate methods for the NSFetchedResultsController are fired correctly, and I can update the custom view.
I have a problem adding multiple people to a meeting. A method loops through an array of people, calling -[Meeting addPeopleObject:] for each person. The first time I do this, NSFetchedResultsControllerDelegate methods are fired after adding each person. So if I add 5 people, controllerWillChangeContent: then controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: then controllerDidChangeContent: are fired 5 times.
If I create a second Meeting object, and then add the same 5 people to this meeting, the willChange and didChange delegate methods are only fired twice, once after the first person, and once after the final person. The controller:didChangeObject:... method is called 5 times as expected, but not in the order the people were inserted.
Is this expected behaviour for an NSFetchedResultsController? Is there some cacheing causing this to happen (the NSFetchedResultsController was created with nil cache). Is there a way to force the `NSFetchedResultsControllerDelegate' methods to fire after each update?
A: Notifications are not guaranteed to show up in any kind of order so that is not an issue.
As long and the call order goes willChange-->controller:didChangeObject:--> didChange there is not a problem as long as all the changes occur between the willChange and the didChange.
Most likely, what you are seeing is the different notifications sent between first use and subsequent use. In the first use, the managed objects are most likely faults and reading them in fully (faulting or firing the fault) triggers a notification for each object. However, once they are fully active adding them all at once again just triggers a single notification.
This is probably one of Core Data's behind the scenes optimizations. As long as the table updates properly, I would worry about it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Scrollview in a RelativeLayout Shows Blank i'm trying to make that all the content i have in a view can be scroll-able and what i'm doing is adding a Scrollview to the entire relative layout but when i do this anything is shown in the view. Below is the layout code i have with the Scrollview.
<Scrollview
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroller"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="3dip">
<ImageView
android:id="@+id/peliculaPortada"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip" />
<TextView
android:id="@+id/detPeliculaTitulo"
android:textStyle="bold"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignTop="@id/peliculaPortada"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="9pt" />
<TextView
android:id="@+id/detPeliculaRestriccion"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:text="Restricción: "
android:layout_below="@id/detPeliculaTitulo"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="6pt" />
<TextView
android:id="@+id/detPeliculaGenero"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:text="Genero: "
android:layout_below="@+id/detPeliculaRestriccion"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="6pt" />
<TextView
android:id="@+id/detPeliculaDuracion"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:text="Duración: "
android:layout_below="@+id/detPeliculaGenero"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="6pt" />
<TextView
android:id="@+id/detPeliculaFechaEstreno"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/peliculaPortada"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:text="Fecha Estreno: "
android:layout_below="@+id/detPeliculaDuracion"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
android:textSize="6pt" />
<Button
android:id="@+id/sitioOficial"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/button_sitio_oficial"
android:layout_below="@+id/peliculaPortada"
android:text="Sitio Oficial"
android:layout_alignLeft="@id/peliculaPortada"
android:gravity="left|center_vertical"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:layout_toLeftOf="@id/peliculaPortada"
android:paddingTop="0pt" />
<Button
android:id="@+id/imdb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/button_link"
android:layout_below="@+id/sitioOficial"
android:text="Imdb"
android:layout_alignLeft="@id/peliculaPortada"
android:gravity="left|center_vertical"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:layout_toLeftOf="@id/peliculaPortada" />
<Button
android:id="@+id/trailer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/button_trailer"
android:layout_below="@id/imdb"
android:text="Trailer"
android:layout_alignLeft="@id/peliculaPortada"
android:gravity="left|center_vertical"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:layout_toLeftOf="@id/peliculaPortada"
android:paddingTop="0pt" />
<Button
android:id="@+id/sinopsis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/button_sinopsis"
android:layout_below="@id/trailer"
android:text="Sinopsis"
android:layout_alignLeft="@id/peliculaPortada"
android:gravity="left|center_vertical"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:layout_toLeftOf="@id/peliculaPortada"
android:paddingTop="0pt" />
<TextView
android:id="@+id/detPeliculaPresentandose"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="true"
android:layout_below="@id/sinopsis"
android:layout_toLeftOf="@id/peliculaPortada"
android:singleLine="false"
android:ellipsize="none"
android:scrollHorizontally="false"
android:layout_weight="1"
android:text="Presentandose En"
android:paddingTop="2pt"
android:textSize="7pt" />
<ListView
android:id="@+id/detPeliculaTandas"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/detPeliculaPresentandose"
android:paddingTop="3pt">
</ListView>
</RelativeLayout>
Thanks in advance for any help.
A: i found a solution through the use of an unusual method that was provided by doughw. The solution is to hack the listview to load to a full height.
Here is the link to the answer:
How can I put a ListView into a ScrollView without it collapsing?
Thanks everybody.
A: I had an issue close to what you had and my problem was using layout_width="match_parent" on items that were aligned to the left or right of another item. I changed it to layout_width="wrap_content" and everything worked perfectly after that.
A: Change the wrap_content to fill_parent in the scrollview height attribute.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: R boxplot with which function I have data from 2 field sampling campaigns. I have organised the data severeal columns and rows:
*
*Data = sample points
*Columns = elements (1,...,n) , season, Sampletype and some others.
Add. info on Columns:
*
*season = 1,2 (discriminating between seasons)
*sampletype = 1,2,3 (discriminating between sampletypes)
These 2 columns are in factor format.
What I want: A boxplot which shows the boxplot for an element i for the season 1 and for season 2 (In one graph). However, not over all sampletypes but only 1, e.g:
boxplot(element i ~ Season)
This would give me the boxplot of the data of element i over all sample types but differentiated between the seasons. But I just want it for 1 sampletype.
How do I do this?
A: Use the subset parameter:
boxplot(element~Season,data=Data,subset=sampletype==1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Packing Node.js-Scripts + node.exe into a single Executable Because Node.js now also available on Windows, I would like to share my scripts without including node.exe. Is it possible to pack the script (no more files) together with the node.exe into a single executable file?
A: You absolutely can, and it's pretty easy with JXcore.
Once you have JXcore installed on windows, all you have to do is run:
jx package app.js "myAppName" -native
This will produce a .exe file that you can distribute and can be executed without any external dependencies whatsoever (you don't even need JXcore nor Node.js on the system).
Here's the documentation on that functionality: https://github.com/jxcore/jxcore/blob/master/doc/api/jxcore-feature-packaging-code-protection.markdown
(Duplicate of https://stackoverflow.com/a/27551233/810830)
A: Have you tried WinRAR? It should give you the opportunity to create a self-extractable executable which unpacks all files to the TEMP folder. After doing this you can setup to run one exe file in the archive. Furthermore you can hide the "Unpack" dialog.
A: actually I think you can use adobe air to accomplish this, no need to include node.exe
have you ever tried to develop hybrid applications with QtWebKit, which I think might be a very good direction for you., hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is GOTO a good practice? (in this php particular case?) Im having some problems in the way a present an error mensage to my users. I "solved" the problem using two Goto instructions. Please take a look of the code:
<?php require_once("registration/include/membersite_config.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head><?php include_once("parts/head.php"); ?></head>
<body>
<div id="footerfix">
<?php include_once("parts/header.php"); ?>
<div class="container">
<div class="hero-unit">
<?php
if (isset($_GET['i'])) {
unlink("users/thumbs/" . $_SESSION["user_code"] . ".jpg");
header('Location: profile.php?i=mycv');
}
if (isset($_FILES['avatar']['tmp_name'])) {
$file_ext = end(explode('.', $_FILES['avatar']['name']));
if (in_array($file_ext, array('jpg', 'jpeg', 'png', 'gif')) == false) {
echo("<h2>Error!</h2><p>Your profile photo have to be a picture file.</p>");
goto nomore;
}
$src_size = getimagesize($_FILES['avatar']['tmp_name']);
if ($src_size['mime'] == 'image/jpeg') {
$src_img = imagecreatefromjpeg($_FILES['avatar']['tmp_name']);
} elseif ($src_size['mime'] == 'image/png') {
$src_img = imagecreatefrompng($_FILES['avatar']['tmp_name']);
} elseif ($src_size['mime'] == 'image/gif') {
$src_img = imagecreatefromgif($_FILES['avatar']['tmp_name']);
} else {
echo("<h2>Error!</h2><p>Incorrect file format.</p>");
goto nomore;
}
$thumb_w = 150;
if ($src_size[0] <= $thumb_w) {
$thumb = $src_img;
} else {
$new_size[0] = $thumb_w;
$new_size[1] = ($src_size[1] / $src_size[0]) * $thumb_w;
$thumb = imagecreatetruecolor($new_size[0], $new_size[1]);
imagecopyresampled($thumb, $src_img, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]);
}
imagejpeg($thumb, "users/thumbs/" . $_SESSION["user_code"] . ".jpg");
//header('Location: profile.php?i=mycv');
echo('<h2>Ready!</h2><p>Your profile picture is updated. <a href="profile.php">Go back</a>.</p>');
nomore:
echo "</div></div>";
include_once("parts/footer.php");
echo "</div></body></html>";
}
?>
I never understood why goto is the worst think that could happened to a code (at least, every one says that), i will like to hear your opinions about this, and if that is really the worst think ever, how still use my code whitout them? Thanks!
A: The short answers why GOTO is a bad idea: readability suffers. Consider this:
<?php require_once("registration/include/membersite_config.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head><?php include_once("parts/head.php"); ?></head>
<body><div id="footerfix">
<?php include_once("parts/header.php"); ?>
<div class="container">
<div class="hero-unit">
<?php
if(isset($_GET['i'])){ unlink("users/thumbs/".$_SESSION["user_code"].".jpg"); header('Location: profile.php?i=mycv');}
if(isset($_FILES['avatar']['tmp_name'])){
$file_ext = end(explode('.',$_FILES['avatar']['name']));
if(in_array($file_ext,array('jpg','jpeg','png','gif'))==false){
echo("<h2>Error!</h2><p>Your profile photo have to be a picture file.</p>");
}
else {
$src_size=getimagesize($_FILES['avatar']['tmp_name']);
if($src_size['mime']=='image/jpeg') {
$src_img=imagecreatefromjpeg($_FILES['avatar']['tmp_name']);
} elseif($src_size['mime']=='image/png') {
$src_img=imagecreatefrompng($_FILES['avatar']['tmp_name']);
} elseif($src_size['mime']=='image/gif') {
$src_img=imagecreatefromgif($_FILES['avatar']['tmp_name']);
} else {
echo("<h2>Error!</h2><p>Incorrect file format.</p>");
}
if(!empty($src_img)) {
$thumb_w = 150;
if($src_size[0]<=$thumb_w){
$thumb=$src_img;
}else{
$new_size[0] = $thumb_w;
$new_size[1] = ($src_size[1]/$src_size[0])*$thumb_w;
$thumb=imagecreatetruecolor($new_size[0],$new_size[1]);
imagecopyresampled($thumb,$src_img,0,0,0,0,$new_size[0],$new_size[1],$src_size[0],$src_size[1]);
}
imagejpeg($thumb,"users/thumbs/".$_SESSION["user_code"].".jpg");
//header('Location: profile.php?i=mycv');
echo('<h2>Ready!</h2><p>Your profile picture is updated. <a href="profile.php">Go back</a>.</p>');
}
}
}
?>
</div></div>
<?php include_once("parts/footer.php"); ?>
</div>
</body>
</html>
Anyway, you should consider separating your template from logic (google "MVC") and use at least functions for complex operations.
A: Your use of goto here seems reasonable to me, because you're basically using the following pattern:
if (error_condition_1) {
goto handle_errors;
} else {
// do stuff
}
if (error_condition_2) {
goto handle_errors;
} else {
// do stuff
}
// ...
if (last_error_condition) {
goto handle_errors;
} else {
// do stuff
}
// do stuff
handle_errors:
// handling errors
There are other ways to do this that don't involve goto; for example, you can use a do ... while (false) loop with break statements in the appropriate places. However, this really just obscures the fact that you're using a goto.
goto has pariah status among computer programmers, which these days is largely unfair; there are situations in which it is a perfectly reasonable choice to use goto (not the majority of situations, I hasten to add) but in general, using goto is liable to get you dogpiled whether or not it's a valid design choice.
Your main problem here, as Daniel Brockman says, is that your code is hard to read. It seems to be crammed onto as few lines as you could manage, and is very dense. Look into how others space out their code, on this site and elsewhere, and see whether you agree that code using other conventions is more readable.
In PHP you need to keep in mind that goto is available only from version 5.3, therefore if your code needs to be portable you may want to consider another option.
A: Your code is a mess. Implementing a GOTO statement would make it a nightmare.
Like XKCD show, terrible things will happen. I remember when I started learning C++, the term "Spaghetti code" often referred to goto usage. It will always mess up your execution flow. Not to mention it ruins readability.
In any case, I've restructured the program for you and it should now work.
The script
<?php require_once("registration/include/membersite_config.php");
//redirect user if i is defined
if(isset($_GET['i'])){ unlink("users/thumbs/".$_SESSION["user_code"].".jpg"); header('Location: profile.php?i=mycv');}
?>
<!DOCTYPE html>
<html lang="en">
<head><?php include_once("parts/head.php"); ?></head>
<body>
<div id="footerfix">
<?php include_once("parts/header.php"); ?>
<div class="container">
<div class="hero-unit">
<?php
check_file();
function check_file(){
//check for file
if(isset($_FILES['avatar']['tmp_name'])){
//get the file extension
$file_ext = end(explode('.',$_FILES['avatar']['name']));
//validate extension
if(in_array($file_ext,array('jpg','jpeg','png','gif')) ==false){
echo "<h2>Error!</h2><p>Your profile photo have to be a picture file.</p>";
return -1;
}
//get the image dimensions
$src_size = getimagesize($_FILES['avatar']['tmp_name']);
switch($src_size['mime']){
case 'image/jpeg':
$src_img=imagecreatefromjpeg($_FILES['avatar']['tmp_name']); break;
case 'image/png':
$src_img=imagecreatefrompng($_FILES['avatar']['tmp_name']); break;
case 'image/gif':
$src_img=imagecreatefromgif($_FILES['avatar']['tmp_name']); break;
default:
echo("<h2>Error!</h2><p>Incorrect file format.</p>");
return -1;
}
$thumb_w = 150;
//if image is within allowed dimensions, set thumbnail as image
if($src_size[0]<=$thumb_w){
$thumb = $src_img;
}else{
$new_size[0] = $thumb_w;
$new_size[1] = ($src_size[1]/$src_size[0])*$thumb_w;
$thumb= imagecreatetruecolor($new_size[0],$new_size[1]);
imagecopyresampled($thumb,$src_img,0,0,0,0,$new_size[0],$new_size[1],$src_size[0],$src_size[1]);
}
//create the updated image
imagejpeg($thumb,"users/thumbs/".$_SESSION["user_code"].".jpg");
echo '<h2>Ready!</h2><p>Your profile picture is updated. <a href="profile.php">Go back</a>.</p>';
}
}
?>
</div>
</div>
<?php include_once("parts/footer.php"); ?>
</div>
</body>
</html>
As you can see, I encapsulated the whole process within a function. This way, you can do a return statement whenever you encounter an error. Making it a function also enables for quick reuse. You could add some parameters to make it more dynamic.
A: Goto introduces problems by creating spaghetti code! In other words, you will have hard time understanding the flow of the code in a code block! It is always possible to use structured control constructs and eliminate gotos entirely! As famous computer scientist Edsger W. Dijkstra implied "Goto" considered harmful in his 1968 article "A Case against the GO TO Statement" (article retitled by editor Niklaus Wirth as "Go To Statement Considered Harmful"). Take a look at the Wikipedia entry http://en.wikipedia.org/wiki/Control_structures on control structures as a starting point.
The concept is applicable to all programming languages!
A: GOTO is not a good practice anywhere.
A: In my opinion a continue or a break would be preferable. If you get tempted to use a goto, think about the flow of your script, it's likely it can be improved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Out of Memory Exception for String, StringBuffer and StringBuilder in Android I'm facing an Out of Memory Exception while converting a 1.8MB image to bytes and then encrypt, finally converting into a string (length printed in log is 1652328). And then, I'm appending this string to some XML format to post, where the real problem arises. While appending some tags to this pictureString using StringBuffer or StringBuilder or adding to a string Out of Memory exception is occuring. How can I resolve this issue?
For small images this issue is not replicating.
The below piece of code converts a picture at path path to String.
fis = new FileInputStream(path);
buffer = new byte[fis.available()];
try {
fis.read(buffer, 0, buffer.length);
String byteString =
com.mobile.android.components.Base64.encodeBytes(buffer);
return byteString;
} catch (IOException ex) {
}
The above byteString is appended to xml post as follows.
StringBuilder pictureName = new StringBuilder();
pictureName.append(byteString ); //here array out of bound at StringBuilder.extendBuffer
..........
appending continues
UPDATED
In the above appending, encoded byteStream is encrypted using cypher AES and then appended to StringBuilder.
A: Call bitmap.recycle(); as soon as you have converted the bitmap to a byte array. This will free the native object associated with this bitmap, and clear the reference to the pixel data.
Update
Its obvious that the memory chunk read from the filestream is too large to handle. Avoid reading the whole file at once. Do it piece by piece. Append the string to the xml without using an intermediate string object.
Update 2
You could do something like this to avoid loading the whole xml file while sending it to server.
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
outputStream = new DataOutputStream( connection.getOutputStream() );
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
Then write the boundry characters, flush and close the streams.
A: Thanks everyone for the support.
I finally optimized my code to a max extent using file operations.
For encoding I used Base64.encodeFileToFile(picturePath, encodedPicturePath);
I saved the encoded image in a file.
And then for encryption,I used CypherOutPutStream where a FileOutputStream is passed in constructor.So Encryption is also done using file.
The final step is while using HttpPost,I used to send the total encrypted data as a StringEntity which is final Hurdle for OutOfMemeoryException.I changed the StringEntity to FileEntity.This reduced the heap consumption of my application and thus improved the overall performance and upload capacity.
Note:
Dont Encrypt the encoded image in chunks which will change the overall encoded data.Do it inn a single piece.
Failures:
Before i used files for Encoding ,I chunked the whole picture and encoded to a file.But,If i decode the encoded file,I failed to get the original picture.
Regards,Sha
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Axi2 client made with wsdl2Java uses UTF-8 instead of UTF-16 I'm using Axis2 1.6.1 to create a webservice, both the server and the client. The webservice is pretty simple: it receives two strings and returns an array of bytes. The issue I'm finding is that the client is sending the request encoded as UTF-8, so when I send a text in Spanish with accents, they get replaced by some strange characters. How can I force the client to use UTF-16?
Thanks
Jose Luis
A: you need to set it as a service client property. Please have a look at here[1].
[1] http://wso2.org/library/230
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: TYPO3: extension with both backend module and frontend plugin I am trying to create an extension ('XML Uploader') with a backend module and a frontend plugin also.
The backend module will be used for managing xml files (upload, validate against a DTD), and the frontend plugin should be used for displaying the uploaded xmls.
The problem is with the frontend part:
I followed
the basic extension tutorial - added a new page, created a content element of type 'Insert plugin' - but when trying to add a new record, the type 'XML Uploader' does not appear in the list of new record types. Moreover, the changes made to class.tx_xmluploader_pi1.php have no effect.
So how should I work with the frontend plugin? Or would it be better to create a separate extension instead?
Any help would be very much appreciated.. Thank you.
A: *
*When creating your table with the extension kickstarter you must check the "Allowed on pages:" checkbox to allow records from this table to be created on regular pages.
*If your changes have no effect, it could be that the page is cached by typo3. In that case you can clear or disable the cache with the admin panel or in the page configuration menu.
A: You have to include the static template of your extension (I presume you used the kickstarter or extension_builder):
go to the your template, in the object browser you should see something like:
plugin.tx_xmluploader_pi1 = USER
if you can't find it, edit your template (edit/modify => edit whole template record) and add your extension template in the tab 'Includes'
Additionally, check your ext_localconf.php for the line
t3lib_extMgm::addPItoST43($_EXTKEY, 'pi1/class.tx_xmluploader_pi1.php', '_pi1', 'list_type', 0);
This is where your FE plugin is being registered.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Socket.bind to all ips - An invalid argument was supplied I want to bind the socket to all the IP addresses available on the machine using:
mainSocket.Bind(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0)); //or IPAddress.Any
but I get an An invalid argument was supplied on
mainSocket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);
Instead, when I specify the IP, it works just fine.
Ok maybe that's impossible to achieve. But how about detecting which internet interface is being used to connect to internet and getting it's ip? (assuming user is behind NAT / router)
A: I think it's not possible.
Operation with sockets has limitations according to this document
TCP/IP Raw Sockets
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can we confgure filters only for a subset of servlets I have various different categories of servlets. Can I configure the filters in my web.xml such that each filter only applies for one of the categories of servlet.
A: You can map them on <servlet-name> instead of <url-pattern>.
<filter-mapping>
<filter-name>yourFilterName</filter-name>
<servlet-name>yourServlet1Name</servlet-name>
<servlet-name>yourServlet2Name</servlet-name>
<servlet-name>yourServlet3Name</servlet-name>
</filter-mapping>
The <servlet-name> must exactly match the same value as in <servlet> definition. This way the filter will be invoked whenever either of those servlets are to be invoked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Understanding ruby splat in ranges and arrays I'm trying to understand the difference between *(1..9) and [*1..9]
If I assign them to variables they work the same way
splat1 = *(1..9) # splat1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
splat2 = [*1..9] # splat2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
But things get weird when I try to use *(1..9) and [*1..9] directly.
*(1..9).map{|a| a.to_s} # syntax error, unexpected '\n', expecting tCOLON2 or '[' or '.'
[*1..9].map{|a| a.to_s} # ["1", "2", "3"...]
I'm guessing part of the problem is with operator precidence? But I'm not exactly sure what's going on. Why am I unable to use *(1..9) the same I can use [*1..9]?
A: I believe the problem is that splat can only be used as an lvalue, that is it has to be received by something.
So your example of *(1..9).map fails because there is no recipient to the splat, but the [*1..9].map works because the array that you are creating is the recipient of the splat.
UPDATE:
Some more information on this thread (especially the last comment): Where is it legal to use ruby splat operator?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Serializing a complex object ORM Entity dealing with relational entities In ColdFusion 9 I am serializing an ORM entity. When doing this, though, it's missing relational entities.
The serializeJSON() method ColdFusion uses to convert complex objects into JSON notation doesn’t seem to work correctly on ORM objects. Any object that had a property that was an array of other objects is not returned when using serializeJSON() on ORM objects!
Has anyone tackled this sort of issue before? How did you handle it?
Thanks.
A: Issue resolved! This is not a bug you have to set remotingFetch to true! By default it is set to false for properties with one-to-one, one-to-many, many-to-one, or many-to-many relationships.
A: I've run into similar issues with remote methods and came up with a recursive function that will introspect your CFC and send back the properties you need. You can specify (with attributes on the CFC) which properties you do and don't want to return. Actually, you can do it by "groups" of properties, so you could assign "id" and "name" to the "compact" group and the rest of the properties in your CFC to the "full" group. It will also handle serializing nested components (ORM or otherwise). The other big advantage is that Adobe's serialization methods do not serialize properties from inherited objects. So if you have a parent object, you will not get those properties back when serialized. My toSerializable() method solves that.
Check it out: http://www.justcodefaster.com/blog/2012/07/toserializable-method-for-coldfusion-objects/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Best way to load an external page into the current one with Webkit/jQuery I would like to load a complete HTML page into the current one using standard web technologies on an iPad web app (no framework like Sencha, etc.)
I have a content page, and an article page. I want to load the article page (including javascript/CSS for this specific page) into a new div and animate the transition (sliding) but it does not seem to work.
Using jQuery load function, the CSS/JS is not perfectly loaded and it works only on Chrome (not on the iPad). Is there a better way to do so?
CSS:
#content-container {
}
#article-container {
position: absolute;
left: @defaultWidth;
width: 100%;
height: 100%;
background-color: @darkGreyColour;
-webkit-transition: left 1s ease-in;
}
#content-container.animate {
left: -100%;
}
#article-container.animate {
left: 0;
}
JS
function animateTransition(event) {
$('#article-container').load('/ #main', function() {
console.log("Animating...");
$('#content-container').addClass('animate');
$('#article-container').addClass('animate');
});
}
A: I would recommend using an <iframe> to load a full HTML page. Using jQuery's .load() to load a portion of a full html page (ex. $("#myElement").load("/index.html #main") ) only loads the html in that portion of the document, so it won't load the js / css that's defined in other portions of the article page. You can read more about the issue in the 'Loading Page Fragments' section of jQuery's .load API Page.
Using an <iframe>:
<iframe src="theArticle.html">
<p>Your browser does not support iframes.</p>
</iframe>
Using jQuery and .load() to load the article into the <div>:
function animateTransition(event) {
// load the html contained in the tag with id of #main
$('#article-container').load('myArticle.html #main', function() {
// load the css
$('head').load('myCSS.css', function() {
// load the js
$.getScript('myScript.js', function() {
console.log("Animating...");
$('#content-container').addClass('animate');
$('#article-container').addClass('animate');
});
});
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Taking a stack and printing it in reverse order in UART So basically I have a class where the teachers designed the program that we use, and they basically said "Do these labs with no background information".
Right now I have to make a RPN calculator using assembly and I have gotten all of it coded except i have to print it in reverse order (the stack).
It would be easy, except we are using 2 digit numbers in each stack slot.
My simple question is how can I take a 2 digit number and split it into each bit.
An example would be having the number 52 and splitting the bits into 5 (then sends through 5 in UART) and 2 (then sends 2 through UART) so the output would be 52.
A: To get the digits of a number, divide by the base (in this case base 10 I assume). The remainder is the least significant digit; the quotient is the remaining digits. Repeat for more digits.
With no divide instruction, and only two digits, here's a cheesy approach:
quotient = 0;
while (number >= 10)
{
number = number - 10;
quotient = quotient + 1;
}
print msdigit;
print number;
Make sure number is positive first!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Inline expressions in HQL What is the most effective way to write this sql query in HQL
select uar.*, (a.default_user_asset_role_id is not null) as is_default from User_asset_role uar
left outer join account a on a.default_user_asset_role_id = uar.id
where uar.account_id = 3
example results
1 role_read Role Read TRUE
2 role_admin Role Admin FALSE
3 role_write Role Write FALSE
A: You can use HQL's CASE expression:
select uar.*, CASE WHEN a.default_user_asset_role_id is null THEN 0 ELSE 1 END as is_default from User_asset_role uar
left outer join account a on a.default_user_asset_role_id = uar.id
where uar.account_id = 3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jackson JSON java class - fields are serialized multiple times I have a following class defined
@JsonTypeName("PhotoSetUpdater")
public class PhotoSetUpdater {
@JsonProperty("Title")
private String title;
@JsonProperty("Caption")
private String caption;
@JsonProperty("Keywords")
private String[] keywords;
@JsonProperty("Categories")
private int[] categories;
@JsonProperty("CustomReference")
private String customReference; // new in version 1.1
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getCustomReference() {
return customReference;
}
public void setCustomReference(String customReference) {
this.customReference = customReference;
}
public void setKeywords(String[] keywords) {
this.keywords = keywords;
}
public String[] getKeywords() {
return keywords;
}
public void setCategories(int[] categories) {
this.categories = categories;
}
public int[] getCategories() {
return categories;
}
}
The problem is that after I serialize this class with Jackson JSON serializer, the fields are insetrted twice in the result payload: one starting with lower letter, one with capital letter:
... {"Caption":"aa","caption":"aa",...}
What may be wrong with type definition?
Regards
A: Try using @JsonAutoDetect(getterVisibility=Visibility.NONE) on the class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Should i use index when using where clause in mysql? i have a table that stores about 50k rows and here's my query :
select * from video where status = 1 and filter = 1 and category = 4
these columns are tinyint and i wonder should i do index on these columns ?
A: No!
You should always consider index selectivity! If the result of a where clause on an index will return more than 20% of the table, then the index is NOT used, but it's mantained.
So, for example, the status of your video will be 1, 2, 3, then you have 3 posible states. If those indexes are well distributed we can think that will be 33.3% of them aprox. Then, the query:
select * from video where status = 1
will NOT use that index! Instead, a FULL TABLE SCAN would be used.
Please, read about it. It's really important and a common mistake.
Google search
A: If you create an index for this query, try (status, filter, category) (the order may be different).
But it depends on what percent of your table rows have (status, filter, category) = (1,1,4). The smallest percent, the better your query will run using the index. As santiagobasulto noted, if the index selectivity is not high, the index will not be used for the query anyway but a full scan of the table will be run.
A: I would definitely use indexes. They make the select faster. But then if there are a lot of inserts into the table, then I would think again. Indexes on insert statements adds a lot of overload and your insert statement will be slow as it has to restructure the indexes every time you make an insert.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails 3.1 on Heroku Bamboo Can someone point out to some nice guide for deploying a Rails 3.1 on Heroku Bamboo stack?
A: Just turn off the asset pipeline for your Rails 3.1 app and it should work.
A: If you use capistrano add load deploy/assets to your Capfile
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: ASP.NET memory problem I have an ASP.NET application that communicates with another API and processes a lot on Page_Load.
If in my browser I hold F5 and hit the site, the server shoots from 120mb to 1.5GB.
I can't find any memory leaks or unclosed objects. Is there any way or extra things I can do to help?
Thank you for your time!
A: Use a profiler like ANTS Profiler or dotTrace.
There are many, many things that could cause that behavior - trying to solve the problem with arbitrary suggestions probably won't get us anywhere.
Once the profiler has identified problem areas, you can post that code in a new question if you aren't able to resolve that problem.
For what it's worth, 1.5 GB isn't huge. Does it eventually give an OutOfMemoryException if you keep the button pressed?
A: I would suggest looking into ANTS Memory Profiler and/or ANTS Performance Profiler from Red Gate. They're very affordable, and they do a great job of identifying bottlenecks.
ANTS Memory Profiler:
http://www.red-gate.com/products/dotnet-development/ants-memory-profiler/
ANTS Performance Profiler:
http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/
A: +1 to "profile and figure out problems" - knowing what is happening is must if you want to solve the issue.
But in short term it may be cheaper and easier to move to decent 64 bit box/64 bit version of Windows and use 64 bit ASP.Net - you'll get much more memory available to IIS process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Oracle job alert notification I am running oracle 11g. I try to setup an email notification for a job.
BEGIN
DBMS_SCHEDULER.add_job_email_notification (
job_name => 'JOB_COLLECT_SESS_DATA',
recipients => 'kaushik.guha@bmo.com',
events => 'job_failed'/*,
filter_condition => ':event.error_code=600'*/);
END;
/
And I get:
PLS-00302: component 'ADD_JOB_EMAIL_NOTIFICATION' must be declared
Is it some issue related to privileges?
A: That function exists in 11.2 but not in 11.1.
You may be able to reproduce that functionality by creating another job that looks at job statuses:
select *
from dba_scheduler_job_run_details
where job_name = 'JOB_COLLECT_SESS_DATA'
and status = 'FAILED'
and additional_info like 'ORA-00600%'
order by log_id desc;
That query works at least for some errors. But ORA-00600 errors are always special and may not always show up in that table for all I know. You'll want to test this carefully.
A: I set up a perl script which runs periodically as a cron job, which prints warnings when errors in the DBMS-jobs have occured. Because my crontab has a MAILTO=<email@domain.com> setting, all warnings are going to be sent to me by email.
my $dbh = ... # set up a database connection using DBI
my $jobs = $dbh->selectall_arrayref("SELECT * FROM USER_JOBS", { Slice=>{}});
for my $job ( @$jobs ) {
if ($job->{NEXT_DATE} eq '01-JAN-4000') {
warn "DBMS-Job $job->{WHAT} is currently stopped.\n";
warn "Last running at: $job->{LAST_DATE} $job->{LAST_SEC}\n";
}
elsif ( $job->{FAILURES} ) {
warn "DBMS-Job $job->{WHAT} has failures.\n";
warn "Last running at: $job->{LAST_DATE} $job->{LAST_SEC}\n";
}
else {
warn "DBMS-Job $job->{WHAT} is broken.\n";
warn "Last running at: $job->{LAST_DATE} $job->{LAST_SEC}\n";
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why was "this" used as a non const deprecated in C++ Why was this deprecated in C++? How is the this pointer in C++ different than this in Java?
Or is Wikipedia just wrong
Early versions of C++ would let the this pointer be changed; by doing
so a programmer could change which object a method was working on.
This feature was eventually deprecated, and now this in C++ is const .
A: You misinterpreted the quote.
Early versions of C++ would let the this pointer be changed; by doing so a programmer could change which object a method was working on. This feature was eventually deprecated, and now this in C++ is const.
What's deprecated is this — the pointer, not the object it points to — being mutable.
this itself is still very much alive, with the type prvalue T*. (GCC simulates this for the time being, by making this a rvalue T* const in current GCC 4.7.0.)
A: Based on your edit, the Wikipedia article is poorly worded. this is not deprecated, just that the feature to allow this pointer to be changed has been deprecated. The keyword this still exists.
From Stroustrup himself:
Why is "this" not a reference?
Because "this" was introduced into C++ (really into C with Classes)
before references were added. Also, I chose "this" to follow Simula
usage, rather than the (later) Smalltalk use of "self".
A: I believe your mistake is in how you interpret that line. They're not saying "The this feature was deprecated". Merely the ability to reassign the this pointer was deprecated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Proper Context Usage of this keyword within a method callback I am trying to get the correct context of "this" when calling a method inside a prototype. It appears that the this keyword is referencing the callback method and not the prototype object that that $.getJSON is being used on. How do I correctly call the object's Timer within the getJSON callback?
function Stocks()
{
var Timer;
}
Stocks.prototype.GetQuote = function ()
{
var requestURL = ""; //Some URL filled
$.getJSON(requestURL, function(result)
{
//Error Line
clearTimeout(this.Timer); //This is the wrong context
});
this.Timer = setTimeout(this.QueryRequest.bind(this, ''), 1000);
}
Stocks.prototype.QueryRequest= function ()
{
console.log('Requested');
this.Timer = setTimeout(this.QueryRequest.bind(this, ''), 1000);
}
A: You can bind the function, which will force the function to be run with a certain this value:
$.getJSON(requestURL, (function(result) {
// this 'this' is the same 'this' as before and after
// the JSON call due to .bind
this.Timer.clearTimeout();
// create a new function with a fixed 'this' value. To be specific, set it to
// the current 'this' value so that the inner and outer 'this' value are equal
}).bind(this));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android 3.x emulator app launcher not working I'm trying to check how a web page is displayed in the Android emulator browser, but seems that I'm out of luck today.
I just installed the new API 13 AVD, launched it with WXGA resolution and realised that it was unusable (it hanged).
Then I edited the configuration and now it is only 640x480. The GUI has changed a little, but still it hangs when I try to open the applications launcher (to find the browser icon). Only the notifications slider works, but is really slow.
How can I open the browser?
Thanks.
A: Ok, I managed to do it. Here's what I've done:
*
*In Android SDK and AVD manager, increased hw.RamSize and vm.heapSize
*The portrait orientation (CTRL+F11) seems a bit more responsive than the landscape one.
*Sometimes playing with F4 (end call button) helps unfreezing the GUI.
But in general, I've noticed hangs, GUI unresponsiveness, and when it works it is really slow. Seems that it is something related to the screen size. Or maybe it needs a ton of RAM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Autofac resolve question about keyed registration via IIndex This is a follow-up question to Configuring an Autofac delegate factory that's defined on an abstract class. I've implemented the suggestion of using IIndex<K,V> that @Aren made in his answer, but I'm unable to overcome the following error:
Test method IssueDemoProject.WidgetTest.ProblemIllustration threw
exception: Autofac.Core.DependencyResolutionException: None of the
constructors found with 'Public binding flags' on type
'IssueDemoProject.WidgetWrangler' can be invoked with the available
services and parameters: Cannot resolve parameter
'IssueDemoProject.WidgetType widgetType' of constructor 'Void
.ctor(Autofac.IComponentContext, IssueDemoProject.WidgetType)'.
UPDATE: It should be noted that if I register different concrete classes based on a parameter, that works. See the second test below.
Here is some sample code that illustrates the issue. [EDIT: I updated the same to use an IIndex lookup.]
Can someone tell me what I'm doing wrong?
using Autofac;
using Autofac.Features.Indexed;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace IssueDemoProject
{
public enum WidgetType
{
Sprocket,
Whizbang
}
public class SprocketWidget : Widget
{
}
public class WhizbangWidget : Widget
{
}
public abstract class Widget
{
}
public class WidgetWrangler : IWidgetWrangler
{
public Widget Widget { get; private set; }
public WidgetWrangler(IComponentContext context, WidgetType widgetType)
{
var lookup = context.Resolve<IIndex<WidgetType, Widget>>();
Widget = lookup[widgetType];
}
}
public interface IWidgetWrangler
{
Widget Widget { get; }
}
[TestClass]
public class WidgetTest
{
// NOTE: This test throws the exception cited above
[TestMethod]
public void ProblemIllustration()
{
var container = BuildContainer(
builder =>
{
builder.RegisterType<WidgetWrangler>().Keyed<IWidgetWrangler>(WidgetType.Sprocket).
InstancePerDependency();
builder.RegisterType<WidgetWrangler>().Keyed<IWidgetWrangler>(WidgetType.Whizbang).
InstancePerDependency();
}
);
var lookup = container.Resolve<IIndex<WidgetType, IWidgetWrangler>>();
var sprocketWrangler = lookup[WidgetType.Sprocket];
Assert.IsInstanceOfType(sprocketWrangler.Widget, typeof(SprocketWidget));
var whizbangWrangler = container.ResolveKeyed<IWidgetWrangler>(WidgetType.Whizbang);
Assert.IsInstanceOfType(whizbangWrangler.Widget, typeof(WhizbangWidget));
}
// Test passes
[TestMethod]
public void Works_with_concrete_implementations()
{
var container = BuildContainer(
builder =>
{
builder.RegisterType<SprocketWidget>().Keyed<Widget>(WidgetType.Sprocket).
InstancePerDependency();
builder.RegisterType<WhizbangWidget>().Keyed<Widget>(WidgetType.Whizbang).
InstancePerDependency();
});
var lookup = container.Resolve<IIndex<WidgetType, Widget>>();
var sprocketWrangler = lookup[WidgetType.Sprocket];
Assert.IsInstanceOfType(sprocketWrangler, typeof(SprocketWidget));
var whizbangWrangler = container.ResolveKeyed<Widget>(WidgetType.Whizbang);
Assert.IsInstanceOfType(whizbangWrangler, typeof(WhizbangWidget));
}
private IComponentContext BuildContainer(Action<ContainerBuilder> additionalRegistrations)
{
var assembly = GetType().Assembly;
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(assembly).AsSelf();
additionalRegistrations(builder);
IComponentContext container = builder.Build();
return container;
} }
}
A: I think you are going about this wrong. Mainly because your WidgetWrangler is expecting both the factory (IIndex<,> effectively becomes your factory), and a WidgetType.
The exception is because your WidgetType enum doesn't have a default registration in Autofac, and it probably shouldn't. Autofac cannot figure out what value to pass into the constructor as I'm guessing you're trying to use Autofac to Reolve your WidgetWrangler.
In order to resolve something from Autofac, it must contain at least one constructor that can be resolved entirely by Autofac's Registrations, OR with you explicitly passing variables to the resolve operation (please note, this method is reflective and extremely slow).
I am assuming the goal of this whole thing is to have some way to retrieve a new Subclass of Widget given a WidgetType somewhere. If this is the case, then ALL YOU NEED is the IIndex<,>.
Wherever you need to create new Widgets you just use the IIndex<,> type. It's simple.
If you need to perform another operation along with your instantiation you should wrap the IIndex in a factory class that uses IIndex then performs the actions.
For Example:
class Widget
{
// Stuff...
public virtual void Configure(XmlDocument xmlConfig)
{
// Config Stuff
}
}
interface IWidgetFactory
{
Widget Create(WidgetType type, XmlDocument config);
}
class WidgetFactory : IWidgetFactory
{
private readonly IIndex<WidgetType, Widget> _internalFactory;
public WidgetFactory(IIndex<WidgetType, Widget> internalFactory)
{
if (internalFactory == null) throw new ArgumentNullException("internalFactory");
_internalFactory = internalFactory;
}
public Widget Create(WidgetType type, XmlDocument config)
{
Widget instance = null;
if (!_internalFactory.TryGetValue(type, out instance))
{
throw new Exception("Unknown Widget Type: " + type.ToString);
}
instance.Configure(config);
return instance;
}
}
You can then just used the wrapped factory simply:
class SomethingThatNeedsWidgets
{
private readonly IWidgetFactory _factory;
public SomethingThatNeedsWidgets(IWidgetFactory factory)
{
if (factory == null) return new ArgumentNullException("factory");
_factory = factory;
}
public void DoSomething()
{
Widget myInstance = _factory.Create(WidgetType.Whizbang, XmlDocument.Load("config.xml"));
// etc...
}
}
Remember, If you don't need to do anything other than get the Widget instance back, your IIndex<WidgetType, Widget> is a factory in itself. (assuming all registered Widget subclasses are InstancePerDependency registered. Otherwise it's an instance selector.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How many successive calls is too many? I'm debugging some code and see a loop where an event is dispatched and a remote call is made for every record.
Everything was working fine until there were several hundred records (700) to be a exact. Is that going to make the flash player chug? Should I move to a queued system? How many records is too many?
Thanks for any helpful tips.
Here is the updated method that sends the successive calls out:
var counter:int= 0;
for each ( var item:ObjectVo in itemColl)
{
counter = counter + 1;
var evt:DataValidationEvent = new DataValidationEvent();
evt.myItem = item;
evt.eventType = DataValidationEvent.EVENT_TYPE_PASTE_FROM_EXCEL
if( counter == ( itemColl.length ) ){
evt.isLastCall=true;
}else{
evt.isLastCall=false;
}
evt.dispatch();
}
This is the event handler. It gets called only once, after 'isLastCall' is set to true.
private function addItemsFromList( item:itemVo ):void{
var myObj:ObjVo = new ObjVo();
myObj.description = item.description;
myObj.rule = item.objRule;
this.itemsColl.addItem( myObj );
this.itemsColl.itemUpdated( myObj );
this.itemsColl.refresh();
}
A: If you're making several hundred remote calls, it might just as well be the server, that's giving up on you. I'd be wondering if Flash Player is the real bottle-neck here. The AVM2 can make a few thousand calls within a few milliseconds.
All I can advise with this little information is to measure the time your loop takes to complete and if it's really that loop that takes time, try to find the most expensive bits by selectively commenting out parts of the loop body.
edit:
Good tweening engines peak at animating a handful of properties on 25K objects at 60FPS, which is well over a million calls (and rendering of 60 frames) per second. Something must be quite wrong with your code.
Things that are slow about your code:
*
*instantiation is orders of magnitude more expensive than simple calls. In performance critical scenarios (which this one actually isn't), you're far better off with object pooling or restricting yourself to primitives.
*calling function objects instead of methods is also slow - as a consequence of this and the previous problem, the commonly practiced event mechanisms are slow as hell. Still 700 per frame should be no problem.
*the last bit seems the most disturbing one. without knowing what handles the event, it's hard to know, but worst case with every event dispatched, you process all the items, which gives you O(N^2) runtime cost and results in N*(N+1) the cost of a single iteration and if a single iteration means redrawing the grid, then this can really go wrong. In any case, I think dispatching one event after the whole loop should suffice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: moving an appended input after clicked span. Im working on a text editor simulation that appends an input to a div, and extracts its values to create spans, here is the initial click() function:
var $cursorStart= $("#cursor-start");
$("#main-edit").click( function() {
var cursorExists = $("#cursor").length;
if (!cursorExists){
$cursorStart.append("<input type='text' id = 'cursor' />");
$("#cursor").markCursor();
}
if (cursorExists){
$("#cursor").focus();
}
});
When I start typing, spans are inserted before the input:
jQuery.fn.enterText = function(e){
var $cursor = $("#cursor");
if( $cursor.val() && e.keyCode != 32 ){
var character = $("#cursor").val();
$cursor.val("");
character = character.split("").join("</span><span class='text'>");
$("<span class = 'text'>"+character+"</span>").insertBefore($cursor);
}
What I want to know now is, how can I move the input (cursor) around (basically be inserted after a clicked span).
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
clicking near a and b would result in an input after "a". These are spans that are dynamically added.
A: After adding the new span, you can bind a new click event to it:
$("<span class = 'text'>"+character+"</span>").insertBefore($cursor);
$cursor.prev().click(function(){
$(this).after($cursor);
});
You could also use jQuery's .live() function, but this is generally not a good solution because it is so expensive.
A: Check out jQuery caret plugin for x-browser compatible functions for managing the caret position or selection in a textbox or textarea. This will allow you to move the "input cursor" around, as you described it :-)
This is assuming "What I want to know now is, how can I move the input (cursor) around" was your question, which I'm not 100% clear on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to remove magic quotes if php.ini/.htaccess are not editable? For some reason, all my quotes are being escaped and displayed as \". Previously, it was okay. Then I looked at phpinfo() and saw that my magic_quotes_gpc is turned on. However, I cannot find the directory /usr/local/lib/ where php.ini file is and I cannot edit my .htaccess file (gets 500 Internal Server Error).
I tried putting this instead on top of my scripts file (which is included in all pages):
if (get_magic_quotes_gpc()) {
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process)) {
foreach ($val as $k => $v) {
unset($process[$key][$k]);
if (is_array($v)) {
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
} else {
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
But still, the " and ' on my pages still have the backslashes in them.
What am I doing wrong?
A: Give this code a try, it's worked for me in the past.
<?php
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
$quotes_sybase = strtolower(ini_get('magic_quotes_sybase'));
$unescape_function = (empty($quotes_sybase) || $quotes_sybase === 'off') ? 'stripslashes($value)' : 'str_replace("\'\'","\'",$value)';
$stripslashes_deep = create_function('&$value, $fn', '
if (is_string($value)) {
$value = ' . $unescape_function . ';
} else if (is_array($value)) {
foreach ($value as &$v) $fn($v, $fn);
}
');
// Unescape data
$stripslashes_deep($_POST, $stripslashes_deep);
$stripslashes_deep($_GET, $stripslashes_deep);
$stripslashes_deep($_COOKIE, $stripslashes_deep);
$stripslashes_deep($_REQUEST, $stripslashes_deep);
}
A: Which PHP-version do you use?
If you use a version larger than 5.2, than you can use filter_input() or filter_input_array(). It seems that it ignores the setting of the magic_quotes_gpc-directive and uses the raw data (the default filter is FILTER_UNSAFE_RAW)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Trouble with String.split in F# I am having trouble with the following code, I am trying to build a lexer.
Again I am using the examples from F# for Scientists.
let lines_of_file filename =
seq { use stream = File.OpenRead filename
use reader = new StreamReader(stream)
while not reader.EndOfStream do
yield reader.ReadLine() };;
let read_matrix filename =
lines_of_file filename
|> Seq.map (String.split [' '])
|> Seq.map (Seq.map float)
|> Math.Matrix.of_seq;;
I have the following namespaces declared:-
open System
open System.IO
open System.Runtime.Serialization.Formatters.Binary
open Microsoft.FSharp.Core
But in the read_matrix function the "split" in "Split.string" is not recognised. Also the intellisense does not recognise "Matrix".
I have tried declaring a lot of namespaces to see if they recognise the method, but nothing works (my intellisense does not even recognise System.Math).
I apologise if this is a stupid question, I have looked all over MSDN and elsewhere but I could not find anything.
Can anyone help me to get VS to recognise "split" and "Matrix"?
Many thanks.
A: There are a few problems. Your casing is wrong. It's Split, not split. It's an instance (not static) method. The separators must be an array, not list. The following works:
let read_matrix filename =
lines_of_file filename
|> Seq.map (fun line -> line.Split ' ')
|> Seq.map (Seq.map float)
|> Math.Matrix.ofSeq
Incidentally, Math.Matrix.of_seq has been deprecated. It is now Math.Matrix.ofSeq.
A: A common thing to do to make instance methods more natural to use in F# is to define simple helper functions:
let split separators (x:string) = x.Split(separators)
// Can now pipe into it:
lines_of_file filename
|> Seq.map (split [|' '|])
A: As for the Math.Matrix method, it is from the f# powerpack that you need to install...
you can read this Stackoverflow thread..
what-happened-to-microsoft-fsharp-math-matrix
Also for the Split issue.. Split is a method on a string instance.. You can not call it as a static method as you did..
ex: "Some string value".Split([|' '|]) is a correct approach to split a string passing the list of delimiters as an array
A: Also for the Split issue.. Split is a method on a string instance.. You can not call it as a static method as you did..
ex: "Some string value".Split([|' '|])
is a correct approach to split a string passing the list of delimiters as an array
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hadoop streaming example failed Type mismatch in key from map
Possible Duplicate:
hadoop-streaming example failed to run - Type mismatch in key from map
When I ran Hadoop streaming example, it failed with Type mismatch in key from map
Hadoop version 0.21.0
input file content:
adfad
adfasdflkjlj
Command line: $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar \
-input myInputDirs \
-output myOutputDir \
-mapper org.apache.hadoop.mapred.lib.IdentityMapper \
-reducer /bin/wc
Error I got:
java.lang.Exception: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, recieved org.apache.hadoop.io.LongWritable
Please advise. What did I do wrong? Thanks
A: EDIT: Sorry, didn't realize this is Streaming. You need to customize how your output is split into Key/Value pairs. The documentation is here: http://hadoop.apache.org/common/docs/current/streaming.html#Customizing+How+Lines+are+Split+into+Key%2FValue+Pairs
The error message gives you all that you need to know. Your mapper is defined as outputting LongWritable keys: `Mapper`, and your Reducer expects Text: `Reducer.`
You need to redefine one or the other of them.
A: It's a known bug in the release versions of Hadoop. It has been fixed in the code, but has to be released. Alternate solution provided here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Excluding elements in XQuery I have an XML element such as:
<items>
<item>
<size>360</size>
<quantity>400</quantity>
<item>
<item>
<size>540</size>
<quantity>1200</quantity>
<item>
<item>
<size>360</size>
<quantity>600</quantity>
<item>
<item>
<size>800</size>
<quantity>750</quantity>
<item>
</items>
What I need to do is iterate over this element and pull out ONLY the first item elements with a distinct size element. So I want to have:
<item>
<size>360</size>
<quantity>400</quantity>
<item>
<item>
<size>540</size>
<quantity>1200</quantity>
<item>
<item>
<size>800</size>
<quantity>750</quantity>
<item>
Removing the second item element with a size of 360. Is there a way of filtering these out in a for loop filter statement?
A: One way is:
for $item in $items
where $item is $items[size = $item/size][1]
return $item
another is
let $sizes = distinct-values($items/size)
for $size in $sizes
return $items[size = $size][1]
and yet another (more evil) way is
$items[index-of($items/size, size)[1]]
A: Is the following query helping?
for $item in $items
let $size := number($item/size/text())
return
if($size != 360) then
$item
else ()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: WIA's ShowAcquireImage only saves in BMP? I am using the WIA 2.0 library within Delphi XE to automate scanning. I am using the "ShowAcquireImage" function to provide an image to be saved to disc. I want to save the image in a compressed format such as png or jpg, but the library only seems to save in bitmap.
Has anyone else seen this problem, and is there a workround? (Apart from saving to disc as a big bmp file, and re-loading into a TJpegImage/TPngImage object, that is).
Thanks for any advice
PhilW.
This the code I am currently using:
//...
uses ComObj, WIA_TLB,
//...
procedure TMainForm.ScanWiaDocument(DocumentRef: String);
const
wiaFormatJPEG = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}';
wiaFormatPNG = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}';
var
CommonDlg: ICommonDialog;
AImage: IImageFile;
ImagePath: String;
begin
CommonDlg := CreateOleObject('WIA.CommonDialog') as ICommonDialog;
//Transfer as JPG
try try
AImage := CommonDlg.ShowAcquireImage(ScannerDeviceType,
ColorIntent, //or UnspecifiedIntent, GrayscaleIntent, TextIntent
MinimizeSize, //or MaximizeQuality
wiaFormatJPEG, //image format **<----Only saves in BMP format!**!
False, //AlwaysSelectDevice
False, //UseCommonUI
True); //CancelError
//Save the image
ImagePath := 'C:\temp\scanimage\'+DocumentRef+'.'+ AImage.FileExtension;
AImage.SaveFile(ImagePath);
except
on E:Exception do LogException(E, 'ScanWiaDocument', True);
end;
finally //release interface
CommonDlg := nil;
AImage := nil;
end;
end;
A: You are asking ShowAcquireImage() to capture in JPG if possible, but it does not have to honor that. When ShowAcquireImage() exits, the returned ImageFile object has a FormatID property that specifies the format that was actually used, for instance if the scanner does not support JPG. If the file is not already in JPG, you will have to convert it afterwards, such as by using the Wia.ImageProcess object. MSDN shows an example of doing that.
A: I noticed that the constants you used for JPG and PNG are both the one I use for BMP. Could this be your problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: xml xslt transform I’ve been trying to transform some simple XML into another simple XML using XSLT. I am new to XSLT, so if someone could give me an example I will expand on it.
I have arbitrary XML files: e.g
<element>
<child_element>
<grandchild_element>
only one
</grandchild_element>
</child_element>
<child_element>
<grandchild_element>
one
</grandchild_element>
<grandchild_element>
two
</grandchild_element>
</child_element>
</element>
From which I want to produce:
<tree>
<item class="element" id="1">
<item class="child_element" id="11">
<item class="grandchild_element" id="111" value="only one"/>
</item>
<item class="child_element" id="12">
<item class="grandchild_element" id="121" value="only one"/>
<item class="grandchild_element" id="122" value="only one"/>
</item>
</item>
</tree>
Thanks!
A: You'd write up a template for each element, like:
<xsl:template match="child_element">
and use the count of the preceding or preceding-sibling elements to get the "id" field:
<xsl:template match="child_element">
<item>
<xsl:attribute name="id">
<xsl:value-of select="concat(count(preceding-sibling::element),count(preceding::child_element)+1)"/>
</xsl:attribute>
</item>
</xsl:template>
For the grandchild-id, you'll have to play around with .. and preceding-sibling.
I'd however strongly advise you not to use your current counting scheme for id's anyway: Once you have more than 10 nodes at any level, collisions occur.
A: To get the id for each element, you will need look back at each of the ancestors, and for each level, count the number of preceding-siblings.
<xsl:attribute name="id">
<xsl:apply-templates select="ancestor-or-self::*" mode="id"/>
</xsl:attribute>
<xsl:template match="*" mode="id">
<xsl:value-of select="count(preceding-sibling::*) + 1"/>
</xsl:template>
To convert the element name into the class attribute is straight-forward, and done like so:
<xsl:attribute name="class">
<xsl:value-of select="local-name()"/>
</xsl:attribute>
And to convert text into the value attribute is also fairly simple.
<xsl:template match="text()">
<xsl:attribute name="value">
<xsl:value-of select="normalize-space(.)"/>
</xsl:attribute>
</xsl:template>
The normalize-space here is to remove the line-breaks shown in your sample XML.
Here is the full XSLT
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Match root element -->
<xsl:template match="/">
<tree>
<xsl:apply-templates select="node()"/>
</tree>
</xsl:template>
<!-- Match any element in the XML -->
<xsl:template match="*">
<item>
<xsl:attribute name="id">
<xsl:apply-templates select="ancestor-or-self::*" mode="id"/>
</xsl:attribute>
<xsl:attribute name="class">
<xsl:value-of select="local-name()"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</item>
</xsl:template>
<!-- Used to match ancestors to work out the id -->
<xsl:template match="*" mode="id">
<xsl:value-of select="count(preceding-sibling::*) + 1"/>
</xsl:template>
<!-- Convert text into the value attribute -->
<xsl:template match="text()">
<xsl:attribute name="value">
<xsl:value-of select="normalize-space(.)"/>
</xsl:attribute>
</xsl:template>
<!-- Copy any existing attributes in the XML -->
<xsl:template match="@*">
<xsl:copy/>
</xsl:template>
</xsl:stylesheet>
When applied on your sample XML, the following is output:
<tree>
<item id="1" class="element">
<item id="11" class="child_element">
<item id="111" class="grandchild_element" value="only one"/>
</item>
<item id="12" class="child_element">
<item id="121" class="grandchild_element" value="one"/>
<item id="122" class="grandchild_element" value="two"/>
</item>
</item>
</tree>
A: One of the simplest/shortest solutions (only 3 templates no modes, no axes, no count(), only a single xsl:attribute) that is at the same time most generic (works with any element names):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<tree>
<xsl:apply-templates/>
</tree>
</xsl:template>
<xsl:template match="*">
<xsl:variable name="vNumber">
<xsl:number count="*" level="multiple"/>
</xsl:variable>
<item class="{name()}"
id="{translate($vNumber, '.', '')}">
<xsl:apply-templates/>
</item>
</xsl:template>
<xsl:template match="text()">
<xsl:attribute name="value">
<xsl:value-of select="normalize-space()"/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on the provided XML document:
<element>
<child_element>
<grandchild_element>
only one
</grandchild_element>
</child_element>
<child_element>
<grandchild_element>
one
</grandchild_element>
<grandchild_element>
two
</grandchild_element>
</child_element>
</element>
the wanted, correct result is produced:
<tree>
<item class="element" id="1">
<item class="child_element" id="11">
<item class="grandchild_element" id="111" value="only one"/>
</item>
<item class="child_element" id="12">
<item class="grandchild_element" id="121" value="one"/>
<item class="grandchild_element" id="122" value="two"/>
</item>
</item>
</tree>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: KeyEventArgs.Handled vs KeyEventArgs.SupressKeyPress What's the difference between using
e.Handled = true
and
e.SuppressKeyPress = true
I've read that SuppressKeyPress calls e.Handled but else does it do?
A: It simply prevents user input for all pending button hits. i.e. in a TextBox, not only event Handled is set to true, user input is suppressed and not reflected on the text box in case you're typing very fast and hit many buttons at once.
A: According to this blog: New keyboard APIs: KeyEventArgs.SuppressKeyPress:
The problem is that "Handled" doesn't take care of pending WM_CHAR
messages already built up in the message queue - so setting Handled =
true does not prevent a KeyPress from occurring.
In order not to break anyone who has currently got e.Handled =
true, we needed to add a new property called SuppressKeyChar. If we
went the other way, if "handling" a keydown suddenly started to
actually work, we might break folks who accidentally had this set to
true.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Java: Call a method from a "contained" class
I have a class hierarchy like this:
public class A {
private B obj = new B(); // Inside this object
// do I need a reference to here?
// (In order to call method1())
public A(){ ... }
private void method1(){ ... }
private void method2(){ ... }
}
// Other package
public class B {
private JButton bt1 = new JButton("Button");
public B(){
...
bt1.addMouseListener(new MouseActionsListener(this));
}
public class MouseActionsListener implements MouseListener
{
@Override
public void mouseClicked(MouseEvent event)
{
/*
* I need to call method1() HERE!!!
*/
}
}
}
Is it possible to call a method of the class A from the class B in that position?
The problem is that I have a list of B objects in A, and whenever a button is clicked in one of the B objects a change has to be made in A.
Thank you!
A: There is no implicit association that would allow you to go from B to A.
You will need to:
*
*change B to keep a reference to the corresponding instance of A;
*initialize that reference in B's constructor;
*use it call A's methods.
In code:
public class A {
private B obj;
public A() {
obj = new B(this);
...
}
public void method1(){ ... }
public void method2(){ ... }
}
public class B {
private final A _a;
public B(A a) {
_a = a;
}
public class MouseActionsListener implements MouseListener
{
@Override
public void mouseClicked(MouseEvent event) {
_a.method1();
}
}
A: No. You would need to have a reference back to an instance of A from your B class.
A: Yes, you have to have a reference back (As has already been said).
I'm only adding in here to mention that this can get a little sticky. If you can, I suggest redesigning your structure so that you don't need the double-reference, if not I highly recommend that you don't try to do the setting in constructors--instead call a.init(b) and/or b.init(a) to set the values.
It may work as written for now but as time goes on initializing in constructors will cause increasing limitations and frustrations. Not that you can't refactor later, but I guess I'm just suggesting this so you don't waste too much time banging your head before you decide to refactor.
If you think about it, doing it that way makes it so that you can't instantiate just one of them, making testing more difficult, and if you add any further dependencies to the construction of the class it can become impossible (this starts to reach the same kind of complexity as multiple inheritance).
You may also want to consider either having both add themselves to a common source as listeners or using an event bus (Probably the cleanest and simplest solution).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MS Access SQL Syntax Error I'm trying to update a microsoft access database table field from a similar field in a linked table.
Here are my table names:
Raw data
sectionroster
And here's my query so far:
UPDATE [raw data].[current supervisor]
FROM [raw data]
INNER JOIN [sectionroster] ON [raw data].[associate id]=[sectionroster].[employee number]
SET [raw data].[Current Supervisor] = [sectionroster].[supervisor];
It's giving me a syntax error referencing the from clause, and I can't figure out why. Any help would be appreciated!
A: Try this
UPDATE [raw data].[current supervisor]
SET [raw data].[Current Supervisor] = [sectionroster].[supervisor]
FROM [raw data]
INNER JOIN [sectionroster] ON [raw data].[associate id]=[sectionroster].[employee number]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Workaround for "undeclared prefix" error on XElement.Load() I'm pulling the source of a website. I then want to extract a specific part of it. My intention is to do this with LINQ-to-XML.
However, I get errors when I parse the source:
XElement source = XElement.Load(reader);
The problem seems to be references to namespaces I don't have. I get the error: 'addthis' is an undeclared prefix. Line 130, position 51. due to this line:
<div class="addthis_toolbox addthis_pill_combo" addthis:url="http://www.foo.com/foo">
And if I delete that one, other occur.
Thing is, I only care about one piece of this XML file - I don't need to be able to parse the whole file. I just want it in an XElement so I can find that one piece of it. Is there a way for me to hack around the parsing error? And I need a generic solution - I want to parse the file regardless of ANY undeclared prefix errors.
Thanks
A: If you need to do it all in code what you want is something like this:
XmlReaderSettings settings = new XmlReaderSettings { NameTable = new NameTable() };
XmlNamespaceManager xmlns = new XmlNamespaceManager(settings.NameTable);
xmlns.AddNamespace("addthis", "");
XmlParserContext context = new XmlParserContext(null, xmlns, "", XmlSpace.Default);
XmlReader reader = XmlReader.Create(new StringReader(text), settings, context);
xmlDoc.Load(reader);
And for any additional prefixes add more of these:
xmlns.AddNamespace("prefix", "");
A: This XML is not valid.
In order to use a namespace prefix (such as addthis:), the namespace must be declared, by writing xmlns:addthis="some URI".
In general, you shouldn't parse HTML using an XML parser, since HTML is likely to be invalid XML, for this reason and a number of other reasons (undeclared entities, unescaped JS, unclosed tags).
Instead, use HTML Agility Pack.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Improving algorithm and syntax for c# linq expression I've been doing a bit of linq in c# .net 3.5 and feel like I should be able to do the following a little neater.
Is there a way to combine this into a single linq statement.
The conditions are as follows
*
*If the list contains an element where count is greater or equal to
the threshold then we can use the list
*Order the list by count
*Order the list by date
I'd also like to add another condition on the count where I could treat all items with a count greater or equal than the threshold the same. I could do this by limiting the count to the threshold but i'd prefer not to in case the threshold were to be changed. I'm a bit stumped on how to do this other than temporarily editing the records when I get them from the database and not saving them. i.e with a threshold of 3 the list (1,2,3,4,5) becomes (3,3(4),3(5),2,1) before being sorted by date.
var allFaves = m_favouriteRepo.Get(user);
if(allFaves.Any(t => t.Count >= threshold))
{
var ordered = allFaves
.OrderByDescending(x => x.Count)
.ThenByDescending(x => x.SortDate)
.ToList();
}
Thanks
Neil
A: if(allFaves.Any(t => t.Count >= threshold))
{
var ordered = allFaves
.OrderByDescending(x => x.Count>=threshold?threshold:x.Count)
.ThenByDescending(x => x.DatesHistory)
.ToList();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Removing after appending isn't removing I've got a funny bit of code which doesn't seem to want to listen to me. Essentially, I'm trying to affect when some zoom buttons appear on a map depending on which map is going to be used.
While starting with the zoom buttons not being appended works as it should, and later adding the zoom buttons when changing to a map that uses them also happens without protest, I cannot for the life of me remove the buttons once they've been appended.
JS:
Map = function()
{
var $MapContainer;
this.initMap = function($container)
{
$MapContainer = $container;
}
this.setZoomButtons = function(mapImage)
{
if(mapImage != "map_noZoom.jpg")
{
$MapContainer.append("<div id='mapZoomIn' class='MapZoomInButton' OnClick='Star.Bus.fire(\"zoomIn\",1)'>+</div>");
$MapContainer.append("<div id='mapZoomOut' class='MapZoomOutButton' OnClick='Star.Bus.fire(\"zoomOut\",-1)'>-</div>");
}
else
{
// I've tried all 3 ways below to have the zoom buttons removed - none successful
// Only showing the zoom in button for the example
$MapContainer.remove("#mapZoomIn");
$MapContainer.remove(".MapZoomInButton");
$MapContainer.remove("<div id='mapZoomIn' class='MapZoomInButton' OnClick='Star.Bus.fire(\"zoomIn\",1)'>+</div>");
}
}
}
If the map I first enter is the one that does not have the zoom buttons (map_noZoom.jpg), then the zoom buttons are not present. I switch areas with a different map while in game, and the zoom buttons appear. If I go back to map_noZoom.jpg map's area, the buttons are not removed. I've tried the three different ways seen above to remove the buttons, but nothing is happening.
Is there another way to remove() (not looking for a cleaner solution here, just a way to have this work!) or am I doing something wrong?
A: You are confused about what the selector passed to .remove([selector]) does. It doesn't match to children of the element you call it on, but instead acts as a filter on those selected elements you call it on, so $MapContainer.remove("#mapZoomIn"); removes all $MapContainer elements with an id of mapZoomIn;
What you would need to do is find the element first, then remove it:
$MapContainer.find('#mapZoomIn').remove();
A: You have to find certain elements and remove them like this:
// find .mapZoomInButton inside $MapContainer and remove those elements
$MapContainer.find(".mapZoomInButton").remove();
.remove with a selector filters the current set (i.e. $MapContainer), which is not what you want.
A: $MapContainer.find(".MapZoomInButton").remove();
or, more simply:
$(".MapZoomInButton").remove();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Writing a program that can handle a Heap that has K amount of children I have researched binary Heaps and I am still very confused about what to do for this program If I could get some guidance I would really appreciate it I'm still learning java and having a lot of trouble doing so.
A k-ary heap is like a binary heap (where k = 2), but (with one possible
exception) non-leaf nodes have k children instead of 2 children. Implement k-ary heap
as a min-priority queue for an arbitrary k ≥ 2 to support following operations:
• insert (x): inserts the element x to the heap.
• extract-min(): removes and returns the element of heap with the smallest key.
k-ary heap is to be implemented using an array of predefined size. Also study the
relative efficiencies of the data structure for varying values of k, by measuring the time
required for performing sequence of operations given the input file for k = 2, 4, 6, 8,
10. In the input file “IN” stands for insert and “EX” stand for extract-min operation.
A: A binary heap is implemented as an almost full (=complete) binary tree. For your k-ary heap, you will probably need to generate almost full k-ary tree [all levels in the tree are full, except the last one, inwhich you fill the tree from left to right] , and repeat the same ops the original heap do, but with more then 2 children per node.
With some knowledge on heap ops, especially the heapify, and the tip above, it shouldn't be too hard to implement your k-ary heap.
To implement it as an array, simply follow how a binary tree is implemented as an array, and follow these ideas when you implement your complete k-ary tree as an array.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Set images in ListView I have a listActivity. In each row of the list a name of a category is placed.
I download the activities from the web, so they may change occasionally. But I would like to set a image to each category.
I have a list of categories that may occur. And I have graphics for all categories. How can I match the correct image with corresponding category in a smooth way?
EDIT:
I have the pictures. And now how to add them to a listView. But Im looking for advice how to map a correct category to a correct picture. Could a bitmap factory do the trick, if I name the pictures to the same as the categories.
Bitmap bMap = BitmapFactory.decodeFile("/categoryicon_"+c.getId() + ".png");
imageView.setImageBitmap(bMap);
A: I would try a map with the category names as key and the resource id of the image as value. Then you can load a drawable from the resources using the right id.
A: For displaying the activities, I would use a custom array adapter, there are so many different examples out there so you will find loads if you just google. List14 is a really good example to start with.
Then you have an array of activities, each activity has an id which decides what kind of image that will be shown, and of course the name of the activity. Then just depending on which id the activity has display the correct image.
If you would like to change it occasionally with refresh from a homepage you should probably download the images and store them in a good manner, if the image changes with the activities of course.
A: I would try and a map with the category names. Then i would use the resource id of the image as the value. Then you could load the images using the right ID.
If you want to add a imageview to a ListView you will also need to use a custom array adapter
This is an example of how you would do it.
This is a good one to get you started
http://sudarmuthu.com/blog/using-arrayadapter-and-listview-in-android-applications
A: Solved it like this:
String icon = "category_"+c.getId();
int resId = getResources().getIdentifier(icon, "drawable", getPackageName());
Bitmap bMap = BitmapFactory.decodeResource(getResources(), resId);
imageView.setImageBitmap(bMap)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to update two different tables with DetailsView Update Command I am developing an ASP.NET application in C#.
I have two Database tables Food(Id, Name, Description) and FoodLog(Id, FoodId, FoodName, FoodDescription, ChangedFields, Date). As the name indicates, FoodLog stores the modification history made by the users to Food records and specifies in the ChangedFields field which fields have been modified compared with the previous "version" of the record.
To display to the user a specific Food record I use the DetailsView control. When the user presses the Update button an UpdateCommand linked to the SQLDataSource is executed. This UpdateCommand just modifies the corresponing Food record.
In order to add a new record to the FoodLog table I need to catch an event fired by the DetailsView upon update. When I catch this event I manually compare the record inserted by the user (not yet committed to the DB) with the one in the Food table matching its Id in order to keep track of the modified fields and store them in the ChangeFields field in the FoodLog table. Now in order to perform this task I can use two events fired by DetailsView
*
*ItemUpdated: It is launched after the UpdateCommand is executed. This
way I lose track of the modified fields because the previous
"version" of the record has been already overwritten.
*ItemUpdating: It is launched before the UpdateCommand is executed.
This way I have still the old "version" of the record in the DB and I
can make the comparison and then dtore in the FoodLog table. However
if then the UpdateCommand fails for some reason I have a record in
the log that do not correspond to a change on the Food table.
Anybody might help with this problem? Is it possible to write two different SQL expressions in the UpdateCommand?
Thanks
A: You could use a stored procedure for your updates.
Call the stored procedure first when you store the old values in log table and then update the main table. Use transaction to avoid partial update in case an error.
A: If you could just strong text use the sp to generate updating and merging and only use an event .NET. If you could just use the sp to generate updating and merging and only use an event .NET invoking the sp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Check a checkbox inside Gridview I want to check a check-box which is inside Gridview programmatic on click of a button
A: If you know the location of the cell then you can set it as
datagridview1[0,2].Value = true;// this should be a checkboxcolumn
OR
datagridview1["chkboxcolumnName",2].Value = true;
This will cause the checkbox to be checked for that particular cell.
Hope this is what you meant else please edit the question for more details.
A: Try it this way (by subscribing to two events):
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dataGridView1_CellValueChanged(object obj, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1) //compare to checkBox column index
{
DataGridViewCheckBoxCell cbx = (DataGridViewCheckBoxCell)dataGridView1[e.ColumnIndex, e.RowIndex];
if (!DBNull.Value.Equals(cbx.Value) && (bool)cbx.Value == true)
{
//checkBox is checked - do the code in here!
}
else
{
//if checkBox is NOT checked (unchecked)
}
}
}
A: This worked for me:
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
dataGridView1.Rows[i].DataGridView[0, i].Value = false;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 8bit YUV, 10bit YUV, 10bit RGB all ends up in color space such as RGB. Why YUV exist? Why should i use it? I am writing a medical application, where i have packets coming in IP interface. Which has following definition for pixel skeleton decoding. I can decide what i pick in the main frame to have different pixel algorithm. But i do not understand the logic properly.
What does this 3 formats mean? Which one would you use?
8 bit YUV (4:2:2)
10 bit YUV (4:2:2)
10 bit RGB (4:4:4)
A: It exists to manage the bandwidth used by color images. Since the typical human eye is more sensitive to luminosity than color, the two color channels (U and V) can be given reduced bandwidth compared to the luminosity channel (Y) while maintaining a certain level of overall quality.
I cannot answer which format is best for your application unless I know more about your application.
*
*8 bit YUV 422 is the most compatible format.
*10 bit YUV 422 achieves a slightly higher quality (especially w.r.t. banding) for a given bandwidth, but support is limited and processing is more difficult. (This assumes some form of lossy compression -- it of course uses more bandwidth if uncompressed.)
*10 bit RGB 444 is often preferable for writing video effects, but undesirable for distributing finished video.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Hosting Serving Web Pages on Windows In Process I am currently writing a web based front end for some proprietary server software. The server is based loosely around MEF components written as seaparate assemblies which serve as modules. The web based front end will have its pages served up as a part of one of the modules and it is desirable that it run "in process" so that failure of the module does not jeopardize the entire server.
I am working through the pros and cons of different approaches for architecting the front end. I have the following as options:
*
*Serve up HTML pages and process commands from a WCF Restful service. Use a WebServiceHost that starts up when a module is initialized.
*Use IIS 7.5 Express to set up a web server for a specific directory.
I have #1 prototyped but the downside is that I would have to do a lot of infrastructure code for processing URLs, generating templates and so on. Right now I'm serving up the pages as embedded resources. I don't have the ability to leverage things like ASP.NET MVC.
I am curious about #2 because although IIS represents a big dependency, all the goodness of ASP.NET MVC and other Microsoft infrastructure (e.g. Razor) is readily available.
My questions:
*
*Are there any drawbacks to running IIS Express in process?
*What are the pitfalls of my initial approach, running a WCF RESTful web service.
*Are there any other lightweight webserver containers I can take advantage of that have the flexibility of ASP.NET for template driven pages and database interaction?
*Any additional insight/experiences if you've tried something similar.
A: If each module will have its own "web server" you could use an OpenRasta Server within each module to create the restful endpoints.
With multiple endpoints though, I suppose you will have to configure multiple port numbers which may have implications with firewall if this is an internet facing application.
Brian
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why I get Access Denied Error using WMI Connection? this is a similar error all around the internet but I am not able to reason out why this can happen in my case. I am trying to use WMI for remotely installing windwos services from my XP client machine. I use,
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
options.Username = "domainName\userName";
options.Password = "pwd";
string path = string.Format("\\\\{0}\\root\\cimv2", machineName);
ManagementScope scope = new ManagementScope(path, options);
scope.Connect();
I get 'Access is denied. (Exception from HRESULT: 0x80070005)' error. I use a windows XP SP3 and trying to connect to windows server 2003.
I found out these but I did check all of these:
*
*User account not admin - The user account is a local admin. I can use the same account, to do a instalutil and create services in that machine. This is the account underwhich my application services run.
*dcomcnfg and check Enable DCOM - This is already enabled.
*Changed Enabled Previliges and Impersonation properties in ConnectionOptions. But this doesnt help.
*Firewall settings - The error message number doesnt say this. But, the machine is withing the same domain as the XP client.
A: I figured this out. The account that I used to login remotely (via mstsc) and install/uninstall services was NOT a local admin account. It was surprising because, I used the same account to install services in that machines, so assumed it would be a local admin. When I added the account to local admin, the WMI connectivity also worked. Hence, for remotely connecting to the machine, u need to use a local admin account.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement such style UI? I want to write some shareware and I love the GUI style in the following image:
(source: batchimageconverter.com)
Who knows how to imp such style? I think maybe it uses some UI library, who knows whas is the UI library? I want to use C++ to write the program.
A: It's almdev's BusinessSkinForm/DynamicSkinForm with the Laconic skin.
I wouldn't recommend using it, but you decide.
A: I know you've tagged this as mfc, however if you wanted to be portable - you could look at Qt. It's not a specific theme - if that's what you are after, but I should imagine it's fairly straight foward to style..
A: If you want to use a nice, portable and powerful GUI for C++, I'd recommend using Qt
A: If you are using C++ Builder (fully compatible C++ compiler), there are quite a few VCL skin libraries that you can use to change the look and feel easily. Or you can do your own by handling the paint events for the components in low level.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Authentication for a Vaadin app using OpenID - difficulty handling redirects I'm trying to authenticate my Vaadin app with OpenID and I'm having difficulties with handling redirects in the app.
*
*On loading the app, users are presented with an OpenID login utility which is a simple Vaadin window with some buttons that trigger redirects to a separate authentication servlet (LoginServlet)
*LoginServlet then handles the redirection to the OpenID Provider and the subsequent redirection back to the servlet, which handles the authentication response. Security status is updated here (using Apache Shiro) which can be checked by the Vaadin app later.
*LoginServlet then redirects to the application, however this is where the issue lies - how to handle this redirect? The Vaadin Window appears to have no method of handling redirects.
Currently the only option seems to be utilizing UriFragmentUtility.FragmentChangedListener and ensuring the redirect from LoginServlet is unique using a UUID ensuring the fragment changed event is fired, allowing the user's authentication status to be checked and allowing access to the app. This however is something of a hack and leads to a messy URIFragment.
If anyone has any better ideas on integrating OpenID and Vaadin or just handling redirects in Vaadin, I'd be very grateful.
A: Have you noticed Leif Åstrand has made an Vaadin OpenId Integration add-on in the directory? Might this do the work for you?
A: The proffered answer links to a very immature project which wasn't suitable. I've chosen a different approach, which is handling all authentication at the servlet level. See my accepted answer on programmers which was based on the recommendations in the article Creating Secure Vaadin Applications using JEE6
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wildcard in Generics doesn't work Looking at the following code, why doesn't the second invocation of dump get compiled? And how can I fix it without removing the wildcard?
import java.util.ArrayList;
import java.util.List;
class Column<A, T extends Object> {
}
public class Generics {
static void main(String[] args) {
Integer i = 5;
// this works
List<Column<Integer, ?>> columns1 = new ArrayList<Column<Integer, ?>>();
dump(columns1, i);
// this doesn't
List<Column<Integer, String>> columns2 = new ArrayList<Column<Integer, String>>();
dump(columns2, i);
}
static <A, T> void dump(Iterable<Column<A, ?>> columns, A value) {
for (Column<A,?> col: columns) {
System.out.println(col);
}
}
}
The JDK's compiler gives
Generics.java:18: <A,T>dump(java.lang.Iterable<Column<A,?>>,A) in Generics cannot be applied to (java.util.List<Column<java.lang.Integer,java.lang.String>>,java.lang.Integer)
dump(columns2, i);
^
1 error
A: Since columns in dump() acts as a producer of objects, you need to declare it with extends (the general rule is "producer - extends, consumer - super"):
static <A, T> void dump(Iterable<? extends Column<A, ?>> columns, A value) {
for (Column<A,?> col: columns) {
System.out.println(col);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Decimal precision - C# All,
For a decimal value of 1 billion being retrieved from SQL Server where the associated datatype is Numeric (28,10), I am running into Conversion overflow exception. From MSDN:
The .NET Framework decimal data type allows a maximum of 28 significant digits
I need to clarify if the digits here refer to the binary form or decimal form itself?
A: In SQL Server for Numeric and Decimal datatypes this defines a maximum of 28 decimal digits (the precision) with a maximum of 10 decimal places to the right of the decimal point (the scale).
A: The limitation is imposed by the decimal representation and the 28 significant digits refer to 28 decimal digits.
A: Its Decimal digits that it will accept max of 28 digits.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to call a pig script within another pig script I have a file in hdfs with 100 columns, which i want to proces using pig. I want to load this file into a tuple with columns names in a separate pig script, and reuse this script from other pig scripts. How do I do this?
Say this 100 column pig script is - 100col.pig. How do i call it from anotherone.pig?
A: Check into the exec command (for batch processing) or the run command (for interactive scripts). Also, if you need to use (non-grunt) shell commands, check the fs command. Here's a good reference:
http://pig.apache.org/docs/r0.7.0/piglatin_ref2.html
A: You should try using macros that is present in pig version 0.9.
http://pig.apache.org/docs/r0.9.1/cont.html#macros
A: Its a little late for this answer, but I was recently working on this requirement and found almost nothing helpful, until I found this, hope this will help someone in need:
** This excerpt is taken from Programming Pig book.
For a long time in Pig Latin, the entire script needed to be in one file. This produced
some rather unpleasant multithousand-line Pig Latin scripts. Starting in 0.9, the preprocessor
can be used to include one Pig Latin script in another. Taken together with
the macros, it is now possible to write
modular Pig Latin that is easier to debug and reuse:
import is used to include one Pig Latin script in another:
--main.pig
import '../examples/ch6/dividend_analysis.pig';
daily = load 'NYSE_daily' as (exchange:chararray, symbol:chararray,
date:chararray, open:float, high:float, low:float, close:float,
volume:int, adj_close:float);
results = dividend_analysis(daily, '2009', 'symbol', 'open', 'close');
import writes the imported file directly into your Pig Latin script in place of the
import statement. In the preceding example, the contents of dividend_analysis.pig will
be placed immediately before the load statement. Note that a file cannot be imported
twice. If you wish to use the same functionality multiple times, you should write it as
a macro and import the file with that macro.
A: Here there are 2 options as mentioned above.
Pig gives run and exec commands to tackle your requirement.
exec command is there for calling a pig script that is inependent and a standalone run.
run command is there for running a pigscipt and preserve its variables and aliases.
I suppose you need to check out the run command to achieve your requirements.
http://pig.apache.org/docs/r0.9.1/cmds.html#run
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Password encryption methods in classic ASP I am looking for a method to encrypt/decrypt password in classic ASP. Can someone please suggest to me which method is good to go and what are the possible ways to do this in classic ASP.
A: I've created a class of functions for hashing passwords in Classic ASP. As well as a standard hashing function that uses MD5, SHA1, SHA256, SHA384 or SHA512 and an auto-generated salt and optional pepper, there's also support for Argon2, Bcrypt and PBKDF2
The standard hashing function should work on most shared hosting servers, the rest require the installation of COM DLL's which I have created and uploaded to GitHub. Everything is outlined and demonstrated in this repository:
https://github.com/as08/ClassicASP.PasswordHashing
A: You can download this free Classic ASP/VBScript script here which encrypts a string to SHA-256, an industry standard one-way hash function:
http://www.freevbcode.com/ShowCode.asp?ID=2565
Most people don't decrypt a password once it has been encrypted. The idea is to store a non reversible, encrypted password in your DB, which in turn stops an attacker reading passwords if the manage to get to your DB. When somebody enters a password, you encrypt the users input and match it against the encrypted password in the DB.
But hashing alone is not secure enough. You have to add a SALT value to the password you want to hash, to make it unbreakable. Salt should be a random but unique password that gets added to the password before hashing, for example:
password = Request("password")
salt = "2435uhu34hi34"
myHashedPassword = SHA256_function(password&salt)
A: I created a COM-interop DLL for this exact task--Classic ASP Password Hashing. Simply build, register the DLL and call it from ASP. This is an early working version using AES256, I plan to add additional algorithm support in the future.
https://github.com/kingdango/SaltedHashPassword
Suggestions welcome!
Classic ASP Code Example
newPassword = "whatever-the-user-typed"
set passwordGenerator = Server.createObject("Kingdango.SaltedHashPassword.PasswordHash")
passwordGenerator.Password = newPassword
newPasswordSaltedHash = passwordGenerator.GetHashedPassword()
newPasswordSalt = passwordGenerator.Salt
A: Looking for the same thing. This whole concept of hashing passwords made me realize that some major websites out there must be using a decrypt method as well. How else can they email a lost password if they do not keep it in either clear text or have a method of decrypting it.
Edit: I think I found an answer here—database column-level encryption.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Display tooltip for invisible series in Highcharts I am trying to display a custom tooltip using Highcharts. You can find an example of the code here:
http://jsfiddle.net/jalbertbowdenii/fDNh9/188/
When you hover over the chart, you can see that the tooltip only contains values from Series 2, but not from Series 1 (which is invisible). When you click on "Series 1" in the legend, you can see the values from Series 1 in the tooltip.
EDIT: no code to commit, just fixing linkrot/adhering to editing rules...
Is there any way to display the values from an invisible series in a tooltip?
A: The tooltip formatter is a function like any other function so if you just make the data available it can return a string with values for all series. In this example I moved the series arrays and categories to separate variables and the tooltip formatter uses an index into these arrays to find the values.
formatter: function() {
var index = $.inArray(this.x, categories);
var s = '<b>'+ this.x +'</b>';
s += '<br/>'+ chart.series[0].name + ': ' + data1[index];
s += '<br/>'+ chart.series[1].name + ': ' + data2[index];
return s;
}
A: Another way to go about this is to make certain attributes of the series invisible, rather than the entire series itself. This will allow you to see it in the tooltip and legend.
Here's what I did:
*
*First, I set the line color of the invisible series to "transparent."
*Next, I set the fill color for the invisible series markers to "transparent."
*Finally, I disabled the hover state for the markers. This prevents the shadowy highlight circles from appearing as you move your mouse cursor over each point in the visible series.
Here's a modified version of your original fiddle with these changes: http://jsfiddle.net/brightmatrix/fDNh9/184/
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
lineColor: 'transparent', // make the line invisible
marker: {
fillColor: 'transparent', // make the line markers invisible
states: {
hover: {
enabled: false // prevent the highlight circle on hover
}
}
}
}, {
data: [216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5]
}]
Two items to note:
*
*I've used the attribute enableMouseTracking: false with other invisible series to prevent users from interacting with them (to achieve visual effects). If you set this for your invisible series, it will prevent the series data from appearing in your tooltip.
*If you wanted to keep your invisbile series from appearing in the legend, you can add the attribute showInLegend: false. Its data will still show in the tooltip.
I hope this helps others who come across this question.
A: tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
var chart = this.points[0].series.chart; //get the chart object
var categories = chart.xAxis[0].categories; //get the categories array
var index = 0;
while(this.x !== categories[index]){index++;} //compute the index of corr y value in each data arrays
$.each(chart.series, function(i, series) { //loop through series array
s += '<br/>'+ series.name +': ' +
series.data[index].y +'m'; //use index to get the y value
});
return s;
},
shared: true
}
A: Too late for the answer but this is what I did. Plot the chart and make the color transparent. Plotted it on the opposite y axis and set max to zero. Set alignTicks to false. Something like this.
chart: {
alignTicks: false,
type: 'line'
},
Then the only thing needed is to change the color value in tooltip formatter since the label will be transparent.
Hope this helps someone.
Happy Learning :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Oracle: using impdp from a full DB expdp I’ve got a full Dump of an Database (all schema, system etc...)
Now I want to import just one schema of this file, is this even possible?
As far I got this command:
impdp sysadm/sysadm@sysadm schemas=sysadm directory=dp_dir dumpfile=export.dmp logfile=export.log
Would this work?
The problem is, in this dump file there are schemas that are already used and I can't overwrite them (I can but it would be pain for me to recover them)
thanks for help
A: It should work as you have shown. You might also want to take a look at the TABLE_EXISTS_ACTION parameter to provide additional warm-fuzziness. With that you can skip tables that exist already.
That said, of course you will have a backup of your database before you start? Or if it's a real pain to recover, perhaps you could create another test database to try this out on?
A: "impdp system/*****@nsd1 directory=DATA_PUMP_DIR parfile=exclude_schemas_parfile.par REMAP_SCHEMA=old_schema:new_schema remap_tablespace=Schema1_TS_TABLES:Schema2_TS_TABLES dumpfile=schema1.dmp LOGFILE=schema1_import.log"
.par file enteries look like this:
exclude=SCHEMA:"='CTXSYS'"
exclude=SCHEMA:"='ORDDATA'"
exclude=SCHEMA:"='OWBSYS_AUDIT'"
.
.
get list of all schemas from schema1 (using system user).
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: erlang, what's difference between 'catch 1=0' and '(catch 1=0)'? What's differenct between 'catch 1=0' and '(catch 1=0)'?
Erlang R14B03 (erts-5.8.4) [source] [64-bit] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.8.4 (abort with ^G)
1> 1=0.
** exception error: no match of right hand side value 0
2> catch 1=0.
{'EXIT',{{badmatch,0},[{erl_eval,expr,3}]}}
3> (catch 1=0).
{'EXIT',{{badmatch,0},[{erl_eval,expr,3}]}}
A: There is no difference. The only thing that changes is when you try to bind the result of the operation to a variable:
1> X = catch 1/0.
* 1: syntax error before: 'catch'
1> X = (catch 1/0).
{'EXIT',{badarith,[{erlang,'/',[1,0]},
{erl_eval,do_apply,5},
{erl_eval,expr,5},
{erl_eval,expr,5},
{shell,exprs,7},
{shell,eval_exprs,7},
{shell,eval_loop,3}]}}
That's simply a question of precedence between catch as a prefix operator, and = as an infix operator. The parentheses help make the use case unambiguous in priority.
Otherwise, they're exactly the same.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: android phone number is null for sim contacts The following code returns Phone number as null for the contacts in SIM. Whereas for the contacts in Phone, it returns the correct value. Please let me know, whether the URI should be different to read the phone number from SIM. Below is my code, almost a copy from Android Contact tutorial.
long contactId = -1;
// Load the display name for the specified person
Cursor cursor = contentResolver.query(contactUri,new String[]{Contacts._ID, Contacts.DISPLAY_NAME}, null, null, null);
try
{
if (cursor.moveToFirst())
{
contactId = cursor.getLong(0);
}
}
finally
{
cursor.close();
}
// Load the phone number (if any).
String phoneNumber=null;
cursor = contentResolver.query(Phone.CONTENT_URI,new String[]{Phone.NUMBER},Phone.CONTACT_ID + "=" + contactId, null, Phone.IS_SUPER_PRIMARY + " DESC");
try
{
if (cursor.moveToFirst())
{
phoneNumber=cursor.getString(0);
}
}
finally
{
cursor.close();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL REGEXP repeating characters How can I find strings with individual repeating characters (for example 3 times)?
This works but I don't want rewrite every alpha characters (a,b,c,d,e...):
... REGEXP '(a){3}|(b){3}|(c){3}|(d){3}|(e){3}|(f){3}...' ...
Thank you very much
A: r = '(\w)\1{2}`
finds any alphanumeric character that is repeated (at least) three times, matching the first three.
A: How about repeating a capture group?
r = '([abc])\1\1'
A: '(abc){3}'
Example:
> echo 'bbbabcabcabcaaabbbccc' | egrep -o '(abc){3}'
abcabcabc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: custom vim syntax highlighting scripts-- why do they work in Windows but not Linux? I have written a vim script for highlighting the syntax of a proprietary query language. It works fine on my Windows 7 machine running gvim 7.3, but it refuses to work on Linux (my test box is CentOS 6). I have gotten the built-in language highlight scripts to work in CentOS, but for some reason any custom syntax scripts I add to the /usr/share/vim/vim72/syntax directory are not recognized even when I explicitly run
:set filetype=on
:set syntax=on
:set ft=cy
with cy.vim being the name of my syntax script. I checked out the ftplugin scripts to see if there was anything special pointing a filetype to a syntax script, but I couldn't see anything... I have another cy.vim file there anyway which reads
augroup cy,Q,q
au BufNewFile,BufRead *.cy,*.Q,*.q set filetype=cy
augroup end
normally I just keep the above in my _vimrc file, but as I can't even get the highlighting to work with explicit commands I doubt automatic filetype recognition on load would work.
Can anyone shed some light on why my syntax script works perfectly on Windows but not at all on Linux? I have tried all the usual avenues already, such as making sure I have vim-common/vim-full/vim-enhanced installed rather than vim-minimal/vim-tiny. Any help would be appreciated!
thanks,
CCJ
A: On Linux box vim will use ~/.vimrc and ~/.vim/.
Try the following command to see vim file type:
:echo &ft
Try the following to command see if your file is loaded:
:scriptnames
A: I believe the issue may have been with my xterm settings; on Solaris I ran into the same problem until I explicitly set the xterm window to support text colors and updated ncurses, per the wiki here: http://vim.wikia.com/wiki/Getting_colors_to_work_on_solaris
I haven't been able to revisit on CentOS Linux yet, but this solved the problem for Solaris
A: Can you load the syntax file via the full path?
:so /path/to/file.vim
What are the permissions on the syntax file?
ls -l /path/to/file.vim
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: XBee origin address in Arduino I am trying to find a way to get the origin address of an XBee radio in Arduino.
Basically, I want my XBee chip to send a string that also contains its origin address (or id) so that I can identify where the message is coming from without having to run different code on every different Arduino.
What should I do?
EDIT
I am using the xbee-arduino library (http://code.google.com/p/xbee-arduino/).
The xbee is connected directly to the Arduino through a Sparkfun Xbee Shield (http://www.sparkfun.com/products/9976)
It is communicating with a Connectport X2 running XIG (http://code.google.com/p/xig/) so I can't run any arduino code on there that would look at the sender's address - it has to be found locally on the board.
A: I believe that what you're looking for is the Serial Number of the XBee, which is a globally unique, 64-bit address that identifies that device.
There are two AT commands available, SH and SL, that give you the high and low 32 bits of the serial number. There's an example program in the xbee-arduino distribution that prints their values: AtCommand.pde
That program then executes the AI command, which returns a byte giving the status of the last network join request. That will return 0x00 on success.
A ZigBee device also has a 16-bit address (use the MY command), which is only guaranteed to be unique on its network. With XBee modems on a stable network, that won't change unless there's an address conflict, but you will probably be better off using the full 64-bit value as determined with SH and SL.
All of these commands assume that the XBee that interests you is connected directly to the Arduino. They can all be executed remotely using RemoteATCommand, but that requires you to pass the serial of the remote modem, so if you can successfully make the call then you already had the address.
If the XBee you're interested in is not connected to the Arduino, then you'll need to use the ND (Node Discover) command to perform a network scan. I'm not familar enough with the xbee-arduino API to know if they make that available, but getting the information about each node as it's discovered requires a little more work.
A: If you are using the API mode on these XBee chips (sure, if you use the XBee-api library), you do not need to include the address of the sender in the message. This information is automatically specified in the frame. Have a look at the getRemoteAddress16() and getRemoteAddress64() methods in class ZNetRxBaseResponse.
So what you have to do, is send a first message "hello" i.e. to the Coordinator (which you can address easily as 0x0000) from the Node you want to know the address. Using the above mentioned methods you can get this information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why doesn't just a variable name display the variable in a script, like in the interpreter? I want to display a string which is returned by a function in a Python script, without using print:
def myfunc(mystring):
return "Converting to lowercase :{0}".format(mystring.lower())
result=myfunc("LOWER")
result
But it doesn't give an output. How can I get result to display without print?
A: Your code does print 'Converting to lowercase :lower' when run in an interactive session (using python or ipython).
It does not, however, print anything if run as part of a script, since there is no implicit printing of expression results.
This is how it's meant to be.
If you want to print something from a script, use print or sys.stdout.write().
A: An alternative to print:
sys.stdout.write()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: How do I get the MSBuild task to show up in the Visual Studio project output? I'm trying to printf debug my Visual Studio project file by spewing messages to the console like this:
<Target Name="BeforeBuild">
<Message Text="+++++++++++++++++++++++ Justin Dearing ++++++++++++++++++++++++++++++++++++" />
</Target>
This works from the command line:
BeforeBuild:
+++++++++++++++++++++++ Justin Dearing ++++++++++++++++++++++++++++++++++++
However, the messages don't show up in the Visual Studio 2010 build output. Is there an alternative MSBuild task I can use, or a setting in Visual Studio I can enable to make these messages appear?
A: To change the build output verbosity shown in the Visual Studio 2010 window, open the Options dialog and select the Build and Run settings below the Projects and Solutions node.
Unless you explicitly specify a low message importance, your messages should show up at Normal verbosity or higher.
A: For anyone reading this with MSBuild 16, bear in mind that you can't use message at the project level. You now need to first define InitialTargets
<Project InitialTargets="Test" ...
And then create a task to place the message in:
<Target Name="Test">
<Message Importance="High" Text="A Message" />
</Target>
A: In VisualStudio 2019 a <Message> disappears from Build log if any <Error> Task occurs in "Build" target (and others?) even if <Error> is after <Message>.
In contrast msbuild.exe 16.8.2.56705 displays <Message> in any case.
[Question only implies by example that BeforeBuild is used, I answered anyway as the question title and text perfectly matched my problem that the message was not shown]
A: Add the Importance attribute with value High to Message.
Like this:
<Message Importance="High" Text="+++ Justin Dearing +++" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "78"
}
|
Q: SPARQL query to find all sub classes and a super class of a given class I need to write a SPARQL query to find a superclass/subclasses of a given class.
For example, given http://139.91.183.30:9090/RDF/VRP/Examples/Phenomenon.rdf RDFS vocabulary file, I want to find the superclass of 'AcousticWave' (which is 'Wave').
Similarly if user enters 'Wave', I want to get all sub classes of 'Wave' (which are 'AcousticWave', 'GravityWave', 'InternalWave' and Tide').
How would I write such SPARQL query?
A: The predicate used in rdfs for state sub/super class relationships is rdfs:subClassOf. With that in mind you just need to write triple patterns in your SPARQL query that bind that predicate and the subject or object that you want to match --- AcousticWave in your case.
I hope that the following queries are self-explanatory.
for super classes ...
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX ns: <http://www.domain.com/your/namespace/>
SELECT ?superClass WHERE { ns:AcousticWave rdfs:subClassOf ?superClass . }
And for sub classes ...
SELECT ?subClass WHERE { ?subClass rdfs:subClassOf ns:Wave . }
If you want to retrieve the labels for every subclass of ns:Wave you would do something like ...
SELECT ?subClass ?label WHERE {
?subClass rdfs:subClassOf ns:Wave .
?subClass rdfs:label ?label .
}
If you need the transitive closure of sub/super classes then you have two options:
*
*Iterate recursively over these queries until you have collected the closure.
*Pass your RDF data through a RDF/RDFS reasoner to forward chain all entailments and assert these in your RDF database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Project asking for a config setting that's there already Here is the code that I am calling:
try
{
using (var client = new WCFServiceChannelFactory<IFxCurveService>())
{
guid = client.Call(svc => svc.ReserveSnapshot(fxCurveKey));
DiscountFactorNew[] dfs = client.Call(svc => svc.GetDiscountFactors(guid, dates, from));
return (double)dfs[0].Value;
}
}
catch
{
throw new Exception();
}
Now it can't instantiate the WCFServiceFactory because it can't find one of the .config keys that we require, however, it's there in the app.config.
<appSettings>
<add key="ConfigurationServiceAddress" value="http://ksintapp:91/configurationservice.svc/mex" />
</appSettings>
This file and the file that are calling it are within the same directory. They are the only two files in the project, which is the only project in the solution.
This is the error:
Failed to initialize configuration repository because an application
setting with the key 'ConfigurationServiceAddress' could not be found
in the local configuration file.
Any ideas?
A: If this is an executable application (Console, WinForms, WPF) make sure that the config file is called AppName.exe.config and is located in the same directory as AppName.exe where AppName is the name of the project. If it is a web application make sure that this setting is present in the web.config.
When you add an App.config file to a project of type executable in Visual Studio everytime you build it copies to the output directory (bin/Debug or bin/Release) this config file by renaming it to AppName.exe.config so that at runtime the application is able to resolve it.
A: Figured this out by changing the service creation to this:
using (var client = new WCFServiceChannelFactory<IFxCurveService>(new Uri("http://ksqcoreapp64int:5025/")))
But now I'm having different issues, but at least I got around not needing a config file.
A: A config file has to be loaded by the application that is hosting the code. In your comments you state that this is an assembly that is loaded by excel. You won't be able to create an excel.exe.config file that has any meaning.
So, you're left with explicitly stating what config file to load OR changing to using the registry. I'd probably go with the latter while having that key defined in an install program.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RestKit - POST response object mapping I have method "getBuses" on my RESTful webservice (Rails). That method needs to return
me list of buses in JSON. But, when I sending request for "/getBuses.json" I
need to send
params = [NSDictionary
dictionaryWithObjectsAndKeys: @"2011-08-16", @"datum", @"TRUE",
@"fromSerbia", nil];
I'm posting params because I need filtered response (just for specific
tour on specific date).
Then, I expecting response like this:
{
"buses" : [ {
"bus_number" : "1",
"created_at" : "2011-08-15T23:07:52Z",
"id" : 1,
"lat" : 44.815,
"long" : 20.4665,
"model" : "Setra",
"registar_number" : "123456",
"seats" : 50,
"tour_id" : 1,
"updated_at" : "2011-08-15T23:07:52Z"
}, {
"bus_number" : "2",
"created_at" : "2011-08-15T23:07:52Z",
"id" : 2,
"lat" : 44.812,
"long" : 20.465,
"model" : "Mercedes",
"registar_number" : "2234",
"seats" : 60,
"tour_id" : 1,
"updated_at" : "2011-08-15T23:07:52Z"
} ]
}
I just need NSArray with Bus objects.
Can you give me code example how to make this request and make object mapping with RestKit?
A: As I told you in the IRC Channel, in your RKClient instance you can use this method:
(NSURL *)URLForResourcePath:(NSString *)resourcePath queryParams:(NSDictionary *)queryParams
So you should do it like this:
[objectManager.mappingProvider setMapping:busesMapping forKeyPath:@"buses"];
params = [NSDictionary dictionaryWithObjectsAndKeys: @"2011-08-16", @"datum", @"TRUE", @"fromSerbia", nil];
NSURL *someURL = [objectManager.client URLForResourcePath:@"/service/getLocations.json" queryParams:params];
[objectManager loadObjectsAtResourcePath:[someURL absoluteString] delegate:self];
That method builds a valid URL using the resourcePath and the parameters you give as parameter. And then you need to set it back using the absoluteString of the NSURL object. Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: problem with url being submitted to facebook comment count hit a small problem and wondering if their is a quick easy fix im missing. im wanting to use facebooks, comment count, but for some reason the url gets changed. should have &id=9 for example at the end of the url but facebook is removing everything from the & symbol
so for example
http://www.prog3kt-mayh3m.info/index.php?page=blog&id=9
becomes
http://www.prog3kt-mayh3m.info/index.php?page=blog
heres the code im having issues with, the particular code is being echo'd from within php tags
echo "<iframe src='http://www.facebook.com/plugins/comments.php?href=http://www.prog3kt-mayh3m.info/index.php?page=blog&id=" . $id . "&permalink=1' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:130px; height:16px;' allowTransparency='true'></iframe>";
any help appreciated
A: ok, found the solution,
replace the ampersand with %26:
<iframe src='http://www.facebook.com/plugins/comments.php?href=http://www.prog3kt-mayh3m.info/index.php?page=blog%26id=9&permalink=1' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:130px; height:16px;' allowTransparency='true'></iframe>
it should work ok :)
JsFiddle result
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can a program such as AutoHotkey be implemented in a browser(as an add-on) using JavaScript The main use of AutoHotkey I'm thinking of is to let you define phrase-shortcuts, like typing "tyvm" would yield "thank you very much" - is JavaScript fast enough and capable enough to do this?
A: Your question wasn't exactly clear to if you were only looking for AutoHotkey, so I though I would state "YES" and support that by reference to another implementation: http://keithcirkel.co.uk/jwerty/ in JavaScript that handles keyboard events.
A: I would not say that is the main use of autohotkey, but that is neither here nor there,
In a word, yes, yes it is fast enough, otherwise inputs would not be able to have keydown/keyup events.
What makes you think javascript is slow?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google visualization p property from JSON I wonder how the p-property is supposed to work when sending JSON table row and column data to render.
I try to send {"p":{"title":"This is the title"}} but I can't get it to work.
Is it possible to set graph configuration options from JSON response?
Best regards,
Niclas
A: Found a solution. Don't know if it is the best out there but it works.
On the server. Add p properties to the JSON data. In this case 'title'.
function drawChart() {
var jsonData = $.ajax({
url: "/statistics/getData",
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var title = data.getTableProperty("title");
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, {'title':title,
'width':800,'height':300});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JavaScript applications and empty HTML elements JavaScript application often use one of the following methods:
*
*They use empty HTML elements (which exist in markup but are invisible because of display:none)
*They generate markup dynamically
*A combination of both
What is the best case for each of these methods? When should I prefer one over the other, and why?
A: It all depends on what you're trying to do.
If you want to add elements to a page, and you know how many you need, you can have them on the page and hide/show them when needed.
If you want to add a dynamic number of new elements, you can just make them on-the-fly, because having them on the page to begin with may not work if you need more than you added.
You can also clone existing elements, and change their attributes, to add elements to a page.
This all depends on what you're trying to do.
For example:
*
*You have a form that can accept a dynamic number of inputs. You don't know how many the user wants, so having them on the page to start with (hidden) won't help. You can either clone the existing inputs (and change their values), or create new ones and add them.
*You have a form that allows from 2-5 names to be added. Since there is a fixed amount, you can add 5 inputs, hide 3 of them to begin with, and show them if needed.
So, there are different methods for what you are trying to do.
A: Things to considerate:
*
*Less HTML code, less time to load web app.
*The main goal is minimize the HTML Reflow:
http://code.google.com/speed/articles/reflow.html
I choose A combination of both to optimize the load time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Returning the input stream of the object that the caller already has an instance of I have a design question.
I'm using the HttpURLConnection class to navigate a website. In order to obtain an HttpURLConnection instance, I have a local getter method. This is responsible for setting all the request properties, including possible cookies. Anyway, throughout the life cycle of this application, I use multiple HttpURLConnection instances. And never is there more than one open connection.
Anyway, I have another local method for sending requests in the form of an HTTP POST. Here is the code:
private final InputStream sendRequest(final HttpURLConnection conn, final String content){
InputStream in = null;
DataOutputStream out = null;
try{
// Write data out to the stream
out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(content);
out.flush();
// Get the input stream
in = conn.getInputStream();
}
catch(IOException e){
e.printStackTrace();
}
finally{
try
{
if(out != null){
out.close();
}
}
catch(IOException e){
e.printStackTrace();
}
}
return in;
}
As you can see, as soon as I'm done writing out the content, I open an input stream on the connection and return it. The reason I do this is if I do not open the input stream on the connection, the application will hang. Therefore, I'm leaving it up to the caller as to whether or not they want to parse the incoming content. Also, the caller needs the connection instance because I leave it up to them to disconnect (that is, close the connection).
So, I guess my question is, is this a poor design? That is, opening the input stream of the connection object that the caller already has an instance of and then returning it?
A: It's a shame you're not allowed to use Apache HttpClient, but a little OOP may help you untangle your code.
Introduce a ResponseHandler interface for the caller to implement. You might also want to provide some out-of-the-box implementations in public static fields (if thread-safe) or via factory methods for the common cases like "give me a String" (make sure to consult the "charset" part of the response's Content-Encoding header when creating your InputStreamReader) and "give me a byte[]".
Don't supply just the InputStream to the ResponseHandler as you might need access to the response headers for character encoding, etc.
Again, this would really be much much nicer with HttpClient :/
(the following code lacks basic sanity checks for the parameters, please add them)
public interface ResponseHandler<T> {
T handleResponse(HttpURLConnection conn);
}
public <T> T sendRequest(final HttpURLConnection conn, final String content,
final ResponseHandler<T> handler)
throws IOException {
OutputStream out = null;
try {
out = conn.getOutputStream();
// uses platform encoding, might want to explicitly
// specify "UTF-8"
out.write(content.getBytes());
out.flush();
return handler.handleResponse(conn);
} finally {
// closing out omitted for brevity
}
}
Edit: If you can somehow managed to get rid of HttpUrlConnection in the calling code, that would be even better. Check out if you can get along with a String for the URL and a Map<String, Object> for the parameters, maybe wrap this in a HttpRequest object.
A: Well IMHO if your class actually handled all the I/O with the HTTP server and returned to the caller the HTTP response body (if there was any) it would make sense.
Now the sendRequest method is not of much use since the caller has to deal with the HTTP and I/O details anyway
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run Jquery on click of an ActionLink How do I run jquery when an MVC ActionLink is clicked? I have an action that takes some time. I want to show a 'processing' image until it returns. Is there a better way to do this?
A: Give the actionlink a class:
@Html.ActionLink("","", new { @class:"delete" })
Then you can hook up your jQuery to the class name in a js file:
$(document).ready(function() {
$('.delete').click(function() {
///Code
});
});
You can also work with id.
A: You can also use @Ajax.ActionLink without need of jQuery script.
For example you can show a div when loading a page.
<div>
@Ajax.ActionLink("Link name", "Action", "Controller", new AjaxOptions { LoadingElementId = "loadingId", UpdateTargetId = "MyDataTable" })
</div>
<div id="loadingId" style="display:none; color:Red; font-weight: bold">
<p>Please wait...</p>
</div>
<div id = "MyData" class="tablediv">
<table id = "MyDataTable" class="Grid">
<tbody id="chartdata">
</tbody>
</table>
</div>
A: $('#element-id').live('click', function(e) {
//do stuff here ...
});
The trick is to give your action link an ID HTML attribute so you can use it as your element id:
$('#html-attribute-id').live('click', function(e) {
//do stuff here ...
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Declaring vector as global variable in C++ Is it a good practice to declare a vector as global in C++?
This is what I did.
#include <vector>
std::vector<int> vec;
My program compiles successfully, but I am not sure whether this could lead to a runtime
error under certain circumstances. According to my understanding, the memory for a global variable will be allocated at compile time, and the compiler may reserve a limited amount of memory to which this vector can expand. Upon hitting this limit, what is being written can eat into the memory used by another variable.
Please advise.
A:
According to my understanding, the memory for a global variable will be allocated at compile time, and the compiler may reserve a limited amount of memory to which this vector can expand.
This is wrong understanding.
Memory is not allocated at compile time. Memory is allocated at the program startup, and then during the program, depending on the storage types of variables. And when the program shutdowns, all the memory used by it returns to the OS, no matter what.
Upon hitting this limit, what is being written can eat into the memory used by another variable.
No. An object of std::vector<int> can never eat memory used by another variable(s).
Now coming back to your main question,
Is it a good practice to declare a vector as global in C++?
No. Avoid global variables, irrespective of their types.
A: Only the space for the vector metadata will be allocated in the area for global variables. The vector contents will still be dynamically allocated (constructors and destructors run normally for global variables).
It's the same situation for an automatic vector variable, like:
int main(void)
{
std::vector<int> v;
return 0;
}
There's a limit to the stack space available for automatic variables, but the vector contents won't use this space, only a handful of pointers and counters.
A: Global variables in general are bad practice. They won't "eat" into memory of another variable as you say, however, it's very easy for you as the programmer to screw something up. For example, everything in the program has access to this vector and so everything can access and modify it. You may or may not want this, but more than likely, you don't want this.
As for memory allocation, objects added to the vector are still added on runtime (because they don't exist on compile time!). Memory is also never allocated at compile time. Your program has the signature in it to allocate this memory at RUN time. Think about that...if the program allocated memory at compile time, you wouldn't really be able to run them on other machines would you? The memory would be allocated on YOUR machine, but not on other machines. Hence, memory must be allocated on run time.
A: Your program doesn't allocate anything during compile-time - I think you mean run-time.
Vector allocates what it holds on the heap (vec.size() * sizeof(/* what you are holding*/)) - it holds sizeof(std::vector<>) on where it is allocated. Global variables may be stored anywhere, it depends on the implementation.
A: Well, vec is a global variable, so the memory for it is presumably allocated from the data segment. However, the memory for the contents of vec depends on the allocator. By default, I think that the memory for the contents is allocated from the heap.
A:
My program compiles successfully, but I am not sure whether this could
lead to a runtime error under certain circumstances.
This is safe to do; the storage for the vec variable will be allocated statically and its default constructor will be called at some point (exactly when within the context of your entire program is not strictly defined, as order of initialization across translation units is not strictly defined).
and the compiler may reserve a limited amount of memory to which this
vector can expand. Upon hitting this limit, what is being written can
eat into the memory used by another variable.
The vector itself allocates its storage on the heap, so there will be no limitations imposed upon its expansion that would be different if you instantiated the vector as a local variable: you're basically going to be limited by the amount of memory you can contiguously allocate at the points in time the vector needs to reallocate its internal storage.
All of that said, while this is safe to do so, it isn't necessarily good practice; it falls into the domain of every other global variable or globally-accessible bit of storage, which can be a bit of a contentious subject. Generally, I would advise that it is preferable to avoid global variable as a rule. While it may be acceptable in some cases, the global access runs counter to your ability to control the access to the variable and enforce invariants on it and the state it controls or implies. This can lead to difficult-to-maintain systems as a codebase scales because those access paths are not clearly spelled out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: How to control casting of null int field to varchar in sql server? First of all I would like to know how does CAST work with NULL fields and how does it behave when the value is NULL?
For example in the expression:
(CAST(INT_FIELD as nvarchar(100))
what happens if the value INT_FIELD is NULL?
The reason is that when I'm trying to do the following:
SELECT (CAST(INT_FIELD as nvarchar(100)) + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;
I'm getting NULL even though the SOME_OTHER_FIELD is not null. I'm guessing it has some kind of logic that NULL + something = NULL but I'm not sure.
How can I control this behavior?
A: Look into COALESCE, where you can find the first non-null and return 0 if all are null, e.g:
SELECT (CAST(COALESCE(INT_FIELD,0) as nvarchar(100)) + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;
A: Try using COALESCE
SELECT COALESCE(CAST(INT_FIELD as nvarchar(100), '') + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;
A: You need to use ISNULL or COALESCE, since most row operation between a NULL is gonna result in NULL. CAST of a NULL returns NULL and NULL + something is also NULL. In your example you should do something like this:
SELECT ISNULL(CAST(INT_FIELD as nvarchar(100)),'') + ' ' + ISNULL(SOME_OTHER_FIELD,'')
FROM SOME_TABLE;
Of course, in my example, if both fields are NULL it will return ' ' instead of '', but you get the idea.
A: Normally, NULL +(-,/,*, etc) something = NULL.
You can use
SELECT ISNULL(CAST(INT_FIELD as nvarchar(100)),'')
+ ' ' + ISNULL(SOME_OTHER_FIELD FROM SOME_TABLE,'')
or you can SET CONCAT_NULL_YIELDS_NULL OFF (more details)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: timing practices for multiple html5 canvas elements on web page I have found some articles on using request animation frames for animating html5 canvas elements. http://paulirish.com/2011/requestanimationframe-for-smart-animating/
If I were to have multiple elements, should I have a timing system for each of them individually (a separate script) or should I have them all within a single loop?
This is for a magazine concept, wherein you may have each 'page' with a different animation (one a series of lines, another a wave, perhaps another that disintegrates an image before your eyes as you read the text)
any help is always appreciated.
A: That's entirely up to you. Do you want the elements to run in sync with each other or not? Or does it not matter?
If its doesn't matter or if you need them synced, keep them all in one loop with one timer. It's probably faster on every browser and it will be easier to debug, maintain, and understand the code.
If they shouldn't be synced up then of course you must have two timers! Also, if you feel in the future you might want different parts to run at distinctly different or changing speeds, then you might want to consider two timers.
A: I assume that you will develop each animations separately, and further these animations are not related with each other. In such case you not at all need for synchronization... If you go for sync them up in one loop, you will have following problems...
*
*If animation in one canvas is slow, animation in other canvas will have to unnecessarily wait...
*requestAnimationFrame help you create intelligent loop, ie if your canvas in hidden or your tab is not active, callback will not occur for canvas. In case of syncing, you will not be able to optimize fully.
*
*It will be more complex to manage all the animation in one loop rather then individual loop.
*While debugging, you may come across problems caused by other animations in the page...
So if your animations are not related, I highly recommend not to sync the animations with one loop. Hope this answers your questions.
Following link will help you learn more about Html5 Canvas...
*
*http://www.technobits.net/articles/13730/improving-html5-canvas-performance/
*http://www.technobits.net/search/page-1/?q=%22html5%20canvas%22
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I make my QThread block and wait for a function called from the main thread to return a value? I am doing some work in a QThread reimplementation. Every now and then, I'd like to ask the user a Yes/No question, so I was planning on using QMessageBox::question(). Problem is, I can't call it from the thread. That's not a big one, I can emit a signal that connects to a slot in the main GUI thread which will display the message box, but I also need the custom thread to block and wait for the message box to be dismissed and retrieve the return value as well (here, a QMessageBox::StandardButton). How do I get around to doing that?
EDIT:
Will the following (pseudo-)code do the trick?
class MyThread
{
public:
MyThread(QObject *parent)
{
connect(this, SIGNAL(inputRequired()), parent, SLOT(popMsgBox()), Qt::QueuedConnection);
}
void MyThread::run()
{
QMutex m;
for (...)
{
if (something)
{
m.lock();
emit inputRequired();
w.wait(&m);
m.unlock();
}
if (MyGui->ans_ == Yes) do_something();
}
}
signals:
void inputRequired();
protected:
QWaitCondition w;
};
void MyGui::popMsgBox()
{
ans_ = QMessageBox::question(this, "Question", "Yes or no?", Yes | No);
MyThread->w->wakeAll();
}
A: Simple answer - use a condition.
http://doc.qt.io/qt-5/qwaitcondition.html
A: If you are working with signals and slots anyway, you can also use the Qt::BlockingQueuedConnection connection type. This connection will wait until the slot (in another thread) is finished executing. Be careful not to deadlock though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Resizing GridView columns after making it visible The setup:
ListView with GridView that is initially hidden when the window is loaded, and then made visible upon a certain user action.
The aim:
Be able to set relative width of GridView's columns.
The problem:
What I need can be achieved either by using a converter on the width (something similar to the answer here), or by adding a Behavior on the ListView (see this solution).
The both approaches seem to be valid - but only for the controls that are rendered from the early beginning.
In my case, the ActualWidth is always 0 when the calculations are made, and these calculations are not repeated when the ListView is made visible.
So, I guess, the real question here is how to get the columns' Width to be re-evaluated when ListView's ActualWidth gets greater than 0.
The solution would preferably be at the XAML level, without involving the code-behind - but that will do too, if that's the only alternative ;-)
Any suggestions?
P.S. Following Chris's question below, here's a clarification on how the ListView is hidden/shown: it's a child of another container control, hosted in a Grid column, and the width of that column is manipulated by a trigger.
<ColumnDefinition>
<ColumnDefinition.Style>
<Style>
<Setter Property="ColumnDefinition.Width" Value="4*"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=OpenItems.Count}" Value="0">
<Setter Property="ColumnDefinition.Width" Value="0"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ColumnDefinition.Style>
</ColumnDefinition>
I tried to apply a similar trigger to the ListView's container itself (to manipulate its Visibility between Collapsed and Visible) instead, but the problem with that is that the Column doesn't shrink from its original 4* width, so I see the (empty) control when it's supposed to be hidden.
A: How are you hiding/showing the ListView? The question seems to imply that you are doing so by setting the Width property to 0 (or non-zero to show it). Instead, you should try using the Visibility property (set to "Collapsed" to hide, or "Visible" to show). This should cause the column's width to be re-evaluated.
UPDATE:
Based on your updated question, I'd suggest checking out this solution: http://www.codeproject.com/KB/grid/ListView_layout_manager.aspx
I got it from here FWIW: WPF : Extend last column of ListView's GridView
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Magento getting a products rewritten URL If you look at this thread;
http://www.magentocommerce.com/boards/viewthread/10807/
It adds a products rewritten url to the collection using;
$collection->addUrlRewrite($categoryId);
I am not getting products this way, I am using this method to get an individual product:
$product->load($productId);
After quite a bit of searching I cant seem to figure a way of getting a products rewritten url using this method, can anyone tell me how I may go about this please?
Thanks
A: I'm not quite sure whether "rewritten url" means request_path or target_path in your question context, but anyway.
To get the request path of a single product you can do this:
$oProduct = Mage::getModel('catalog/product')->load($productId);
var_dump(
$oProduct->getUrlPath()
);
To get the target path, you can use this:
$oProduct = Mage::getModel('catalog/product')->load($productId);
$oRewrite = Mage::getModel('core/url_rewrite')->loadByRequestPath(
$oProduct->getUrlPath()
);
var_dump(
$oRewrite->getTargetPath()
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Separate Data by Comma I am learning RegEx. completely a newbie :P
I wanted to separate numbers from the below data, which are separated by comma only
test
t,b
45,49
31,34,38,34,56,23,,,,3,23,23653,3875,3.7,8.5,2.5,7.8,2., 6 6 6 6 ,
,
.
.,/;,jm.m.,,n ,sdsd, 3,2m54,2 4,2m,ar ,SSD A,,B,4D,CE,S4,D,2343ES,SD
Suppose I am getting the above data from Form text field. Now I want to read the data only which are numbers seperated by comma
Solution should be[string]
45,49,31,34,38,34,56,23,3,23,23653,3875
all other data should be skipped.
I tried something like this ^[0-9]+\,$
But it's also selecting 7 from 3.7, and 5 from 8.5, etc.....
Can anyone help me out in solving this!!
A: Assuming you are already splitting at commas and try to check whether the elements you get are numbers, use this expression: ^\d+(?:\.\d+)?$, which means: "must begin with digits potentially followed by a dot and at least one more digit".
This would match 31 as well as 7.8, but not 2., 6 6 6 6 or 2m54.
Here's a part by part explanation of that expression:
*
*^ means: matches must start at the first character
*$ means: matches must end at the last character, so both together mean the entire string must match
*\d+ means: one or more digits
*(?: ... ) is a non-capturing group allowing to apply the ? quantifier
*\. means: the literal dot
*(?:\.\d+)? thus means: zero or one occurences of a dot followed by at least one digit
Edit: if you only want integer numbers, just remove the group: ^\d+$ -> entire input must be one or more digits.
Edit 2: If you can prepend and append a comma to the input string(see Edit 4), you should be able to use this regex for getting all numbers: (?<=,)\s*(\d+(?:\.\d+)?)\s*(?=,) (integers only would require you to remove the (?:\.\d+)? part).
That expression gets all numbers between two commas with possible whitespace between the commas and the number and catches the number into a group. This should prevent matches of 6 6 6 6 or 2m54. Then just iterate over the matches to get all the groups.
Edit 3: Here's an example with your input string.
String input = "test\n" +
"t,b\n" +
"45,49\n" +
"31,34,38,34,56,23,,,,3,23,23653,3875,3.7,8.5,2.5,7.8,2., 6 6 6 6 ,\n" +
",\n" +
".\n" +
".,/;,jm.m.,,n ,sdsd, 3,2m54,2 4,2m,ar ,SSD A,,B,4D,CE,S4,D,2343ES,SD\n";
Pattern p = Pattern.compile( "(?<=,|\\n)\\s*(\\d+(?:\\.\\d+)?)\\s*(?=,|\\n)" );
Matcher m = p.matcher( input );
List<String> numbers = new ArrayList<String>();
while(m.find())
{
numbers.add( m.group( 1 ) );
}
System.out.println(Arrays.toString( numbers.toArray() ));
//prints: [45, 49, 31, 34, 38, 34, 56, 23, 3, 23, 23653, 3875, 3.7, 8.5, 2.5, 7.8, 3]
//removing the faction group: [45, 49, 31, 34, 38, 34, 56, 23, 3, 23, 23653, 3875, 3]
Edit 4: actually, you don't need to add commas, just use this expression:
`(?<=,|\n|^)\s*(\d+)\s*(?=,|\n|$)`
The groups at the start and end mean the match must follow the start of the input, a comma or a line break and be followed by the end of the input, a comma or a line break.
A: The shortest solution i could come up with would be to replace anything that isn't a set of numbers separated by commas with the empty string. So you could do s.replaceAll("[^0-9]*,", ",") If you have random newlines in there, you will probably want to add in a s.replaceAll("\n", ","). Then after those transformations, you can just do as suggested and split on commas.
A: this experssion will give you all numbers you need (only numbers, no commas).
"^\d+|(?<=,)\d+$|(?<=,)\d+(?=,)"
see the grep example:
kent$ echo "31,34,38,34,56,23,,,,3,23,23653,3875,3.7,8.5,2.5,7.8,2., 6 6 6 6 ,
"|grep -oP "^\d+|(?<=,)\d+$|(?<=,)\d+(?=,)"
31
34
38
34
56
23
3
23
23653
3875
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: python: simple way to input python data from file In a shell script one might do something like:
myvar='default_value'
source myfile.sh
echo $myvar
where myfile.sh is something like:
echo "myvar='special_value'" > myfile.sh
I know several "safe" ways of doing this in python, but the only way I can think of getting similar behaviour in Python (albeit ugly and unsafe) is the following:
myvar = 'default_value'
myimport = 'from %s import *' % 'myfile'
exec(myimport)
print(myvar)
where myfile.py is in ./ and looks like:
myvar = 'special_value'
I guess I would be happiest doing something like:
m.myvar = 'default_value'
m.update(__import__(myimport))
and have the objects in m updated. I can't think of an easy way of doing this without writing something to loop over the objects.
A: There are two ways to look at this question.
How can I read key-value pairs in python? Is there a standard way to do this?
and
How can I give full expressive power to a configuration script?
If your question is the first; then the most obvious answer is to use the ConfigParser module:
from ConfigParser import RawConfigParser
parser = RawConfigParser({"myvar": "default_value"}) # Never use ConfigParser.ConfigParser!
parser.read("my_config")
myvar = parser.get("mysection", "myvar")
Which would read a value from a file that looks like a normal INI style config:
# You can use comments
[mysection]
myvar = special_value
For the second option, when you really want to give full power of python to a configuration (which is rare, but sometimes necessary), You probably don't want to use import, instead you should use execfile:
config = {}
execfile("my_config", config)
myvar = config.get("myvar", "default_value")
Which in turn will read from a python script; it will read the global variable myvar no matter how the script derives it:
import random
myvar = random.choice("special_value", "another_value")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Resharper shortcut for closing Find Usages window? What's the Resharper shortcut for closing Find Usages or similar type of window?
A: I use Ctrl+F4.
Shift + Esc doesn't work for me even though "Options... Keyboard" "Window.CloseWindow" shows Shift + Esc. (VS 2013, R# 8.2)
A: Ctrl+Shift+F4 will close most recently used tab in any ReSharper toolwindow. Shift+Esc will close the toolwindow. Esc inside toolwindow will focus code editor.
A: Find Usages is a Tool Window like any other, so the shortcut to close it is Shift+Esc (or, if this doesn't appear to work, check what it says in VS Tools | Options..., Keyboard, Window.CloseToolWindow).
THAT SAID I've always been slightly hazy on how to use the keyboard to get focus to / from Tool Windows - Ctrl+Tab works fine from a code window into a Tool Window, but doesn't always seem to work to get you out...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Jenkins Database and Authentication Does Jenkins store build status information into a database on its own? Does it have a plugin to talk to an Oracle database? If yes, can the slaves running on remote sites do this on their own, without master having to do the database interaction?
I will be running Jenkins on remote sites.Won't network hiccups cause master to think that the build has failed?
A: You can configure Audit to Database plugin to store build data into DB using oracle, mysql, postgres, etc.
Regards!
A:
Does Jenkins store build status information into a database on its own?
Everything is stored locally in XML files on the master.
Does it have a plugin to talk to an Oracle database?
No, for the reason above.
Won't network hiccups cause master to think that the build has failed?
Yes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Membership.GetUser().UserName; (.net 4, mvc 3) i log users into .net using straightforward .net authentication:
if ( Membership.ValidateUser( user, passwd ) )
works fine. hot on the heels of that, i try to get the user name:
Membership.GetUser().UserName
sometimes this will return an invalid object. sometimes not.
i cannot seem to detect a pattern as to which is which.
for example, a user logs in with a valid role in the system as 'root'/'password'.
the ValidateUser() call succeeds, but Membership.GetUser().UserName returns an invalid object.
2 seconds later, do the same exact thing again, and both the validate and the GetUser() succeed.
any ideas?
.. edit 1 ..
here's how i use the username:
Roles.GetRolesForUser( Membership.GetUser().UserName );
when i swap in System.Environment.UserName, the roles list comes back empty.
if i leave it as is and i set the auth cookie using 'true' as my second argument, it works fine.
FormsAuthentication.SetAuthCookie( user, true );
if i use HttpContext.Current.User.Identity.Name, the roles list is fine with the auth cookie set to true or false.
now, i understand the issue about performance. this is important to me. but i also need to ensure the application functions correctly.
A: Why can't you use
HttpContext.Current.User.Identity.Name
?
A: Membership.ValidateUser() returns true or false whether the user is valid or not, but it does not sign them in.
Membership.ValidateUser Method
Verifies that the supplied user name and password are valid.
Try this instead:
bool createPersistentCookie = true; // remember me?
if (Membership.ValidateUser(user, passwd)) {
FormsAuthentication.SetAuthCookie(user, createPersistentCookie);
if (FormsAuthentication.GetAuthCookie(user, createPersistentCookie) == null)
throw new SecurityException("Authentication persistence failed");
Membership.GetUser().UserName; // should have a value now
}
else
{
// invalid login
}
A: I am using the system.web.security methods to authenticate users to use web service methods.
I don't use the cookie authentication in FormsAuthentication at all.
I have to set up the roles associated with the web service methods in the web.config file
<add name="rule1" url="~/WebService.svc/rest/help" method="*" role="?"/>
<add name="rule1" url="~/WebService.svc/rest/Method1" method="*" role="service"/>
<add name="rule1" url="~/WebService.svc/rest/Method2" method="*" role="service"/>...
Then the following code is called every time a request comes in to verify the authentication:
Membership.ValidateUser(username, password); //Validates user credential
Roles.IsUserInRole(username, "/WebService.svc/rest/Method2"); //Verifies User is authorised for method in question
A: Are you using cookies to persist user credentials? If so.. I believe the following authentication steps should be taken:
*
*call ValidateUser to check for correct credentials.. as you already do
*call FormsAuthentication.SetAuthCookie to to set the authentication cookie
*Response.Redirect( "Some home page or another "); will refresh the credentials cookies and get you a valid user object
Hope it helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to make header of a table "draggable" I have a table. The top row has 2 columns - "header" and "close" button. I can make the entire table "draggable". How can I make the "header" to be the only element that user can drag in order to move the entire table around?
UPDATED: As tagged, I need to use jQuery. This is what's not working:
$(tblElement).draggable({ handle: "tdDialogHeader" });
A: I'll assume you're using the jQuery UI. Then you're looking for the "handle" option.
$( "#draggable" ).draggable({ handle: "thead" });
A: If the solution suggested by Sinetheta doesn't work for you, that means your table doesn't have "tHead" tag as its header. jQuery is not great with tables, especially if they are malformed. Replace the "TR" tag of the first row in your table with "tHead" and try the Sinetheta's code. Should work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use for loop variable as dictionary key in Django template I am trying to get the following working.
The count loop needs to loop through for all values, and there may not be a user associated with each count, but the count value i needs to be used in each loop to pass to the JavaScript.
python part:
users = {}
users[1]={}
users[1][id]=...
users[1][email]=...
...
count=[1,2,3,4,5,6,7,8,9,10]
Django template part:
{% for i in count %}
do some stuff with the value i using {{i}} which always returns the value, i.e. 1
email:{% if users.i.email %}'{{users.i.email}}'{% else %}null{% endif%}
{% endfor %}
This returns nothing for email.
When I substitute the number 1 for i in {% if user.i.email %} email returns the users email address.
I'm using the data in JavaScript, so it needs to be implicitly null if it doesn't exist.
I can't seem to get Django to recognize the i variable as a variable instead of the value i.
using [] doesn't work, as it throws an invalid syntax error
email:{% if users.[i].email %}'{{users.[i].email}}'{% else %}null{% endif%}
I have tried using "with" statement
{% for i in count %}{% with current_user=users.i %}...
and then using current_user.email, but returned nothing
Have also tried
{% for i in count %}{% with j=i.value %}...
just in case it would work, and then trying to use j, but same result.
I have thought about creating an inner for loop that loops over the user object and check if i is equal to the key/value, but that seems expensive and not very scalable.
Any ideas how I can force Django to view i as a variable and use it's value as an index, or any other way get around this?
Thanks
Jayd
*Edit:
I tried the extra for loop, as suggested by Abhi, below.
{% for i in count %}
{% for key, current_user in users.items %}
do some stuff with the value i using {{i}} which always returns the value, i.e. 1
email:{% if i == key and current_user.email %}'{{current_user.email}}'{% else %}null{% endif%}
{% endfor %}
{% endfor %}
This sort of works, but now it will repeat do some stuff with the value i for every value of users. and if I put in an if:
{% for i in count %}
{% for key, current_user in users.items %}
{% if i == key %}
do some stuff with the value i using {{i}} which always returns the value, i.e. 1
email:{% if i == key and current_user.email %}'{{current_user.email}}'{% else %}null{% endif%}
{% endif%}
{% endfor %}
{% endfor %}
That ignores the loops when a count doesn't have a particular user.
The only way I can see around this is the have the user loop at each place that I want to use current_user.
{% for i in count %}
do some stuff with the value i using {{i}} which always returns the value, i.e. 1
email:{% for key, current_user in users.items %}{% if i == key and current_user.email %}'{{current_user.email}}'{% else %}null{% endif%}{% endfor %}
{% endfor %}
And this seems very expensive to do.
Any ideas?
I was thinking of maybe writing a filter that returns the values for users using i as the key:
{% with current_user=users|getuser:i %}
But I don't know if this will work or I will get the same error, where i is being passed as the value 'i' instead of a variable name.
I will give it a try so long.
*Edit
This didn't work.
The filter worked using {{}} returning the object, but it didn't work inside the {% %}
.
Thanks for the input
A: As Joe says in his comment, a dictionary is clearly the wrong data structure for the outer container. You should be using a list.
users = []
user = {'id':..., 'email': ...}
users.append(user)
...
{% for user in users %}
{{ user.email }}
{% endfor %}
If you need the number of each user within the loop, you can use {{ forloop.counter }}.
A: Try this:
{% for key,val in user.items %}
ID is {{ val.id }} and Email is {{ val.email }}
{% endfor %}
A: I have come up with the following as a work around:
This is the filter code:
@register.filter(name='dict_value_or_null')
def dict_value_or_null(dict, key):
if key in dict:
return dict[key]
else:
return 'null'
Here is the template code
{% for i in count %}
do some stuff with the value i using {{i}} which always returns the value, i.e. 1
email:'{{users|dict_value_or_null:i|dict_value_or_null:'email'}}'
{% endfor %}
This works well, so I suppose that have my solution. But I still think this all could have been much easier if there was a way in the template system to force values inside {% %} to be treated as variables, instead of literals.
Is there a way to do this?
Thanks for the input
A: to make Jayd Code usable with either list or dict, try this
@register.filter(name='dict_value_or_null')
def dict_value_or_null(dict, key):
try:
return dict[key]
except:
return 'null'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: SQL need to return data even if specific where statement isnt matched I've built an extension to a employment application where we can easily add new questions to the form. I need to query to match on both which job they applied to and what application ID it is. I need to return both the answer and the question, the problem is it will return both if both are defined, but I need it to return the question, even if the application isn't defined, but right now it'll only return the question if the answer is defined.
Please help!
Code: (Note the where uses a Coldfusion variable, so nothing out of the normal)
SELECT
dbo.mod_employmentAppQuestionAnswers.questionID
,dbo.mod_employmentAppQuestionAnswers.questionDefinitionID
,dbo.mod_employmentAppQuestionAnswers.AppID
,dbo.mod_employmentAppQuestionAnswers.questionText
,dbo.mod_employmentAppQuestionAnswers.questionDate1
,dbo.mod_employmentAppQuestionAnswers.questionDate2
,dbo.mod_employmentAppQuestionAnswers.questionBit
,dbo.mod_employmentAppQuestionDefinitions.definitionID
,dbo.mod_employmentAppQuestionDefinitions.jobTitleID
,dbo.mod_employmentAppQuestionDefinitions.title AS QuestionTitle
,dbo.mod_employmentAppQuestionDefinitions.questionTypeID
,dbo.mod_employmentAppQuestionDefinitions.description
,dbo.mod_employmentAppQuestionDefinitions.isActive
,dbo.mod_employmentAppJobTitles.title AS JobTitle
,dbo.mod_employmentAppQuestionTypes.type AS QuestionType
FROM dbo.mod_employmentAppQuestionAnswers
FULL JOIN dbo.mod_employmentAppQuestionDefinitions
ON dbo.mod_employmentAppQuestionAnswers.questionDefinitionID = dbo.mod_employmentAppQuestionDefinitions.definitionID
INNER JOIN dbo.mod_employmentAppJobTitles
ON dbo.mod_employmentAppQuestionDefinitions.jobTitleID = dbo.mod_employmentAppJobTitles.jobTitleID
LEFT JOIN dbo.mod_employmentAppQuestionTypes
ON dbo.mod_employmentAppQuestionDefinitions.questionTypeID = dbo.mod_employmentAppQuestionTypes.questionTypeID
WHERE
(dbo.mod_employmentAppQuestionDefinitions.jobTitleID =
<cfqueryparam cfsqltype="cf_sql_integer" value="#jobTitleID#" />) AND
(dbo.mod_employmentAppQuestionAnswers.AppID =
<cfqueryparam cfsqltype="cf_sql_integer" value="#applicationID#" />)
Database design below:
A: I would use left across. I'm not sure you used FULL JOIN intentionally except in an attempt to get better results, right? Also please learn to use aliases for tables in your joins - people who have to read your code will thank you, I promise.
SELECT
a.questionID
,a.questionDefinitionID
,a.AppID
,a.questionText
,a.questionDate1
,a.questionDate2
,a.questionBit
,d.definitionID
,d.jobTitleID
,d.title AS QuestionTitle
,d.questionTypeID
,d.description
,d.isActive
,t.title AS JobTitle
,qt.type AS QuestionType
FROM
dbo.mod_employmentAppQuestionDefinitions AS d
LEFT OUTER JOIN
dbo.mod_employmentAppQuestionAnswers AS a
ON a.questionDefinitionID = d.definitionID
AND a.AppID = <cfqueryparam cfsqltype="cf_sql_integer" value="#applicationID#" />
LEFT OUTER JOIN
dbo.mod_employmentAppJobTitles AS t
ON d.jobTitleID = t.jobTitleID
LEFT OUTER JOIN
dbo.mod_employmentAppQuestionTypes AS qt
ON d.questionTypeID = qt.questionTypeID
WHERE
d.jobTitleID = <cfqueryparam cfsqltype="cf_sql_integer" value="#jobTitleID#" />
A: Simply you have to use left outer join there...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mongoid: before_destroy and Paranoia Is there some callbacks for soft deleting in Mongoid? Because before_destory won't be triggered.
Now I thought I can use before_update but it looks not so clear solution as I want and it is not triggered as well
class Message
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
before_update :some_action
private
def some_action
if self.deleted_at_changed?
... # do my stuff
end
end
end
So the only solution is to call it from destroy action in controller?
A: Mongoid supports paranoid documents.
What you do is include the Paranoia mixin:
class Person
include Mongoid::Document
include Mongoid::Paranoia
end
Then observe the following new features:
person.delete # Sets the deleted_at field to the current time.
person.delete! # Permanently deletes the document.
person.destroy! # Permanently delete the document with callbacks.
person.restore # Brings the "deleted" document back to life.
You can find this information in the extra part of the documentation on the mogoid website here.
A: What I did is:
def delete_with_callbacks
run_callbacks(:destroy) { delete_without_callbacks }
end
alias_method_chain :delete, :callbacks
A: As Tyler mentioned, you can use Mongoid::Paranoia. This will give you another option ::
message.remove
To check to see if it has been deleted or not, you can use message.destroyed?.
Also Message.deleted would fetch you all the Soft Deleted (removed) records from class Message.
Visit their beautiful documentation along with this one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Get the following error when trying to run rails server Just shifted from rails 3.0.0 to 3.1.0
When I try to run rails s, I get the following error:
`alias_method': undefined method `method_missing_with_paginate' for class `ActiveSupport::Deprecation::DeprecatedConstantProxy' (NameError)
A: Probably a problem with your pagination gem or plugin. Do you use will_paginate or Kaminari ? Try to update your pagination gem to the latest version. A few weeks ago Mislav has published the new version 3.0 of will_paginate, which works with Rails 3. Kaminari also works with Rails 3.
A: The error concerns with_paginate. Are you sure you didn't simply misspell will_paginate somewhere?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: LESS.JS Redundancy in CSS, Use of Mixins instead of selector inheritance? I am using less.js with some regular use of mixins. E.g. I do have a basic class 'gradientBlack' like this.
.gradientBlack {
background: #333333;
background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5a5a5a), color-stop(60%, #333333), color-stop(100%, #000000));
background: -webkit-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -o-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -ms-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#5a5a5a', endColorstr='#000000', GradientType=0 );
background: linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
}
Then I reuse this class at several definitions, like
h3 {
.gradientBlack;
...
}
.darkBox {
.gradientBlack;
...
}
A disadvantage of this approach is, that it bloats the CSS with redundant definitions. E.g. the computed CSS might look similar to this.
h3 {
background: #333333;
background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5a5a5a), color-stop(60%, #333333), color-stop(100%, #000000));
//... and maybe some more (redundant) definitions
}
.darkBox {
background: #333333;
background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5a5a5a), color-stop(60%, #333333), color-stop(100%, #000000));
//... and maybe some more (redundant) definitions
}
For someone like me, who uses a lot of gradients, roundCorners etc, this adds up quickly.
Question (edited)
I found out that the known name for this topic is selector inheritance (see Sass) and as it seems isn't implemented right now. Usage and advantages are discussed here. The computed css of this syntax might look like this.
h3,
.darkBox,
.gradientBlack {
background: #333333;
background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
...
}
Nevertheless, I would appreciate any suggestions, when to bother and when not to - as well as any other on-topic hints how to proceed as long as selector inheritance is not an option.
A: I think there are a few issues to consider:
*
*Size of the style sheet
*Efficiency of style sheet execution (how fast the browser executes)
*Maintainability of the style sheet
*Maintainability of the markup (html)
The approach that Mark Gemmill advocates (in /3) is really Nicole Sullivan's Object Oriented CSS. I used that pattern before switching to Sass, and still find some of it useful, but I think the Sass/Less way results in more maintainable CSS and more maintainable markup - there is no need to sprinkle presentational classes throughout the markup.
I think @extend (selector inheritance) is one of the main advantages that Sass has over Less and does reduce the redundancy in the compiled style sheet.
To me, the benefits of more maintainable CSS and markup outweigh any downside of a slightly larger style sheet. I think you'll find that if you keep your selectors efficient (don't nest in Less/Sass more than you need to) and combine and minimize in production the performance hit will be less than you might imagine.
A: You can define your mixin, and then pass in variables that you want to override when you call it.
This is an example form the less website:
.box-shadow (@x: 0, @y: 0, @blur: 1px, @alpha) {
@val: @x @y @blur rgba(0, 0, 0, @alpha);
box-shadow: @val;
-webkit-box-shadow: @val;
-moz-box-shadow: @val;
}
So when you call it you could do something like
div.header {
.box-shadow(5px,5px,2px,.5);
}
This way you can have 1 mixin, but each time you call it, you can pass it different attributes.
Hope this helps.
A: I recently started using less css as well, and this exact question came to mind as well. My response was:
1/ The actual generated css is kind of besides the point as you are never likely to be looking at it (except perhaps to debug your less code), so if there is some redundancy in the output that's a trade off you get with what I think is a syntax that is much better to understand and maintain.
2/ The disadvantage is, as you've described, if you pass in those less css class style around as a mixin you are bloating the size of your css output. If you are using less css on the front end, and it's generating the css in the browser this isn't a worry. However, if you are pre-generating your css, then it becomes a question of how that bloat effects download times. Unless your css file becomes huge as a result, and/or your site is doing very high volume, I wouldn't worry about it.
3/ An alternative to passing a class style around as a mixin (or using selector inheritance) in your less css is to just use class inheritance in your html, so rather than this in your less file:
.gradientBlack {
...
}
h3 {
.gradientBlack;
...
}
.darkBox {
.gradientBlack;
...
}
td.dark {
.gradientBlack;
...
}
You just define .gradientBlack in your style sheet and then reference the class directly in the html:
<h3 class="gradientBlack"></h3>
<div class="darkBox gradientBlack></div>
<td class="dark gradientBlack"></td>
I think in the end, aside from a question of download time, the bottom line is what makes your code easier to understand and maintain in your given situation. I rather have 100 more lines in my generated css if it makes my less css easier to comprehend.
A: What about something like this?
h3, .darkBox, td.dark {
.gradientBlack;
}
h3, {
/*other styles here*/
}
.darkBox {
/*other styles here*/
}
td.dark {
/*other styles here*/
}
Alternatively you could consider using a CSS minifier and see if that gives you an acceptable size without compromising the cleanliness of your LESS file.
A: I'm using lessphp (which may be different than less.js in this example) but I've noticed that if I declare the mixin as though it had an empty parameter list it will never generate a style block.
So change this:
.gradientBlack {
background: #333333;
background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5a5a5a), color-stop(60%, #333333), color-stop(100%, #000000));
background: -webkit-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -o-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -ms-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#5a5a5a', endColorstr='#000000', GradientType=0 );
background: linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
}
To this:
.gradientBlack() {
background: #333333;
background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5a5a5a), color-stop(60%, #333333), color-stop(100%, #000000));
background: -webkit-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -o-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
background: -ms-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#5a5a5a', endColorstr='#000000', GradientType=0 );
background: linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
}
and use it like this:
h3 {
.gradientBlack();
...
}
.darkBox {
.gradientBlack();
...
}
and it won't generate the unused block.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Padding-Right or Padding-Left problem when direction change between RTL and LTR in a table I'm developing a project in two languages (RTL and LTR) so when I design my tables some TDs must have right or left padding and I when I changes page direction to other, left padding means right and vies-versa and it is my problem because I shoud design my table once for RTl and once for LTR.
My problem:
LTR RTL
| Hello| ----> | سلام|
that correct design:
| Hello| ----> |سلام |
Thanks
A: If I understand the question correctly, I think you have two options.
One. create classes for specific directional text and style accordingly. So
<td class="rtl"></td>
and the css
td.rtl{
direction:rtl;
padding-left:20px; //OR WHATEVER
}
And then the opposite for ltr
Two. set the padding one way. Then use jQuery to detect the direction and adjust accordingly.
So something like
$('td').each(function(){
if($(this).css('direction') == 'rtl'){
$(this).css({'padding-left':'//whatver','padding-right':'0'});
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Run an rspec "before" block before rails initializers run I would like to run an rspec before block to set some stuff up before the Rails initializers run, so I can test what an initializer should be doing. Is this possible?
A: If the logic in your initializers is complex enough it should be tested, you should extract it into a helper that you can isolate and test without being in the context of the initializer.
complex_initializer.rb
config.database.foo = calculate_hard_stuff()
config.database.bar = other_stuff()
You could extract that into a testable helper (lib/config/database.rb)
module Config::DatabaseHelper
def self.generate_config
{:foo => calculate_hard_stuff, :bar => other_stuff)
end
def calculate_hard_stuff
# Hard stuff here
end
end
...then just wire up the configuration data in your initializer
db_config_values = Config::DatabaseHelper.generate_config
config.database.foo = db_config_values[:foo]
config.database.bar = db_config_values[:bar]
...and test the complex configuration determination/calculation in a separate test where you can isolate the inputs.
describe Config::DatabaseHelper do
describe '.calculate_hard_stuff' do
SystemValue.stubs(:config => value)
Config::DatabaseHelper.calculate_hard_stuff.should == expected_value
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7557636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.