Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've got a potentially rather large list of objects I'd like to bind to a ListBox in WPF. However, I'd like to have the List load itself incrementally. How can I bind a ListBox to an IEnumerable that loads itself on-demand in such a way that the listbox only tries to enumerate as much as it needs for the display?
WPF ListBox's use a [VirtualizingStackPanel](http://msdn.microsoft.com/en-us/library/system.windows.controls.virtualizingstackpanel.aspx) as the layout control for its items. You can set the VirtualizingStackPanel to only load items as needed with the following XAML: ``` <ListBox VirtualizingStackPanel.IsVirtualizing="True" ItemSource="..." /> ```
You could store the list in a database - maybe an in-memory one - and then retrieve the needed chunk in your IEnumerable using LINQ.
On-demand IEnumerable binding to ListBox
[ "", "c#", "wpf", "data-binding", "" ]
My schema specifies a namespace, but the documents don't. What's the simplest way to ignore namespace during JAXB unmarshalling (XML -> object)? In other words, I have ``` <foo><bar></bar></foo> ``` instead of, ``` <foo xmlns="http://tempuri.org/"><bar></bar></foo> ```
I believe you must [add the namespace](https://download.oracle.com/javaee-archive/jaxb.java.net/users/2008/05/7860.html) to your xml document, with, for example, the use of a [SAX filter](https://web.archive.org/web/20090113211510/http://www.digitalkarate.net/?p=63). That means: * Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them. * Define a XMLReader which will set the content handler then link the two together: ``` public static Object unmarshallWithFilter(Unmarshaller unmarshaller, java.io.File source) throws FileNotFoundException, JAXBException { FileReader fr = null; try { fr = new FileReader(source); XMLReader reader = new NamespaceFilterXMLReader(); InputSource is = new InputSource(fr); SAXSource ss = new SAXSource(reader, is); return unmarshaller.unmarshal(ss); } catch (SAXException e) { //not technically a jaxb exception, but close enough throw new JAXBException(e); } catch (ParserConfigurationException e) { //not technically a jaxb exception, but close enough throw new JAXBException(e); } finally { FileUtil.close(fr); //replace with this some safe close method you have } } ```
Here is an extension/edit of VonCs solution just in case someone doesn´t want to go through the hassle of implementing their own filter to do this. It also shows how to output a JAXB element without the namespace present. This is all accomplished using a SAX Filter. Filter implementation: ``` import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.XMLFilterImpl; public class NamespaceFilter extends XMLFilterImpl { private String usedNamespaceUri; private boolean addNamespace; //State variable private boolean addedNamespace = false; public NamespaceFilter(String namespaceUri, boolean addNamespace) { super(); if (addNamespace) this.usedNamespaceUri = namespaceUri; else this.usedNamespaceUri = ""; this.addNamespace = addNamespace; } @Override public void startDocument() throws SAXException { super.startDocument(); if (addNamespace) { startControlledPrefixMapping(); } } @Override public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException { super.startElement(this.usedNamespaceUri, arg1, arg2, arg3); } @Override public void endElement(String arg0, String arg1, String arg2) throws SAXException { super.endElement(this.usedNamespaceUri, arg1, arg2); } @Override public void startPrefixMapping(String prefix, String url) throws SAXException { if (addNamespace) { this.startControlledPrefixMapping(); } else { //Remove the namespace, i.e. don´t call startPrefixMapping for parent! } } private void startControlledPrefixMapping() throws SAXException { if (this.addNamespace && !this.addedNamespace) { //We should add namespace since it is set and has not yet been done. super.startPrefixMapping("", this.usedNamespaceUri); //Make sure we dont do it twice this.addedNamespace = true; } } } ``` This filter is designed to both be able to add the namespace if it is not present: ``` new NamespaceFilter("http://www.example.com/namespaceurl", true); ``` and to remove any present namespace: ``` new NamespaceFilter(null, false); ``` The filter can be used during parsing as follows: ``` //Prepare JAXB objects JAXBContext jc = JAXBContext.newInstance("jaxb.package"); Unmarshaller u = jc.createUnmarshaller(); //Create an XMLReader to use with our filter XMLReader reader = XMLReaderFactory.createXMLReader(); //Create the filter (to add namespace) and set the xmlReader as its parent. NamespaceFilter inFilter = new NamespaceFilter("http://www.example.com/namespaceurl", true); inFilter.setParent(reader); //Prepare the input, in this case a java.io.File (output) InputSource is = new InputSource(new FileInputStream(output)); //Create a SAXSource specifying the filter SAXSource source = new SAXSource(inFilter, is); //Do unmarshalling Object myJaxbObject = u.unmarshal(source); ``` To use this filter to output XML from a JAXB object, have a look at the code below. ``` //Prepare JAXB objects JAXBContext jc = JAXBContext.newInstance("jaxb.package"); Marshaller m = jc.createMarshaller(); //Define an output file File output = new File("test.xml"); //Create a filter that will remove the xmlns attribute NamespaceFilter outFilter = new NamespaceFilter(null, false); //Do some formatting, this is obviously optional and may effect performance OutputFormat format = new OutputFormat(); format.setIndent(true); format.setNewlines(true); //Create a new org.dom4j.io.XMLWriter that will serve as the //ContentHandler for our filter. XMLWriter writer = new XMLWriter(new FileOutputStream(output), format); //Attach the writer to the filter outFilter.setContentHandler(writer); //Tell JAXB to marshall to the filter which in turn will call the writer m.marshal(myJaxbObject, outFilter); ``` This will hopefully help someone since I spent a day doing this and almost gave up twice ;)
JAXB: How to ignore namespace during unmarshalling XML document?
[ "", "java", "xml", "xml-serialization", "jaxb", "" ]
I am fetching an array of floats from my database but the array I get has converted the values to strings. How can I convert them into floats again without looping through the array? Alternatively, how can I fetch the values from the database without converting them to strings? --- ### EDIT: * I am using the Zend Framework and I am using PDO\_mysql. The values are stored one per column and that is a requirement so I can't serialize them. * `array_map('floatval', $array)` only works on single dimensional arrays. * I can't `floatval` the single elements when I use them because I have to pass an array to my flash chart. * The momentary, non-generic solution is to extract the rows and do `array_map('floatval',$array)` with each row.
You could use ``` $floats = array_map('floatval', $nonFloats); ``` There is the option `PDO::ATTR_STRINGIFY_FETCHES` but from what I remember, MySQL always has it as `true` Edit: see [Bug 44341](http://bugs.php.net/bug.php?id=44341) which confirms MySQL doesn't support turning off stringify. Edit: you can also map a custom function like this: ``` function toFloats($array) { return array_map('floatval', $array); } $data = array_map('toFloats', $my2DArray); ```
How are you getting your data? mysql, mysqli or PDO, some other way or even some other database? you could use `array_map` with `floatval` like so: `$data = array_map('floatval', $data);` but that still executes a loop and i think it assumes you only have one column in your data. you're probably best of casting to float when you use your value, if you have to. php is likely to do a good job of interpreting it right anyway.
How can I convert all values of an array to floats in PHP?
[ "", "php", "" ]
There is `ConnectionManager` which waits for incoming connections. For each incoming connection it creates a `Connection` instance which handles the inbound and outbound traffic on this connection. Each `Connection` has a `Watchdog` which handles "bad connection" conditions and calls registered "Listerners". One "Listener" is the `ConnectionManager` which closes the connection and deletes the `Connection` instance which in turn deletes the corresponding Watchdog. Wait. A. Minute. The `Watchdog` calls the `ConnectionManager` which deletes the `Connection` which deletes the `Watchdog`? The Watchdog chases its own tail. I am completly blocked. How do I resolve this? --- **Solution**: I will make the Listener thingy asynchronous, altough I don't know yet how to do that without too much pain. The `Watchdog` doesn't know about the `ConnectionManager`. It is fairly generic. Also the Win32-Thread-API doesn't have something like "join", so I might need to roll my own with `GetExitCodeThread()` and `STILL_ACTIVE`... Thanks, guys.
If the watchdog is running in a different thread, then the problem isn't too bad - the watchdog signals the ConnectionManager to delete with a asynchronous message, then exits it's own thread. Mean-while, the ConnectionManager thread gets the delete message, and starts deleting the watchdog. To avoid race-conditions the watchdog destructor should join the watchdog thread, and cleanup the thread. (Probably also signal the watchdog thread, or assert() something about the watchdog thread being ready to exit).
Messaging. Instead of having the Watchdog call a method of the `ConnectionManager`, post a message to a queue in the connection manager. This queue needs to be thread safe. When the `ConnectionManager` processes the queue in its thread, it will be safe to wait for the Connection thread to end. ``` Watchdog Queue ConnectionManager | | | Kill Connection---->| | | |<-------------------Get Message --- | | |-------------------->Process Message | | | Kill Connection ```
Threading issue (chase your own tail)
[ "", "c++", "multithreading", "" ]
Fun with enums in C#. Take one generic list that is created to store some Enum that you had defined previously and add few items in it. Iterate with foreach or `GetEnumerator<T>()` but specify some other enum then the original and see what happens. I was expecting InvalidCastException or something like that but it perfectly works :). For the illustration let's take a simple console application and create two enums there: Cars and Animals: ``` public enum Cars { Honda = 0, Toyota = 1, Chevrolet = 2 } public enum Animals { Dog = 0, Cat = 1, Tiger = 2 } ``` And do this in main method: ``` public static void Main() { List<Cars> cars = new List<Cars>(); List<Animals> animals = new List<Animals>(); cars.Add(Cars.Chevrolet); cars.Add(Cars.Honda); cars.Add(Cars.Toyota); foreach (Animals isItACar in cars) { Console.WriteLine(isItACar.ToString()); } Console.ReadLine(); } ``` It will print this in console: > ``` > Tiger > Dog > Cat > ``` Why is this happening? My first guess was that enum is not actually a Type by himself it's just and int but that's not true: If we write: `Console.WriteLine(Animals.Tiger.GetType().FullName);` We will get his fully qualified name printed! So why this?
Enum types are distinct, but you're being confused by an implicit cast which is in foreach. Let's rewrite your loop a bit: ``` public static void Main() { List<Cars> cars = new List<Cars>(); List<Animals> animals = new List<Animals>(); cars.Add(Cars.Chevrolet); cars.Add(Cars.Honda); cars.Add(Cars.Toyota); foreach (Cars value in cars) { // This time the cast is explicit. Animals isItACar = (Animals) value; Console.WriteLine(isItACar.ToString()); } Console.ReadLine(); } ``` Now does the result surprise you? Hopefully not, except possibly the fact that you *can* cast from one enum to another. This is just a more explicit version of what your original code is doing. The fact that there's a cast implicit in every `foreach` loop (even though it's usually a no-op) is the bit which most developers would find confusing, I think. From section 8.8.4 of the C# 3.0 spec: > The above steps, if successful, > unambiguously produce a collection > type C, enumerator type E and element > type T. A foreach statement of the > form ``` foreach (V v in x) embedded-statement ``` > is then expanded to: ``` { E e = ((C)(x)).GetEnumerator(); try { V v; while (e.MoveNext()) { v = (V)(T)e.Current; embedded-statement } } finally { ... // Dispose e } } ``` The enumeration conversion itself is covered in section 6.2.2: > The explicit enumeration conversions > are: * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal to any enum-type. * From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal. * From any enum-type to any other enum-type. > An explicit enumeration conversion > between two types is processed by > treating any participating enum-type > as the underlying type of that > enum-type, and then performing an > implicit or explicit numeric > conversion between the resulting > types. For example, given an enum-type > E with and underlying type of int, a > conversion from E to byte is processed > as an explicit numeric conversion > (§6.2.1) from int to byte, and a > conversion from byte to E is processed > as an implicit numeric conversion > (§6.1.2) from byte to int.
Conceptually, an Enum is a statically-typed value with a string representation and a number. When you call `ToString()` on an enum, it will return the string representation. When you call `GetType()` on an enum, you'll get the static enumeration type. If you cast an enum to `int`, you'll get the integer value for the enum. Enums are supposed to be strongly-typed but there are some things you need to be aware of, like the fact that any integer can be cast to any enum even if it doesn't have a corresponding declaration (in which case the string representation will be the same as the number's). In the CLR, enums (like `bool`s) are just treated as `int`s but if you called GetType() or GetString() it calls the versions that do what was described above.
Are enums only named integers, types or neither of both?
[ "", "c#", "enums", "" ]
I am working on [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) currently and have gotten stuck. My code doesn't work. When I run my code in GUI, it says: ``` [[0 0 0 0] [0 1 1 0] [0 1 0 0] [0 0 0 0]] Traceback (most recent call last): File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 53, in b= apply_rules(a) File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 14, in apply_rules neighbours=number_neighbours(universe_array,iy,ix) File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 36, in number_neighbours neighbours+=1 UnboundLocalError: local variable 'neighbours' referenced before assignment ``` Here is my code: ``` '''If a cell is dead at time T with exactly three live neighbours, the cell will be alive at T+1 If a cell is alive at time T with less than two living neighbours it dies at T+1 If a cell is alive at time T with more than three live neighbours it dies at T+1 If a cell is alive at time T with exactly two or three live neighbours it remains alive at T+1''' import numpy def apply_rules (universe_array): height, width = universe_array.shape # create a new array for t+1 evolved_array = numpy.zeros((height, width),numpy.uint8) for iy in range(1, height-1): for ix in range(1,width-1): neighbours=number_neighbours(universe_array,iy,ix) if universe_array[iy,ix]==0 and neighbours==3: evolved_array[iy,ix]==1 elif universe_array[iy,ix]==1 and neighbours<2: evolved_array[iy,ix]==0 elif universe_array[iy,ix]==1 and neighbours>3: evolved_array[iy,ix]==0 elif universe_array[iy,ix]==1 and neighbours==2 or neighbours==3: evolved_array[iy,ix]=universe_array[iy,ix] return evolved_array def number_neighbours(universe_array,iy,ix): neighbours=0 #fixed this line,thanks:) if universe_array[iy-1,ix-1]==1: neighbours+=1 if universe_array[iy,ix-1]==1: neighbours+=1 if universe_array[iy+1,ix-1]==1: neighbours+=1 if universe_array[iy-1,ix]==1: neighbours+=1 if universe_array[iy+1,ix]==1: neighbours+=1 if universe_array[iy-1,ix+1]==1: neighbours+=1 if universe_array[iy,ix+1]==1: neighbours+=1 if universe_array[iy+1,ix+1]==1: neighbours+=1 else: neighbours=neighbours return neighbours if __name__ == "__main__": a = numpy.zeros((4,4),numpy.uint8) a[1,1]=1 a[1,2]=1 a[2,1]=1 print a b= apply_rules(a) print b ``` I am a beginner at Python, and I don't know how to fix the error. I am a little bit confused about `import "neighbours"` to `function "apply_rules"`, is that right way to do this?
Well, I guess that you are also quite new to programming *per se*, otherwise you should not have any problems in interpreting that simple error message. I'll help you dissect it: * First, all "current" line numbers of your project's files are displayed, in calling order. * Then, it shows you the function in which the error occured: `number_neighbours` * Then, it shows you the contents of the line that contains the error: `neighbours+=1` * Finally, it tells you what the problem with that line is: `UnboundLocalError: local variable 'neighbours' referenced before assignment` Now, what does that mean? Let's see what the `+=` operator does: it adds something to the current value of `neighbours`. That means that it reads the current value, adds something to it, and finally stores it back. "Reading" is called "reference" with respect to variables. What is the current value of `neighbours`? Well, it has never been used before, so it doesn't have any value -- there has never been a value assigned to it. Adding something to 'no value' is not a sensible thing to do. I guess that you expect it to have the value 0, but you have to tell it to your interpreter. To do this, add the following statement before, at the start of your function: `neighbours = 0`
You're trying to increment a variable that doesn't exist yet. Python can't increment something if it doesn't know what is. Try adding the following line at the top of your def number\_neighbours function. ``` neighbours = 0 ```
Problem with Python implementation of Conway's Game of Life
[ "", "python", "" ]
I have a database with two main tables `notes` and `labels`. They have a many-to-many relationship (similar to how stackoverflow.com has questions with labels). What I am wondering is how can I search for a note using multiple labels using SQL? For example if I have a note "test" with three labels "one", "two", and "three" and I have a second note "test2" with labels "one" and "two" what is the SQL query that will find all the notes that are associated with labels "one" and "two"?
To obtain the details of notes that have **both** labels 'One' and 'Two': ``` select * from notes where note_id in ( select note_id from labels where label = 'One' intersect select note_id from labels where label = 'Two' ) ```
``` select * from notes a inner join notes_labels mm on (mm.note = a.id and mm.labeltext in ('one', 'two') ) ``` Of course, replace with your actual column names, hopefully my assumptions about your table were correct. And actually there's a bit of possible ambiguity in your question thanks to English and how the word 'and' is sometimes used. If you mean you want to see, for example, a note tagged 'one' but not 'two', this should work (interpreting your 'and' to mean, 'show me all the notes with label 'one' and/plus all the notes with label 'two'). However, if you only want notes that have both labels, this would be one way to go about it: ``` select * from notes a where exists (select 1 from notes_labels b where b.note = a.id and b.labeltext = 'one') and exists (select 1 from notes_labels c where c.note = a.id and c.labeltext = 'two') ``` Edit: thanks for the suggestions everyone, the Monday gears in my brain are a bit slow...looks like I should've wiki'd it!
SQL how to search a many to many relationship
[ "", "sql", "search", "many-to-many", "relational-division", "" ]
If I have an inner class, like this: ``` public class Test { public class Inner { // code ... } public static void main(String[] args) { // code ... } } ``` When I compile it, I expect it should generate two files: ``` Test.class Test$Inner.class ``` So why do I sometimes see classfiles like SomeClass$1.class, even though SomeClass does not contain an inner class called "1"?
The SomeClass$1.class represent anonymous inner class hava a look at the anonymous inner class section [here](http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html)
You'll also get something like `SomeClass$1.class` if your class contains a private inner class (not anonymous) but you instantiate it at some point in the parent class. For example: ``` public class Person { private class Brain{ void ponderLife() { System.out.println("The meaning of life is..."); } } Person() { Brain b = new Brain(); b.ponderLife(); } } ``` This would yield: ``` Person.class Person$Brain.class Person$1.class ``` Personally I think that's a bit easier to read than a typical anonymous class especially when implementing a simple interface or an abstract class that only serves to be passed into another local object.
Why does Java code with an inner class generates a third SomeClass$1.class file?
[ "", "java", "compiler-construction", "" ]
I have a vector-like class that contains an array of objects of type `"T"`, and I want to implement 4 arithmetic operators, which will apply the operation on each item: ``` // Constructors and other functions are omitted for brevity. template<class T, unsigned int D> class Vector { public: // Add a value to each item: naive implementation. void operator += (const T&) { for (int i = 0; i < D; ++i) { data[i] += value; } } void operator -= (const T&) { ... } void operator *= (const T&) { ... } void operator /= (const T&) { ... } private: T items[D]; }; ``` Because operators will contain the same boilerplate code (looping over every element and applying appropriate operation), I thought I could generalize it: ``` template<class T, unsigned int D> class Vector { public: void operator += (const T& value) { do_for_each(???, value); } void operator -= (const T& value) { do_for_each(???, value); } void operator *= (const T& value) { do_for_each(???, value); } void operator /= (const T& value) { do_for_each(???, value); } private: void do_for_each(std::binary_function<void, T, T>& op, T value) { std::for_each(data, data + D, std::bind2nd(op, value)); } T data[D]; }; ``` Now, the problem is, how do I pass an operator that takes two intrinsic types and returns `void` to `do_for_each`, as depicted in the example above? C++ does not let me do this trick for intrinsic types (`"T::operator+="` will not work if `"T"` is `"int"`).
First, you should really return a reference from your operator+=, since you can later use them to implement operator+, operator- and so on. I will change that accordingly. Also, your do\_for\_each has to be a template, since it has to know the precise type of the function object, as binary function objects are not polymorph classes. For the actual operation, you want to use `std::transform`: ``` template<class T, unsigned int D> class Vector { public: Vector& operator += (const T& value) { do_for_each(std::plus<T>(), value); return *this; } Vector& operator -= (const T& value) { do_for_each(std::minus<T>(), value); return *this; } Vector& operator *= (const T& value) { do_for_each(std::multiplies<T>(), value); return *this; } Vector& operator /= (const T& value) { do_for_each(std::divides<T>(), value); return *this; } private: template<typename BinFun> void do_for_each(BinFun op, const T& value) { std::transform(data, data + D, data, std::bind2nd(op, value)); } T data[D]; }; ``` [std::transform](http://www.sgi.com/tech/stl/transform.html) will just pass each element to the function object, and assigns the result back to the iterator given as the third argument.
You should really have a look at [Boost Operators](http://www.boost.org/doc/libs/1_37_0/libs/utility/operators.htm), a header-only library that really simplifies creating orthogonal and consistent arithmetic operator overloads. Specifically: you might find that deriving from `boost::operators::integer_arithmatic<T>` saves you a lot of the repetition of this class.
C++: Using operator of two intrinsic types as a function object
[ "", "c++", "templates", "functional-programming", "" ]
I developed a greasemonkey script that refreshes a page and checks for certain updates. I would like to run this script in a tab and browse the internet in another tab, but then have the script automatically activate it's tab when an update is found. Im not sure how clear that was, maybe this is better: Tab 1 is running a greasemonkey script, refreshing every x seconds looking for the word "foo" Tab 2 is browsing stackoverflow -- Now on a refresh, the GM script finds the word "foo". This is when I want the tab focus to automatically shift from Tab 2 to Tab 1. Is this possible, and if so, how do I achieve this? Thanks.
I'm pretty sure that firefox gives focus to tabs that call `alert()`. So just pop up an `alert('found foo')`
You can achieve this with [Scriptish](https://addons.mozilla.org/en-US/firefox/addon/scriptish/)'s [`GM_openInTab`](https://github.com/erikvold/scriptish/wiki/GM_openInTab) implementation, like so: ``` GM_openInTab(window.location.href, true); ``` That should cause the page that a GM script is on to be focused.
Activate Firefox tab in Greasemonkey/Javascript? Is this possible?
[ "", "javascript", "firefox", "tabs", "greasemonkey", "" ]
Assume I allow the user to input a arbitrary numerical expression that allows usage of the explicit set of functions and predefined variables. Interpreting this is pretty straight forward but what if performance is a critical factor? I need a way to compile (in runtime) a string with a expression into something that can be executed 20K times with different values on the variables.
So really you want to parse the string into (eventually) a typed delegate. One option, then it to parse the string into an `Expression`, which you can then compile to a lambda. This is quite complex, but I have some code that will do much of this - but there may be existing parsers that already do the job in full. As a trivial `Expression` example: ``` var x = Expression.Parameter(typeof(double), "x"); var y = Expression.Parameter(typeof(double), "y"); var body = Expression.Multiply(x, y); var func = Expression.Lambda<Func<double, double,double>>(body, x, y).Compile(); double z = func(123.45, 678.90); ``` The problem is the rest of the parsing code ;-p I wrote a `string` to `Expression` parser last week, but it is more code than I'd normally post here... over 300 lines (not including recognition of bespoke external functions, or named arguments (it currently uses anonymous "?" place-holders)). but if (as you say) interpreting is easy, then perhaps use similar code to write an `Expression` that you can compile?
Linq Samples by Microsoft already contain implementation of extensible Linq parser. ``` sealed class Order { public double SubTotal { get; set; } public double Shipping { get; set; } } static void Main() { var calculateTotal = DynamicExpression .ParseLambda<Order, double>("SubTotal*@0+Shipping", 0.12) .Compile(); var order = new Order { SubTotal = 124.99, Shipping = 7.99 }; Console.WriteLine(calculateTotal(order)); Console.ReadLine(); } ``` You can check out the [DbLinq project](http://code.google.com/p/dblinq2007/) for sources or this post for more details: [Dynamic Linq and Expression Parsing in .NET as a hint of C# compiler extensibility](http://rabdullin.com/journal/2008/12/7/dynamic-linq-and-expression-parsing-in-net-as-a-hint-of-c-co.html)
C# compile numerical expression
[ "", "c#", "compilation", "" ]
What exactly do `*args` and `**kwargs` mean? According to the Python documentation, from what it seems, it passes in a tuple of arguments. ``` def foo(hello, *args): print(hello) for each in args: print(each) if __name__ == '__main__': foo("LOVE", ["lol", "lololol"]) ``` This prints out: ``` LOVE ['lol', 'lololol'] ``` How do you effectively use them?
Putting `*args` and/or `**kwargs` as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments. For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this: ``` def my_sum(*args): return sum(args) ``` It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in. You don’t actually have to call them `args` and `kwargs`, that’s just a convention. It’s the `*` and `**` that do the magic. The official Python documentation has [a more in-depth look](http://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions).
Also, we use them for managing inheritance. ``` class Super( object ): def __init__( self, this, that ): self.this = this self.that = that class Sub( Super ): def __init__( self, myStuff, *args, **kw ): super( Sub, self ).__init__( *args, **kw ) self.myStuff= myStuff x= Super( 2.7, 3.1 ) y= Sub( "green", 7, 6 ) ``` This way Sub doesn't really know (or care) what the superclass initialization is. Should you realize that you need to change the superclass, you can fix things without having to sweat the details in each subclass.
What do *args and **kwargs mean?
[ "", "python", "" ]
Let's say I have some pointers called: ``` char * pChar; int * pInt; ``` I know they both simply hold memory addresses that point to some other location, and that the types declare how big the memory location is pointed to by the particular pointer. So for example, a char might be the size of a byte on a system, while an int may be 4 bytes.. So when I do: ``` pChar++; // I am actually incrementing the address pointed to by pChar by 1 byte; pInt++; // I am actually incrementing the address pointed to by pInt by 4 bytes; ``` But what if I do this: ``` pChar+2; // increment the address pointed to by pChar by 2 bytes? pInt+2; // increment the address pointed to by pInt by 2 bytes? what happens to the other two bytes? ``` Thanks.. Would appreciate any clarification here.. Is the pointer type simply for the ++ operation? EDIT: So avp answered my question fittingly, but I have a follow up question, what happens when I do: ``` memcpy(pChar,pInt,2); ``` Will it copy 2 bytes? or 4 bytes? Will I have an access violation? EDIT: THe answer, according to Ryan Fox, is 2 bytes, because they are typecasted to a (void\*). Thanks! CLOSED! EDIT: Just so that future searchers may find this.. Another piece of info I discovered.. ``` memcpy(pChar+5,pInt+5,2); ``` doesnt copy 2 bytes of the memory block pointed to by pInt+5bytelocations,to pChar+5bytelocations.. what happens is that 2 bytes are copied to pChar+5bytelocations from pInt(4\*5)bytelocations.. no wonder I got access violations, I was trying to read off somewhere I wasn't supposed to be reading.. :)
"++" is just another name for X = X + 1; For pointers it doesn't matter if you increment by 1 or by N. Anyway, sizeof(type)\*N is used. In the case of 1 it will be just sizeof(type). So, when you increment by 2 (your second case): for char is 2\*sizeof(char)=2\*1=2 bytes, for int will be 2\*sizeof(int)=2\*4=8 bytes.
Ahh, now I understand. You should have asked - **"What is the point of pointers having types?"** There are two points, actually: * Pointer arithmetics; * Dereferencing (getting the value back that is stored in the address that the pointer is pointing to). Both would be impossible without knowing the type of the pointer. **Added:** Read the documentation of memcpy. The last argument is number of bytes, because memcpy has no idea what the type of the pointer is. Both arguments to it are void pointers. **Added 2:** Access violation - it depends. If you aren't going outside of the memory that you have allocated for these pointers, there will be no access violation. The copy operation will copy everything byte-by-byte and you will get your results just like you expect them (although it might not make much sense). If you are going outside your allocated memory bounds then you **might** get an access violation, but you might as well just cross over into the memory that was allocated for another variable. It's pretty much impossible to tell what gets where when your program is executed, so doing this will lead to quite unpredictable results. --- ~~There are three main advantages of pointers:~~ 1. You can pass arguments to function "by reference". This used to be more of an issue in C, which didn't have real references like C++, but it's still very useful in many cases, like when you have to cooperate with external libraries. Also notice, that passing by reference is not only useful when you want the function to modify the variable you're passing. It's also very good for passing large data structures as parameters. 2. For building all kinds of nifty dynamic data structures like trees, linked lists, etc. This would be impossible without pointers. 3. For being able to re-allocate arrays to bigger/smaller ones as needed. P.S. I understand that the question was about why pointers are good, using the arithmetics only as an example, right?
What is the point of pointer types in C++?
[ "", "c++", "pointers", "memcpy", "" ]
Some websites have code to "break out" of `IFRAME` enclosures, meaning that if a page `A` is loaded as an `IFRAME` inside an parent page `P` some Javascript in `A` redirects the outer window to `A`. Typically this Javascript looks something like this: ``` <script type="text/javascript"> if (top.location.href != self.location.href) top.location.href = self.location.href; </script> ``` My question is: As the author of the parent page `P` and not being the author of the inner page `A`, how can I prevent `A` from doing this break-out? P.S. It seems to me like it ought to be a cross-site security violation, but it isn't.
Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page. Example: <https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload> In HTML5 you can use sandbox property. Please see Pankrat's answer below. <http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/>
With HTML5 the [iframe sandbox](http://www.w3schools.com/tags/att_iframe_sandbox.asp) attribute was added. At the time of writing this [works on Chrome, Safari, Firefox and recent versions of IE and Opera](http://caniuse.com/iframe-sandbox) but does pretty much what you want: ``` <iframe src="url" sandbox="allow-forms allow-scripts"></iframe> ``` If you want to *allow* top-level redirects specify `sandbox="allow-top-navigation"`.
How to prevent IFRAME from redirecting top-level window
[ "", "javascript", "html", "iframe", "" ]
Is there a C# port of the [optparse (command line option parser)](http://www.python.org/doc/2.5.2/lib/module-optparse.html) module from Python available under some [OSI-approved license](http://www.opensource.org/licenses/alphabetical)?
Have you already looked at <http://csharpoptparse.sourceforge.net/> ? I did not read the licensing, but since it it's on sourceforge, I would guess it is OSI approved.
CSharpOptParse homepage says it is a port of Perl's GetOpt, not of Python's optparse. Anyway, I looks terribly, unline the original optparse :/
C# version of optparse?
[ "", "c#", "command-line", "" ]
I found the [Computational Geometry Algorithms Library](http://www.cgal.org/) in my search for an algorithm to decompose a concave polygon into the minimum number of convex components. Links off the site and numerous google results indicate there are python bindings for it, which would be really handy, but all the links are dead! What happened to it? Where can I get it now?
A rewrite of the CGAL-Python bindings has been done as part of the cgal-bindings project. Check it out : <http://code.google.com/p/cgal-bindings/>
You may also be interested in the GEOS library, which is available in Python through [Shapely](https://github.com/Toblerity/Shapely) and [the GEOS API included in GeoDjango](http://geodjango.org/docs/geos.html).
What happened to the python bindings for CGAL?
[ "", "python", "geometry", "polygon", "computational-geometry", "cgal", "" ]
In Java (And in general) is there a way to make a class so public that it's methods etc... are accessible from little classes all around that don't even instantiate it? Ha, what I mean is... If I have a daddy class that has a method `draw()` and it instantiates a baby class called Hand and one called Deck, and then deck instantiates a babier class called Card that has a method `play()`, is there a way for `Play()` to then call `Draw()` from the daddy class? The idea here is that... the daddy class says "Deck! play(card)!" and then deck says "Card! play()!" and then play turns around and says "Hey daddy! Draw()!" PS the idea is that... in a CCG every card has a "play()" method that is different but they are all essentially called in the same way. The opportunity to play the card comes around, and you call play on it. But the card doesn't do anything internal to itself: no no, it calls a number of methods from the rules of the game, which is has visibility to. So, like, a card in MTG that says "draw one card. Deal one damage to target player." is calling draw(player, 1) and dealDamage(player, 1) which are presumably not in the card itself... since they effect variables presumably instantiated by the players when they started the game and agreed on life totals and rules such as what "draw" means? (meta-question: as usual, could someone please rename this question so that it reflects what I am asking... being a beginner is so frustrating!)
When the Daddy class instantiates the Baby classes, it (Daddy) could pass a reference to itself to the Baby constructor, giving Baby access to all of its public methods. ``` class Daddy { public foo(){...} public createBaby(){ Baby baby = new Baby(this); // baby now has a reference to Daddy } } class Baby { Daddy daddy; public Baby(Daddy daddy){ this.daddy = daddy; } ... public callDaddy(){ daddy.foo(); } } ```
You can: * Pass the object reference through the constructor. Or by getters and setters. Or directly to the function. * Use inheritance. * Use static classes.
method visibility between classes in java
[ "", "java", "visibility", "" ]
I'm trying to find an zip compression and encryption component with [encryption suitable for use by the US Federal Government](http://www.networkworld.com/careers/2004/0315manonline.html), so I can't use Zip 2.0 encryption, it has to be AES or the like. I've already found [SharpZipLib](http://www.icsharpcode.net/OpenSource/SharpZipLib/) (can't do AES encyrption), and [Chilkat](http://www.chilkatsoft.com/downloads.asp) (can do AES encryption, but costs money). Am I missing any other options?
How much would you be willing to pay for AES in DotNetZip? ;) DotNetZip supports AES Encryption, with 128 or 256-bit keys. <http://www.codeplex.com/DotNetZip> Example code: ``` using (ZipFile zip = new ZipFile()) { zip.AddFile("ReadMe.txt"); // no password for this entry // use a password for subsequent entries zip.Password= "This.Encryption.is.FIPS.197.Compliant!"; zip.Encryption= EncryptionAlgorithm.WinZipAes256; zip.AddFile("Rawdata-2008-12-18.csv"); zip.Save("Backup-AES-Encrypted.zip"); } ``` The AES-encrypted zip files produced by DotNetZip can be read and extracted by WinZip, and vice-versa. You can also just create regular zip files without encryption. oh, and it's free.
If money is a big issue, you could take an open source library like this <http://www.codeplex.com/DotNetZip>, which now has AES support
Suggestions for a cheap/free .NET library for doing Zip with AES encryption?
[ "", "c#", ".net", "vb.net", "encryption", "zip", "" ]
I'm using a streamwriter to log errors the way it has been designed (please dont ask why) is to open a new streamwriter everytime the application has to log a message. It outputs everything to ./Logs/[current-date].txt which usually resolves to "c:\myappfolder\logs[current-date].txt" Everything works correctly, but after I use an open file dialog to say, "C:\home\myfolder\myfile" the streamwriter tries to write to "c:\home\myfolder\logs[current-date].txt" I know solutions to this problem but i just dont understand what's going on
The current directory is a process wide value. The `OpenFileDialog` is changing the current directory. If you're using the .NET `OpenFileDialog` class, you can set the `RestoreDirectory` property to `true` to tell the dialog to leave the current directory alone (although the way the docs for `RestoreDirectory` is written there may be some threading issues, which I imagine might make this still inappropriate for a logging facility).
As Mike B said, `OpenFileDialog` may change current directory. Since `./` is relative to current, that changes too. The `RestoreDirectory` property modifies this behavior. Do something like this rather: ``` OpenFileDialog openFileDialog1 = new OpenFileDialog(); OpenFileDialog1.InitialDirectory = "c:\\" ; openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ; openFileDialog1.FilterIndex = 2 ; openFileDialog1.RestoreDirectory = true ; ``` Taken from [MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx).
./ changes target when i use OpenFileDialog
[ "", ".net", "c++", "relative-path", "openfiledialog", "" ]
I am not understanding the point of using .def files with DLLs. It seems that it replaces the need to use explicit exports within your DLL code (ie. explicit \_\_declspec(dllexport)) however I am unable to generate a lib file when not using these which then creates linker issues later when using the DLL. So how do you use .defs when linking with the client application, do they replace the need to use a header or .lib file?
My understanding is that .def files provide an alternative to the \_\_declspec(dllexport) syntax, with the additional benefit of being able to explicitly specify the ordinals of the exported functions. This can be useful if you export some functions only by ordinal, which doesn't reveal as much information about the function itself (eg: many of the OS internal DLL's export functions only by ordinal). See the [reference page](https://learn.microsoft.com/en-us/cpp/build/exporting-from-a-dll-using-def-files). Note that the names in the .def file must match the names in the binary. So if you using C or C++ with 'extern "C" { ... }', the names will not be mangled; otherwise you must use the correct mangled names for the specific version of the compiler used to generate the DLL. The \_\_declspec() function does this all automatically.
I find the use of both \_\_declspec(dllexport) and the .def file together to be useful in creating portable DLLs, i.e. DLLs that can be called from code compiled with a different compiler or with different compiler settings. Just putting \_\_declspec(dllexport) on your function declarations will cause those functions to be "exported" by your DLL (at least on Windows) so that they can be called from outside the DLL. However, adding to the build a .def file that lists all of your exported functions lets you stop Microsoft compilers (for example) from adding a leading underscore and trailing parameter-width information to the exported function name (at least when combined with the \_\_stdcall directive, also useful for portability). E.g. the function declaration ``` void foo(int i); ``` could end up being exported as "\_foo@4" if you aren't careful about calling convention and .def file usage. Keeping the exported function names in the symbol table free of such name-decoration comes in really handy when making GetProcAddress() calls as part of loading and hooking into a DLL explicitly at runtime. i.e. to get a pointer to the above function foo() (assuming it was exported at all) at runtime, you ideally just want to call: ``` HANDLE dllHandle = LoadLibrary("mydll.dll"); void* fooFcnPtr = GetProcAddress(dllHandle, "foo"); ``` With some appropriate error case checking of course! Use of a .def file plus \_\_stdcall, \_\_declspec(dllexport) and extern "C" on your function declarations when building your DLL will ensure that the above client-side code will work for a wide range of compilers and compiler settings.
.def files C/C++ DLLs
[ "", "c++", "c", "dll", "" ]
I'm working on a site now that have to fetch users feeds. But how can I best optimize fetching if I have a database with, lets say, 300 feeds. I'm going to set up a cron-job to which fetches the feeds, but should I do it like 5 every second minute or something? Any ideas on how to do this the best way in PHP?
Based on the new information I think I would do something like this: Let the "first" client initiate the updatework and store timestamp with it. Everey other clients that will ask for the information get a cashed information until that information are to old. Next hit from a client will then refresh the cashe that then will be used by all clients till next time its to old. The client that will actually initiate the updatework should not have to wait for it to finnish, just serv the old cashed version and continue to do it till the work is done. That way you dont have to update **anything** if no clients are requesting it.
If I understand you question, you are basically working on a feed agregator site? You can do the following; start by refreshing every 1 hor (for example). When you have anough entries from some feed - calculate the average interval between entries. Then use that interval as an interval for fetching that feed. For example, if the site published 7 articles in the last 7 days - you can fetch feeds from it every 24hours (1day). I use this algorithm with a few changes, when I calculate this average interval I divide it by 2 (to be sure not to fetch too rarely). If the result is less than 60 minutes - I set the interval to 1h or it is bigger than 24 I set it to 24h. For example, something like this: ``` public function updateRefreshInterval() { $sql = 'select count(*) _count ' . 'from article ' . 'where created>adddate(now(), interval -7 day) and feed_id = ' . (int) $this->getId(); $array = Db::loadArray( $sql ); $count = $array[ '_count' ]; $interval = 7 * 24 * 60 * 60 / ( $count + 1 ); $interval = $interval / 2; if( $interval < self::MIN_REFRESH_INTERVAL ) { $interval = self::MIN_REFRESH_INTERVAL; } if( $interval > self::MAX_REFRESH_INTERVAL ) { $interval = self::MAX_REFRESH_INTERVAL; } Db::execute( 'update feed set refresh_interval = ' . $interval . ' where id = ' . (int) $this->getId() ); } ``` The table is 'feed', 'refreshed' is the timestampt when the feed was last time refreshed and 'refresh\_interval' is the desired time interval between two fetches of the same feed.
Optimize feed fetching
[ "", "php", "mysql", "cron", "feed", "fetch", "" ]
Assume you have some objects which have several fields they can be compared by: ``` public class Person { private String firstName; private String lastName; private String age; /* Constructors */ /* Methods */ } ``` So in this example, when you ask if: ``` a.compareTo(b) > 0 ``` you might be asking if a's last name comes before b's, or if a is older than b, etc... What is the cleanest way to enable multiple comparison between these kinds of objects without adding unnecessary clutter or overhead? * `java.lang.Comparable` interface allows comparison by one field only * Adding numerous compare methods (i.e. `compareByFirstName()`, `compareByAge()`, etc...) is cluttered in my opinion. So what is the best way to go about this?
You can implement a `Comparator` which compares two `Person` objects, and you can examine as many of the fields as you like. You can put in a variable in your comparator that tells it which field to compare to, although it would probably be simpler to just write multiple comparators.
With Java 8: ``` Comparator.comparing((Person p)->p.firstName) .thenComparing(p->p.lastName) .thenComparingInt(p->p.age); ``` If you have accessor methods: ``` Comparator.comparing(Person::getFirstName) .thenComparing(Person::getLastName) .thenComparingInt(Person::getAge); ``` If a class implements Comparable then such comparator may be used in compareTo method: ``` @Override public int compareTo(Person o){ return Comparator.comparing(Person::getFirstName) .thenComparing(Person::getLastName) .thenComparingInt(Person::getAge) .compare(this, o); } ```
How to compare objects by multiple fields
[ "", "java", "oop", "" ]
Is there any way to find all references to an object while debugging?
If you're willing to dig into WinDbg it is fairly easy to find references to a specific object. However, WinDbg is not the easiest tool to use. This [blog](http://blogs.msdn.com/tess/) has lots of info on using WinDbg.
Not without using the profiling/debugger API, as far as I'm aware. (Even with the API, I don't know how to do it.)
Finding references to an object
[ "", "c#", "debugging", "" ]
Here's an example: ``` Double d = (1/3); System.out.println(d); ``` This returns 0, not 0.33333... as it should. Does anyone know?
That's because `1` and `3` are treated as `integers` when you don't specify otherwise, so `1/3` evaluates to the `integer` `0` which is then cast to the `double` `0`. To fix it, try `(1.0/3)`, or maybe `1D/3` to explicitly state that you're dealing with double values.
If you have `int`s that you want to divide using floating-point division, you'll have to cast the `int` to a `double`: ``` double d = (double)intValue1 / (double)intValue2 ``` (Actually, only casting `intValue2` should be enough to have the `intValue1` be casted to `double` automatically, I believe.)
Double value returns 0
[ "", "java", "division", "" ]
On a page I want to dynamically list years and all the months in each year so an archive for each month can be viewed. I want to show the current year first but the current year may not be over yet so I only want to show the months that have passed, and the current month. Then I want all years and all months in the past since this year (i.e. 2008). The PHP code I have created that does the job is below. Is there a more efficient way of achieving this? I am running PHP 5.2. ``` $current_year = date('Y'); $months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); // Loop through all the months and create an array up to and including the current month foreach ($months as $month) { if ($month <= date('m')) { switch ($month) { case 1: $years[$current_year][] = 'January'; break; case 2: $years[$current_year][] = 'February'; break; case 3: $years[$current_year][] = 'March'; break; case 4: $years[$current_year][] = 'April'; break; case 5: $years[$current_year][] = 'May'; break; case 6: $years[$current_year][] = 'June'; break; case 7: $years[$current_year][] = 'July'; break; case 8: $years[$current_year][] = 'August'; break; case 9: $years[$current_year][] = 'September'; break; case 10: $years[$current_year][] = 'October'; break; case 11: $years[$current_year][] = 'November'; break; case 12: $years[$current_year][] = 'December'; break; } } } // Previous years $years_to_create = $current_year - 2008; if (!empty($years_to_create)) { for ($i = 1; $i <= $years_to_create; $i++) { $years[$current_year - $i] = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); } } ```
``` $current_year = date('Y'); $months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); $month_names = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); // Loop through all the months and create an array up to and including the current month for ($month=1;$month<=date('m');$month++) { $years[$current_year][] = $month_names[$month-1]; } // Previous years $years_to_create = $current_year - 2008; if (!empty($years_to_create)) { for ($i = 1; $i <= $years_to_create; $i++) { $years[$current_year - $i] = $month_names; } } ``` This seems a little simpler...is it any faster...?
try this it will out put a descending list of months/years for the past 5 years ``` $years = 5; for ($i = 0; $i < (12* $years); $i++) { if (date('Y',strtotime("-".$i." month")) > (date('Y') - $years) ) { echo date('F Y',strtotime("-".$i." month")) . '<br />'; } } ``` Then if you need it in an array, just add to as you go like so ``` $years = 5; $myarray = array(); for ($i = 0; $i < (12* $years); $i++) { if (date('Y',strtotime("-".$i." month")) > (date('Y') - $years) ) { $year_key = date('Y') - date('Y',strtotime("-".$i." month")); $myarray[$year_key][] = date('F',strtotime("-".$i." month")); } } //Write it out to the screen foreach ($myarray as $yearkey=>$eachyear) { foreach ($eachyear as $eachmonth) { echo (date('Y')-$yearkey) . ' ' . $eachmonth . '<br>'; } } ```
Is there a more efficient way of creating a list of years/months?
[ "", "php", "language-agnostic", "datetime", "performance", "" ]
``` #include<iostream> using namespace std; class A { int a; int b; public: void eat() { cout<<"A::eat()"<<endl; } }; class B: public A { public: void eat() { cout<<"B::eat()"<<endl; } }; class C: public A { public: void eat() { cout<<"C::eat()"<<endl; } }; class D: public B, C { }; int foo(A *ptr) { ptr->eat(); } main() { D obj; foo(&(obj.B)); //error. How do i call with D's B part. } ``` The above foo call is a compile time error. I want to call foo with obj's B part without using virtual inheritance. How do i do that. Also, in case of virtual inheritance, why the offset information need to be stored in the vtable. This can be determined at the compile time itself. In the above case, if we pass foo with D's object, at compile time only we can calculate the offset of D's A part.
## Inheriting twice With double inheritance you have an ambiguity - the compiler cannot know which of the two A bases do you want to use. If you want to have two A bases (sometimes you may want to do this), you may select between them by casting to B or C. The most appropriate from default casts here is the `static_cast` (as the weakest available), however it is not realy needed (it is still stronger than your case needs), as you are not casting to a derived type. A custom `safe_cast` template should do the job: ``` /// cast using implicit conversions only template <class To,class From> inline To safe_cast( const From &from ) {return from;} main() { D obj; foo(safe_cast<B *>(&obj)); //error. How do i call with D's B part. } ``` ## Compile time types - use templates > Also, in case of virtual inheritance, > why the offset information need to be > stored in the vtable. This can be > determined at the compile time itself. > In the above case, if we pass foo with > D's object, at compile time only we > can calculate the offset of D's A > part. This is a misconception. The foo function as it is written now has no compile type information about ptr type other than it is A \*, even if you pass B \* or C\*. If you want foo to be able to act based on the type passed compile time, you need to use templates: ``` template <class TypeDerivedFromA> int foo(TypeDerivedFromA *ptr) { ptr->eat(); } ``` ## Virtual Inheritance Your questions mentions virtual inheritance. If you want to use virtual inheritance, you need to specify so: ``` class B: public virtual A ... class C: public virtual A ... ``` With this the code would compile, but with this solution there is no way you could select between B::A or C::A (there is only one A), therefore this is probably not what you are about. ## Virtual functions Furthermore, your questions seems to be confusing two different concepts, virtual inheritance (which means sharing one base class between two intermediate base classes) and virtual functions (which mean allowing derived class function to be called via base class pointer). If you want the B::eat to be called using A pointer, you can do this without virtual inheritance (actually virtual inheritance would prevent you doing so, as explained above), using virtual functions: ``` class A { int a; int b; public: virtual void eat() { cout<<"A::eat()"<<endl; } }; ``` If virtual functions are not acceptable for you, the compile time mechanism for this are templates, as explained above.
Use a cast - `static_cast` is required here to cast up the heirarchy. ``` main() { D obj; foo(static_cast<B*>(&obj)); } ```
Multiple Inheritance
[ "", "c++", "inheritance", "multiple-inheritance", "" ]
I'm using SQL Server 2008 Management studio viewing a 2005 server and have just added 2 users. For some reason they both have slightly different icons and I'm not sure why. Anyone have a definitive list of the icons and their meaning or a link to microsoft's doc on it as I can't find anything anywhere. Thanks.
One icon for user account, another icon is for group account.
If the user icon has a red down arrow, it means the associated login is disabled.
what do the sql server icons mean?
[ "", "sql", "sql-server-2005", "sql-server-2008", "icons", "" ]
I am looking for a way to localize properties names displayed in a PropertyGrid. The property's name may be "overriden" using the DisplayNameAttribute attribute. Unfortunately attributes can not have non constant expressions. So I can not use strongly typed resources such as: ``` class Foo { [DisplayAttribute(Resources.MyPropertyNameLocalized)] // do not compile string MyProperty {get; set;} } ``` I had a look around and found some suggestion to inherit from DisplayNameAttribute to be able to use resource. I would end up up with code like: ``` class Foo { [MyLocalizedDisplayAttribute("MyPropertyNameLocalized")] // not strongly typed string MyProperty {get; set;} } ``` However I lose strongly typed resource benefits which is definitely not a good thing. Then I came across [DisplayNameResourceAttribute](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.modeling.design.displaynameresourceattribute.aspx) which may be what I'm looking for. But it's supposed to be in Microsoft.VisualStudio.Modeling.Design namespace and I can't find what reference I am supposed to add for this namespace. Anybody know if there's a easier way to achieve DisplayName localization in a good way ? or if there is as way to use what Microsoft seems to be using for Visual Studio ?
Here is the solution I ended up with in a separate assembly (called "Common" in my case): ``` [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)] public class DisplayNameLocalizedAttribute : DisplayNameAttribute { public DisplayNameLocalizedAttribute(Type resourceManagerProvider, string resourceKey) : base(Utils.LookupResource(resourceManagerProvider, resourceKey)) { } } ``` with the code to look up the resource: ``` internal static string LookupResource(Type resourceManagerProvider, string resourceKey) { foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic)) { if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager)) { System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null); return resourceManager.GetString(resourceKey); } } return resourceKey; // Fallback with the key name } ``` Typical usage would be: ``` class Foo { [Common.DisplayNameLocalized(typeof(Resources.Resource), "CreationDateDisplayName"), Common.DescriptionLocalized(typeof(Resources.Resource), "CreationDateDescription")] public DateTime CreationDate { get; set; } } ``` What is pretty much ugly as I use literal strings for resource key. Using a constant there would mean to modify Resources.Designer.cs which is probably not a good idea. Conclusion: I am not happy with that, but I am even less happy about Microsoft who can't provide anything useful for such a common task.
There is the [Display attribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx) from System.ComponentModel.DataAnnotations in .NET 4. It works on the MVC 3 `PropertyGrid`. ``` [Display(ResourceType = typeof(MyResources), Name = "UserName")] public string UserName { get; set; } ``` This looks up a resource named `UserName` in your `MyResources.resx` file.
Localization of DisplayNameAttribute
[ "", "c#", "visual-studio-2008", "localization", "attributes", "" ]
I am doing something like this: ``` #include <signal.h> class myClass { public: void myFunction () { signal(SIGIO,myHandler); } void myHandler (int signum) { /** * Handling code */ } } ``` I am working on Ubuntu, using gcc. But it won't compile. It is complaining with: > error: the argument with type `void (MyClass::)(int)` doesn't agree with `void (*) (int)` Any clues? Or maybe it is just that I cannot use a signal inside classes? Are signals only allowed in C? The error message is an approximate translation because my compiler is not in English.
The second parameter of signal should be a pointer to a function accepting an int and returning void. What you're passing to signal is a pointer to a *member* function accepting an int and returning void (its type being `void (myClass::*)(int)`). I can see three possibilities to overcome this issue: 1 - Your method `myHandler` can be static: this is great, make it static ``` class myClass { public: void myFunction () { signal(SIGIO, myClass::myHandler); } static void myHandler (int signum) { // handling code } }; ``` 2 - Your method shouldn't be static: if you're planning to use signal with only one instance, you can create a private static object, and write a static method that simply call the method on this object. Something along the lines of ``` class myClass { public: void myFunction () { signal(SIGIO, myClass::static_myHandler); } void myHandler (int signum) { // handling code } static void static_myHandler(int signum) { instance.myHandler(signum); } private: static myClass instance; }; ``` 3 - However, if you're planning on using the signal with multiple instances, things will get more complicated. Perhaps a solution would be to store each instance you want to manipulate in a static vector, and invoking the method on each of these : ``` class myClass { public: void myFunction () // registers a handler { instances.push_back(this); } void myHandler (int signum) { // handling code } static void callHandlers (int signum) // calls the handlers { std::for_each(instances.begin(), instances.end(), std::bind2nd(std::mem_fun(&myClass::myHandler), signum)); } private: static std::vector<myClass *> instances; }; ``` and somewhere, do a single call to ``` signal(SIGIO, myClass::callHandlers); ``` But I think that if you end up using the last solution, you should probably think about changing your handling design :-)!
To pass a pointer to a method, it must be a static method and you must specify the class name. Try this: ``` class myClass { void myFunction () { signal(SIGIO, myClass::myHandler); } static void myHandler (int signum) { // blabla } }; ``` And you should also read the link supplied by Baget, the [paragraph 33.2 in the C++ FAQ](http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2).
Is it possible to use signal inside a C++ class?
[ "", "c++", "signal-handling", "" ]
How can I select the good method (I have in the example below show 2 differents way that doesn't work). I was using instead of a variable of type Object with a IF and IS to do the job but I am trying to avoid using Object and boxing/unboxing. So I thought that Generic could do the job but I am stuck here. Here is a small snippet of code that illustrate my question: ``` class Program { static void Main(string[] args) { Parser p = new Parser(); ObjectType1 o1 = new ObjectType1(); p.execute(o1); Console.Read(); } } class Parser { public T execute<T>(T obj) { /* if (obj is ObjectType1) this.action((ObjectType1)obj); else if (obj is ObjectType2) this.action((ObjectType2)obj); */ this.action(obj); return obj; } private void action(ObjectType1 objectType1) { Console.WriteLine("1"); } private void action(ObjectType2 objectType2) { Console.WriteLine("2"); } } class ObjectType1 { } class ObjectType2 { } ``` ## Update I do not want interface and class. Sorry. I knew that it's not the goal of the question. Casting with (ObjectType)obj doesn't work but if you do : ``` if (obj is ObjectType1) this.action(obj as ObjectType1); else if (obj is ObjectType2) this.action(obj as ObjectType1); ``` it works... why? And... I cannot overload for all type the execute method because this method is from an Interface. This is why all need to be called from this method.
No, you can't do this. Generics don't work like C++ templates - the generic method is compiled just once. The only information that the compiler can use for overload resolution is the information it knows about within the generic method, regardless of what code uses it. As an example to show this, here's a bit of code which may not work how you expect it to: ``` using System; class Test { static void Main() { string x = "hello"; string y = string.Copy(x); Console.WriteLine(x==y); // Overload used Compare(x, y); } static void Compare<T>(T x, T y) where T : class { Console.WriteLine(x == y); // Reference comparison } } ``` It's hard to say the best way to proceed without knowing more about what you want to do.
Have you considered interfaces? ``` interface IAction { void action(); } class ObjectType1 : IAction { void action() { Console.WriteLine("1"); } } class ObjectType2 : IAction { void action() { Console.WriteLine("2"); } } class Parser { public IAction execute(IAction obj) { obj.action(); return obj; } } ``` ### Edited by OP: This solution would require to change all Business Logic Object to have this interface. This is really not a thing to do (in my situation). And, in other situation, I always prefer to have clean BusinessObject that doesn't have Interface not related with Business stuff. In my question, I want a solution that is more related with Generic/Object/Delegate method to achieve it. Thx you. This answer won't be accepted.
C# Generic and method
[ "", "c#", ".net", "generics", ".net-2.0", "c#-2.0", "" ]
does anybody know any resources that I can refer to?
I believe you are referring to the [JQuery FadeOut effect](http://docs.jquery.com/Effects/fadeOut#speedcallback) (since [Stackoverflow uses JQuery](http://ttp://blog.stackoverflow.com/2008/09/what-was-stack-overflow-built-with/))
Stackoverflow uses the JQuery library, and it uses the [fadeOut effect](http://docs.jquery.com/Effects/fadeOut#speedcallback) for what you are describing. I have never used JQuery, but I have used the [scriptaculous](http://github.com/madrobby/scriptaculous/wikis) library to do this same thing in the past. The [Effect.highlight](http://github.com/madrobby/scriptaculous/wikis/effect-highlight) effect is probably the one you are looking for.
javascript flashing effect after you answer a question, or when you cannot vote down and close the warning
[ "", "javascript", "" ]
I have a 3 table SQLServer Database. ``` Project ProjectID ProjectName Thing ThingID ThingName ProjectThingLink ProjectID ThingID CreatedDate ``` When a Thing is ascribed to a Project an entry is put in the ProjectThingLink table. Things can move between Projects. The CreatedDate is used to know which Project a Thing was last moved too. I am trying to create a list of all Projects with which Things are currently linked to them, but my brain is failing. Is there an easy way of doing this?
``` select p.projectName, t.ThingName from projects p join projectThingLink l on l.projectId = p.projectId join thing t on t.thingId = l.thingId where l.createdDate = ( select max(l2.createdDate) from projectThingLink l2 where l2.thingId = l.thingId ); ``` NOTE: Corrected after comment
This will almost always give you better performance than the subquery method. You're basically looking for the row which doesn't have any other rows past it rather than looking for the row with the greatest date: ``` SELECT P.ProjectID, P.ProjectName, T.ThingID, T.ThingName FROM dbo.Projects P INNER JOIN dbo.ProjectThingLinks PTL1 ON PTL1.ProjectID = P.ProjectID LEFT OUTER JOIN dbo.ProjectThingLinks PTL2 ON PTL2.ProjectID = ThingID = PTL1.ThingID AND PTL2.CreatedDate > PTL1.CreatedDate INNER JOIN dbo.Things T ON T.ThingID = PTL1.ThingID WHERE PTL2.ThingID IS NULL ``` Once you decide on your business rules for handling two rows that have identical CreatedDate values you may need to tweak the query. Also, as a side note, a table called "Things" is typically a good sign of a problem with your database design. Tables should represent distinct real life entities. That kind of generality will usually result in problems in the future. If these are resources then they will probably share certain attributes beyond just a name. Maybe your case is a very special case, but most likely not. ;)
How do I select only the latest entry in a table?
[ "", "sql", "sql-server", "" ]
I have got a template class as follows: ``` class MyClass<T> { T field; public void myMethod() { field = new T(); // gives compiler error } } ``` How do I create a new instance of T in my class?
After type erasure, all that is known about `T` is that it is some subclass of `Object`. You need to specify some factory to create instances of `T`. One approach could use a [`Supplier<T>`](http://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html): ``` class MyClass<T> { private final Supplier<? extends T> ctor; private T field; MyClass(Supplier<? extends T> ctor) { this.ctor = Objects.requireNonNull(ctor); } public void myMethod() { field = ctor.get(); } } ``` Usage might look like this: ``` MyClass<StringBuilder> it = new MyClass<>(StringBuilder::new); ``` Alternatively, you can provide a `Class<T>` object, and then use reflection. ``` class MyClass<T> { private final Constructor<? extends T> ctor; private T field; MyClass(Class<? extends T> impl) throws NoSuchMethodException { this.ctor = impl.getConstructor(); } public void myMethod() throws Exception { field = ctor.newInstance(); } } ```
Another non-reflective approach is to use a hybrid Builder / Abstract Factory pattern. In Effective Java, Joshua Bloch goes over the Builder pattern in detail, and advocates a generic Builder interface: ``` public interface Builder<T> { public T build(); } ``` Concrete builders can implement this interface, and outside classes can use the concrete builder to configure the Builder as required. The builder can be passed to MyClass as a `Builder<T>`. Using this pattern, you can get new instances of `T`, even if `T` has constructor parameters or requires additional configuration. Of course, you'll need some way to pass the Builder into MyClass. If you can't pass anything into MyClass, then Builder and Abstract Factory are out.
Instantiating object of type parameter
[ "", "java", "generics", "reflection", "" ]
I need an equivalent to c++'s `std::multimap<K, V, Comp, Alloc>` in C-sharp. Does it exist in the standard library?
Because it's almost christmas :) ``` ////////////////////////////////////////////////////////////////////// // Algorithmia is (c) 2008 Solutions Design. All rights reserved. // http://www.sd.nl ////////////////////////////////////////////////////////////////////// // COPYRIGHTS: // Copyright (c) 2008 Solutions Design. All rights reserved. // // The Algorithmia library sourcecode and its accompanying tools, tests and support code // are released under the following license: (BSD2) // ---------------------------------------------------------------------- // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY SOLUTIONS DESIGN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SOLUTIONS DESIGN OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those of the authors // and should not be interpreted as representing official policies, either expressed or implied, // of Solutions Design. // ////////////////////////////////////////////////////////////////////// // Contributers to the code: // - Frans Bouma [FB] ////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using SD.Tools.Algorithmia.UtilityClasses; namespace SD.Tools.Algorithmia.GeneralDataStructures { /// <summary> /// Extension to the normal Dictionary. This class can store more than one value for every key. It keeps a HashSet for every Key value. /// Calling Add with the same Key and multiple values will store each value under the same Key in the Dictionary. Obtaining the values /// for a Key will return the HashSet with the Values of the Key. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> public class MultiValueDictionary<TKey, TValue> : Dictionary<TKey, HashSet<TValue>> { /// <summary> /// Initializes a new instance of the <see cref="MultiValueDictionary&lt;TKey, TValue&gt;"/> class. /// </summary> public MultiValueDictionary() : base() { } /// <summary> /// Adds the specified value under the specified key /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public void Add(TKey key, TValue value) { ArgumentVerifier.CantBeNull(key, "key"); HashSet<TValue> container = null; if(!this.TryGetValue(key, out container)) { container = new HashSet<TValue>(); base.Add(key, container); } container.Add(value); } /// <summary> /// Determines whether this dictionary contains the specified value for the specified key /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>true if the value is stored for the specified key in this dictionary, false otherwise</returns> public bool ContainsValue(TKey key, TValue value) { ArgumentVerifier.CantBeNull(key, "key"); bool toReturn = false; HashSet<TValue> values = null; if(this.TryGetValue(key, out values)) { toReturn = values.Contains(value); } return toReturn; } /// <summary> /// Removes the specified value for the specified key. It will leave the key in the dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public void Remove(TKey key, TValue value) { ArgumentVerifier.CantBeNull(key, "key"); HashSet<TValue> container = null; if(this.TryGetValue(key, out container)) { container.Remove(value); if(container.Count <= 0) { this.Remove(key); } } } /// <summary> /// Merges the specified multivaluedictionary into this instance. /// </summary> /// <param name="toMergeWith">To merge with.</param> public void Merge(MultiValueDictionary<TKey, TValue> toMergeWith) { if(toMergeWith==null) { return; } foreach(KeyValuePair<TKey, HashSet<TValue>> pair in toMergeWith) { foreach(TValue value in pair.Value) { this.Add(pair.Key, value); } } } /// <summary> /// Gets the values for the key specified. This method is useful if you want to avoid an exception for key value retrieval and you can't use TryGetValue /// (e.g. in lambdas) /// </summary> /// <param name="key">The key.</param> /// <param name="returnEmptySet">if set to true and the key isn't found, an empty hashset is returned, otherwise, if the key isn't found, null is returned</param> /// <returns> /// This method will return null (or an empty set if returnEmptySet is true) if the key wasn't found, or /// the values if key was found. /// </returns> public HashSet<TValue> GetValues(TKey key, bool returnEmptySet) { HashSet<TValue> toReturn = null; if(!base.TryGetValue(key, out toReturn) && returnEmptySet) { toReturn = new HashSet<TValue>(); } return toReturn; } } } ```
[ILookup](http://msdn.microsoft.com/en-us/library/bb534291.aspx) may be good enough for you - but unfortunately there are no public implementations. You've basically got to go through [Enumerable.ToLookup](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx), as far as I'm aware. That means it's a "build once" kind of map - you can't add to it later. However, if that's all you need it's handy to be able to just use the built-in stuff.
multimap in .NET
[ "", "c#", "multimap", "" ]
That is, all text and subtags, without the tag of an element itself? Having ``` <p>blah <b>bleh</b> blih</p> ``` I want ``` blah <b>bleh</b> blih ``` element.text returns "blah " and etree.tostring(element) returns: ``` <p>blah <b>bleh</b> blih</p> ```
This is the solution I ended up using: ``` def element_to_string(element): s = element.text or "" for sub_element in element: s += etree.tostring(sub_element) s += element.tail return s ```
ElementTree works perfectly, you have to assemble the answer yourself. Something like this... ``` "".join( [ "" if t.text is None else t.text ] + [ xml.tostring(e) for e in t.getchildren() ] ) ``` Thanks to JV amd PEZ for pointing out the errors. --- Edit. ``` >>> import xml.etree.ElementTree as xml >>> s= '<p>blah <b>bleh</b> blih</p>\n' >>> t=xml.fromstring(s) >>> "".join( [ t.text ] + [ xml.tostring(e) for e in t.getchildren() ] ) 'blah <b>bleh</b> blih' >>> ``` Tail not needed.
How do I get the full XML or HTML content of an element using ElementTree?
[ "", "python", "xml", "api", "elementtree", "" ]
How do I parameterize a query containing an `IN` clause with a variable number of arguments, like this one? ``` SELECT * FROM Tags WHERE Name IN ('ruby','rails','scruffy','rubyonrails') ORDER BY Count DESC ``` In this query, the number of arguments could be anywhere from 1 to 5. I would prefer not to use a dedicated stored procedure for this (or XML), but if there is some elegant way specific to [SQL Server 2008](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2008), I am open to that.
Here's a quick-and-dirty technique I have used: ``` SELECT * FROM Tags WHERE '|ruby|rails|scruffy|rubyonrails|' LIKE '%|' + Name + '|%' ``` So here's the C# code: ``` string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" }; const string cmdText = "select * from tags where '|' + @tags + '|' like '%|' + Name + '|%'"; using (SqlCommand cmd = new SqlCommand(cmdText)) { cmd.Parameters.AddWithValue("@tags", string.Join("|", tags); } ``` Two caveats: * The performance is terrible. `LIKE "%...%"` queries are not indexed. * Make sure you don't have any `|`, blank, or null tags or this won't work There are other ways to accomplish this that some people may consider cleaner, so please keep reading.
You can parameterize *each* value, so something like: ``` string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" }; string cmdText = "SELECT * FROM Tags WHERE Name IN ({0})"; string[] paramNames = tags.Select( (s, i) => "@tag" + i.ToString() ).ToArray(); string inClause = string.Join(", ", paramNames); using (SqlCommand cmd = new SqlCommand(string.Format(cmdText, inClause))) { for (int i = 0; i < paramNames.Length; i++) { cmd.Parameters.AddWithValue(paramNames[i], tags[i]); } } ``` Which will give you: ``` cmd.CommandText = "SELECT * FROM Tags WHERE Name IN (@tag0, @tag1, @tag2, @tag3)" cmd.Parameters["@tag0"] = "ruby" cmd.Parameters["@tag1"] = "rails" cmd.Parameters["@tag2"] = "scruffy" cmd.Parameters["@tag3"] = "rubyonrails" ``` No, this is not open to [SQL injection](http://en.wikipedia.org/wiki/SQL_injection). The only injected text into CommandText is not based on user input. It's solely based on the hardcoded "@tag" prefix, and the index of an array. The index will *always* be an integer, is not user generated, and is safe. The user inputted values are still stuffed into parameters, so there is no vulnerability there. Edit: > Injection concerns aside, take care to note that constructing the command text to accomodate a variable number of parameters (as above) impede's SQL server's ability to take advantage of cached queries. The net result is that you almost certainly lose the value of using parameters in the first place (as opposed to merely inserting the predicate strings into the SQL itself). Not that cached query plans aren't valuable, but IMO this query isn't nearly complicated enough to see much benefit from it. While the compilation costs may approach (or even exceed) the execution costs, you're still talking milliseconds. If you have enough RAM, I'd expect SQL Server would probably cache a plan for the common counts of parameters as well. I suppose you could always add five parameters, and let the unspecified tags be NULL - the query plan should be the same, but it seems pretty ugly to me and I'm not sure that it'd worth the micro-optimization (although, on Stack Overflow - it may very well be worth it). Also, SQL Server 7 and later will [auto-parameterize queries](http://msdn.microsoft.com/en-us/library/aa175264(SQL.80).aspx), so using parameters isn't really necessary from a performance standpoint - it is, however, *critical* from a security standpoint - especially with user inputted data like this.
Parameterize an SQL IN clause
[ "", "sql", "sql-server-2008", "parameters", "" ]
I’ve just found out that the execution plan performance between the following two select statements are massively different: ``` select * from your_large_table where LEFT(some_string_field, 4) = '2505' select * from your_large_table where some_string_field like '2505%' ``` The execution plans are 98% and 2% respectively. Bit of a difference in speed then. I was actually shocked when I saw it. I've always done LEFT(xxx) = 'yyy' as it reads well. I actually found this out by checking the LINQ generated SQL against my hand crafted SQL. I assumed the LIKE command would be slower, but is in fact much much faster. My question is why is the LEFT() slower than the LIKE '%..'. They are afterall identical? Also, is there a CPU hit by using LEFT()?
More generally speaking, you should never use a function on the LEFT side of a WHERE clause in a query. If you do, SQL won't use an index--it has to evaluate the function for every row of the table. The goal is to make sure that your where clause is "[Sargable](http://en.wikipedia.org/wiki/Sargable)" Some other examples: ``` Bad: Select ... WHERE isNull(FullName,'') = 'Ed Jones' Fixed: Select ... WHERE ((FullName = 'Ed Jones') OR (FullName IS NULL)) Bad: Select ... WHERE SUBSTRING(DealerName,4) = 'Ford' Fixed: Select ... WHERE DealerName Like 'Ford%' Bad: Select ... WHERE DateDiff(mm,OrderDate,GetDate()) >= 30 Fixed: Select ... WHERE OrderDate < DateAdd(mm,-30,GetDate()) Bad: Select ... WHERE Year(OrderDate) = 2003 Fixed: Select ... WHERE OrderDate >= '2003-1-1' AND OrderDate < '2004-1-1' ```
It looks like the expression LEFT(some\_string\_field, 4) is evaluated for every row of a full table scan, while the "like" expression will use the index. Optimizing "like" to use an index if it is a front-anchored pattern is a much easier optimization than analyzing arbitrary expressions involving string functions.
Surprising SQL speed increase
[ "", "sql", "performance", "" ]
I am doing the following statements in Java, ``` Obj t[] = new Obj[10]; Obj a = new Obj("a"); t[0] = a; a = new Obj("b"); t[1] = a; ``` Why in java, when i access t[0] , it returns me "a", rather than "b"? Is this because of the GC? and can i believe it is safe to do such an operation
Here's exactly what's happening. ``` Obj t[] = new Obj[10]; // 1 Obj a = new Obj("a"); // 2 t[0] = a; a = new Obj("b"); // 3 t[1] = a; // 4 ``` 1. You create an array that can hold 10 references to instances of `Obj`. Call this `obj01`. You assign it to `t`. Note that the variable `t` and the actual object `obj01` have a pretty casual relationship. 2. You create an instance of `Obj`, call this `obj02`. You assign a reference to this object to the variable `a`. Note that the variable `a` and the actual object `obj02` have a pretty casual relationship. You also put this reference into `t[0]`. You have one object known in two places. The object `obj02` (with a value of `"a"`) is known as `a` and known also as `t[0]`. 3. You create an instance of `Obj`, call this `obj03`. You assign a reference to this new object to the old variable `a`. Note that the variable `a` and the actual object `obj03` have a pretty casual relationship. `a` used to reference `obj02`, but it doesn't reference that anymore. So, `obj01` (an array) is referenced by `t`; `obj02` (and instance of `Obj`) is known as `t[0]`; `obj03` (an instance of `Obj`) is known as `a`. 4. You put the reference that's in `a` into `t[1]`. So, `t[1]` gets a reference to `obj03`. At this point all the objects are referenced by variables which are in scope. Since all objects have references, they can't be garbage collected.
The problem is, Java doesn't have pointers. When you assign one object variable to another, it changes what that variable points to but not any other references you might have. So: ``` Object a = new Object("a"); Object b = new Object("b"); a = b; b = new Object("c"); // At this point, a = "b" // and b = "c" ``` As you can see, although you first set a = b, when you then set b to be a new Object, a still retains the reference to the old object.
What exactly happens while you assign a reference to an element in Array in Java?
[ "", "java", "arrays", "" ]
I need your expertise once again. I have a java class that searches a directory for xml files (displays the files it finds in the eclipse console window), applies the specified xslt to these and sends the output to a directory. What I want to do now is create an xml containing the file names and file format types. The format should be something like; ``` <file> <fileName> </fileName> <fileType> </fileType> </file> <file> <fileName> </fileName> <fileType> </fileType> </file> ``` Where for every file it finds in the directory it creates a new `<file>`. Any help is truely appreciated.
Have a look at DOM and ECS. The following example was adapted to you requirements from [here](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1044810.html#): ``` XMLDocument document = new XMLDocument(); for (File f : files) { document.addElement( new XML("file") .addXMLAttribute("fileName", file.getName()) .addXMLAttribute("fileType", file.getType()) ) ); } ```
Use an XML library. There are plenty around, and the third party ones are almost all easier to use than the built-in DOM API in Java. Last time I used it, [JDom](http://jdom.org/) was pretty good. (I haven't had to do much XML recently.) Something like: ``` Element rootElement = new Element("root"); // You didn't show what this should be Document document = new Document(rootElement); for (Whatever file : files) { Element fileElement = new Element("file"); fileElement.addContent(new Element("fileName").addContent(file.getName()); fileElement.addContent(new Element("fileType").addContent(file.getType()); } String xml = XMLOutputter.outputString(document); ```
Creating xml from with java
[ "", "java", "xml", "" ]
Is there a way for a Windows application to access another applications data, more specifically a text input field in the GUI, and grab the text there for processing in our own application? If it is possible, is there a way to "shield" your application to prevent it? --- **EDIT:** The three first answers seem to be about getting the another applications window title, not a specific text input field in that window. I'm no Windows API expert, so could you be more exact how do I find a certain text field in that window, what are the prerequisites for it (seems like knowing a window handle something is required, does it require knowing the text field handle as well? How do I get that? etc...) Code snippets in C++ really would be really appreciated. MSDN help is hard to browse since Win32-API has such horrible naming conventions. --- **Completed!** See my answer below for a how-to in C++.
For reading text content from another application's text box you will need to get that text box control's window handle somehow. Depending on how your application UI is designed (if it has a UI that is) there are a couple of different ways that you can use to get this handle. You might use "FindWindow"/"FindWindowEx" to locate your control or use "WindowFromPoint" if that makes sense. Either way, once you have the handle to the text control you can send a "WM\_GETTEXT" message to it to retrieve its contents (assuming it is a standard text box control). Here's a concocted sample (sans error checks): ``` HWND hwnd = (HWND)0x00310E3A; char szBuf[2048]; LONG lResult; lResult = SendMessage( hwnd, WM_GETTEXT, sizeof( szBuf ) / sizeof( szBuf[0] ), (LPARAM)szBuf ); printf( "Copied %d characters. Contents: %s\n", lResult, szBuf ); ``` I used "Spy++" to get the handle to a text box window that happened to be lying around. As for protecting your own text boxes from being inspected like this, you could always sub-class your text box (see "SetWindowLong" with "GWL\_WNDPROC" for the "nIndex" parameter) and do some special processing of the "WM\_GETTEXT" message to ensure that only requests from the same process are serviced.
OK, I have somewhat figured this out. The starting point is now knowing the window handle exactly, we only know partial window title, so first thing to do is find that main window: ``` ... EnumWindows((WNDENUMPROC)on_enumwindow_cb, 0); ... ``` which enumerates through all the windows on desktop. It makes a callback with each of these window handles: ``` BOOL CALLBACK on_enumwindow_cb(HWND hwndWindow, LPARAM lParam) { TCHAR wsTitle[2048]; LRESULT result; result = SendMessage(hwndWindow, WM_GETTEXT, (WPARAM) 2048, (LPARAM) wsTitle); ... ``` and by using the wsTitle and little regex magic, we can find the window we want. By using the before mentioned Spy++ I could figure out the text edit field class name and use it to find wanted field in the *hwndWindow*: ``` hwndEdit = FindWindowEx(hwndWindow, NULL, L"RichEdit20W", NULL); ``` and then we can read the text from that field: ``` result = SendMessage(hwndEdit, WM_GETTEXT, (WPARAM) 4096, (LPARAM) wsText); ``` I hope this helps anyone fighting with the same problem!
Reading from a text field in another application's window
[ "", "c++", "user-interface", "winapi", "textbox", "ipc", "" ]
I would like to search my table having a column of first names and a column of last names. I currently accept a search term from a field and compare it against both columns, one at a time with ``` select * from table where first_name like '%$search_term%' or last_name like '%$search_term%'; ``` This works fine with single word search terms but the result set includes everyone with the name "Larry". But if someone enters a first name then a space, then a last name, I want a narrower search result. I've tried the following without success. ``` select * from table where first_name like '%$search_term%' or last_name like '%$search_term%' or concat_ws(' ',first_name,last_name) like '%$search_term%'; ``` Any advice? **EDIT:** The name I'm testing with is "Larry Smith". The db stores "Larry" in the "first\_name" column, and "Smith" in the "last\_name" column. The data is clean, no extra spaces and the search term is trimmed left and right. **EDIT 2:** I tried Robert Gamble's answer out this morning. His is very similar to what I was running last night. I can't explain it, but this morning it works. The only difference I can think of is that last night I ran the concat function as the third "or" segment of my search query (after looking through first\_name and last\_name). This morning I ran it as the last segment after looking through the above as well as addresses and business names. Does running a mysql function at the end of a query work better than in the middle?
What you have should work but can be reduced to: ``` select * from table where concat_ws(' ',first_name,last_name) like '%$search_term%'; ``` Can you provide an example name and search term where this doesn't work?
Note that the search query is now case sensitive. When using ``` SELECT * FROM table WHERE `first_name` LIKE '%$search_term%' ``` It will match both "Larry" and "larry". With this concat\_ws, it will suddenly become case sensitive! This can be fixed by using the following query: ``` SELECT * FROM table WHERE UPPER(CONCAT_WS(' ', `first_name`, `last_name`) LIKE UPPER('%$search_term%') ``` Edit: Note that this only works on non-binary elements. See also [mynameispaulie's answer](https://stackoverflow.com/a/13184217/1201863).
Using mysql concat() in WHERE clause?
[ "", "php", "mysql", "" ]
I'm building an XML DOM document in C++. My problem is this: I execute an XPATH query from an Element in my Document, which I know will return another Element. The elementPtr->selectSingleNode call returns an IXMLDOMNode. How can I gain access to the attributes of this node? Part of me wants to downcast the Node to an Element, but I couldn't get the cast to work. I tried ``` MSXML2::IXMLDOMElementPtr pParentElement; pParentNode->QueryInterface(__uuidof(MSXML2::IXMLDOMElement), (void**) &pParentElement); ``` Which results in the following runtime error: ``` 0x0057cc58 _com_error::`scalar deleting destructor'(unsigned int) ``` The other route I tried was to just use nodes: ``` MSXML2::IXMLDOMNodePtr pParentNode = pParameterElement->selectSingleNode("parent"); MSXML2::IXMLDOMNamedNodeMap* pParentAttributes; pParentNode->get_attributes(&pParentAttributes); MSXML2::IXMLDOMNodePtr pCategoryNameNode = pParentAttributes->getNamedItem("Category"); VARIANT value; pCategoryNameNode->get_nodeValue(&value); CString categoryName = value; ``` This fails at "parentNode->get\_attributes()". It seems like I'm missing something; the API should not be this hard to use. --edit-- What I was missing was that the selectSingleNode call was failing, leaving me with a NULL pointer. You can't call QueryInterface on that, neither can you call get\_attributes on it :P I've selected the answer that fits the question that I asked, not the answer that helped me to realise that I asked the wrong question.
I don't see anything wrong with what you have written. The smart com pointers will help you convert if they can, you don't have to write the query interface yourself. ``` MSXML2::IXMLDOMNodePtr pParentNode = pParameterElement->selectSingleNode("parent"); MSXML2::IXMLDOMElementPtr pParentElement( pParentNode ); ``` Using the Ptr types is a bit painfull in my opinion, though the MSXML interface favours them. Here is an equivelant example using ATL ``` CComPtr<IXMLDOMNode> node = ...; CComQIPtr<IXMLDOMElement> elementNode( node ); if( elementNode ) { // it was an element! } else { // it's something else try again? } ``` The other attempt would look like... ``` CComPtr<IXMLDOMNamedNodeMap> attributes; node->get_attributes( &attributes ); if( attributes ) { _bstr_t name( L"category" ); attributes->getNamedItem(name); } ``` And it's COM, it's always hard to use in C++ :(
How did you try to do the downcast from IXMLDOMNode to IXMLDOMElement? You can't just use a C++ cast for that, as it's a COM object: you've got to use QueryInterface(). --- Looking at your QueryInterface() code, some thoughts: * Is pParentNode definitely not null? I don't think that this is the problem, given what you get, but it's worth checking. * The QueryInterface() call isn't quite right, I think: you've got to call AddRef() one way or another on the returned interface, and your code won't. As another poster noted, you can get \_com\_ptr\_t<> to do this for you: ``` MSXML2::IXMLDOMElementPtr pParentElement(pParentNode); ``` Doing this will, I hope, stop that "scalar deleting destructor" error that's probably caused by an AddRef()/Release() mis-match. Anyway, try the above and see if pParentElement is null or not. If it is, the next thing I'd suggest is calling get\_nodeType() on pParentNode to see what sort of node it really is. This might give a clue as to whether the XPath is not returning what you expect.
How can I access element attributes from an IXMLDOMNode?
[ "", "c++", "dom", "msxml", "ixmldomelement", "ixmldomnode", "" ]
Given either the binary or string representation of an IPv6 address and its prefix length, what's the best way to extract the prefix in Python? Is there a library that would do this for me, or would I have to: 1. convert the address from string to an int (inet\_ntop) 2. Mask out the prefix 3. Convert prefix back to binary 4. Convert binary to string (inet\_ntop)
See <http://code.google.com/p/ipaddr-py/> With this, you can do ``` py> p=ipaddr.IPv6("2001:888:2000:d::a2") py> p.SetPrefix(64) py> p IPv6('2001:888:2000:d::a2/64') py> p.network_ext '2001:888:2000:d::' ``` etc.
Using the python [netaddr](https://github.com/drkjam/netaddr) library: ``` >>> from netaddr.ip import IPNetwork, IPAddress >>> IPNetwork('2001:888:2000:d::a2/64').network 2001:888:2000:d:: ```
Extract ipv6 prefix in python
[ "", "python", "ipv6", "" ]
I'd like to be able to print the definition code of a lambda function. Example if I define this function through the lambda syntax: ``` >>>myfunction = lambda x: x==2 >>>print_code(myfunction) ``` I'd like to get this output: ``` x==2 ```
*As long as you save your code to a source file* you can retrieve the source code of an object using the inspect module. example: open editor type: ``` myfunction = lambda x: x==2 ``` save as lamtest.py open shell type python to get to interactive python type the following: ``` >>>from lamtest import myfunc >>>import inspect >>>inspect.getsource(myfunc) ``` the result: ``` 'myfunc = lambda x: x==2\n' ```
It will only work for mathematical based operations, but you might look at [SymPy](http://code.google.com/p/sympy/)'s `Lambda()` object. It was designed exactly for this purpose: ``` >>> from sympy import * >>> x = Symbol('x') >>> l = Lambda(x, x**2) >>> l Lambda(_x, _x**2) >>> l(3) 9 ``` It even supports pretty printing: ``` >>> pprint(l) ⎛ 2⎞ Λ⎝x, x ⎠ ``` To do your equals example, us the SymPy Eq() object: ``` >>> l1 = Lambda(x, Eq(x, 2)) >>> l1 Lambda(_x, _x == 2) >>> l1(2) True ``` It supports partial argument expansion: ``` >>> y = Symbol('y') >>> l2 = Lambda((x, y), x*y + x) >>> l2(1) Lambda(_y, 1 + _y) >>> l2(1, 2) 3 ``` And of course, you get the advantage of getting all of SymPy's computer algebra: ``` >>> l3 = Lambda(x, sin(x*pi/3)) >>> pprint(l3(1)) ⎽⎽⎽ ╲╱ 3 ───── 2 ``` By the way, if this sounds like a shameless plug, it's because it is. I am one of the developers of SymPy.
print the code which defined a lambda function
[ "", "python", "" ]
What are the benefits of passing by pointer over passing by reference in C++? Lately, I have seen a number of examples that chose passing function arguments by pointers instead of passing by reference. Are there benefits to doing this? Example: ``` func(SPRITE *x); ``` with a call of ``` func(&mySprite); ``` vs. ``` func(SPRITE &x); ``` with a call of ``` func(mySprite); ```
A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference. Also, passing by pointer allows you to explicitly see at the call site whether the object is passed by value or by reference: ``` // Is mySprite passed by value or by reference? You can't tell // without looking at the definition of func() func(mySprite); // func2 passes "by pointer" - no need to look up function definition func2(&mySprite); ```
### Passing by pointer * Caller has to take the address -> not transparent * A 0 value can be provided to mean `nothing`. This can be used to provide optional arguments. ### Pass by reference * Caller just passes the object -> transparent. Has to be used for operator overloading, since overloading for pointer types is not possible (pointers are builtin types). So you can't do `string s = &str1 + &str2;` using pointers. * No 0 values possible -> Called function doesn't have to check for them * Reference to const also accepts temporaries: `void f(const T& t); ... f(T(a, b, c));`, pointers cannot be used like that since you cannot take the address of a temporary. * Last but not least, references are easier to use -> less chance for bugs.
Are there benefits of passing by pointer over passing by reference in C++?
[ "", "c++", "pointers", "parameter-passing", "pass-by-reference", "" ]
It is not possible to fire an event in C# that has no handlers attached to it. So before each call it is necessary to check if the event is null. ``` if ( MyEvent != null ) { MyEvent( param1, param2 ); } ``` I would like to keep my code as clean as possible and get rid of those null checks. I don't think it will affect performance very much, at least not in my case. ``` MyEvent( param1, param2 ); ``` Right now I solve this by adding an empty inline handler to each event manually. This is error prone, since I need to remember to do that etc. ``` void Initialize() { MyEvent += new MyEvent( (p1,p2) => { } ); } ``` Is there a way to generate empty handlers for all events of a given class automatically using reflection and some CLR magic?
I saw this on another post and have shamelessly stolen it and used it in much of my code ever since: ``` public delegate void MyClickHandler(object sender, string myValue); public event MyClickHandler Click = delegate {}; // add empty delegate! //Let you do this: public void DoSomething() { Click(this, "foo"); } //Instead of this: public void DoSomething() { if (Click != null) // Unnecessary! Click(this, "foo"); } ``` \* If anyone knows the origin of this technique, please post it in the comments. I really do believe in the source getting due credit. (**Edit:** I got it from this post [Hidden Features of C#?](https://stackoverflow.com/questions/9033/hidden-features-of-c#9282))
The notation: ``` if ( MyEvent != null ) { MyEvent( param1, param2 ); } ``` is not thread safe. You should do it this way: ``` EventHandler handler = this.MyEvent; if ( null != handler ) { handler( param1, param2 ); } ``` I understand, that this is a bother, so you can do helper method: ``` static void RaiseEvent( EventHandler handler, object sender, EventArgs e ) { if ( null != handler ) { handler( sender, e ); } } ``` and then call: ``` RaiseEvent( MyEvent, param1, param2 ); ``` If you are using C# 3.0, you can declare helper method as extension method: ``` static void Raise( this EventHandler handler, object sender, EventArgs e ) { if ( null != handler ) { handler( sender, e ); } } ``` and then call: ``` MyEvent.Raise( param1, param2 ); ``` Also you can create next extension/helper methods for other event handlers. For example: ``` static void Raise<TEventArgs>( this EventHandler<TEventArgs> handler, object sender, TEventArgs e ) where TEventArgs : EventArgs { if ( null != handler ) { handler( sender, e ); } } ```
Create empty C# event handlers automatically
[ "", "c#", "events", "delegates", "clr", "" ]
In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class. Suppose that you want create a subclass of `OptionParser` that overrides only a single method (for example `exit()`). In Java you can write something like this: ``` new OptionParser () { public void exit() { // body of the method } }; ``` This piece of code creates a anonymous class that extends `OptionParser` and override only the `exit()` method. There is a similar idiom in Python? Which idiom is used in these circumstances?
You can use the [`type(name, bases, dict)`](http://docs.python.org/library/functions.html#type) builtin function to create classes on the fly. For example: ``` op = type("MyOptionParser", (OptionParser,object), {"foo": lambda self: "foo" }) op().foo() ``` Since OptionParser isn't a new-style class, you have to explicitly include `object` in the list of base classes.
Java uses anonymous classes mostly to imitate closures or simply code blocks. Since in Python you can easily pass around methods there's no need for a construct as clunky as anonymous inner classes: ``` def printStuff(): print "hello" def doit(what): what() doit(printStuff) ``` Edit: I'm aware that this is not what is needed in this special case. I just described the most common python solution to the problem most commonly by anonymous inner classes in Java.
Does Python have something like anonymous inner classes of Java?
[ "", "python", "class", "anonymous-class", "" ]
In the following code doesn't work as ``` public void Foo() { CompanyDataContext db = new CompanyDataContext(); Client client = (select c from db.Clients ....).Single(); Bar(client); } public void Bar(Client client) { CompanyDataContext db = new CompanyDataContext(); db.Client.Attach(client); client.SomeValue = "foo"; db.SubmitChanges(); } ``` This doens't work, I get error msg. "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported." How do you work with DataContexts throughout an application so you don't need to pass around a reference? What
The [PLINQO](http://plinqo.com) framework generates detach for all entities making it easy to detach and reattach objects without receiving that error. ``` public void Foo() { CompanyDataContext db = new CompanyDataContext(); Client client = (select c from db.Clients ....).Single(); // makes it possible to call detach here client.Detach(); Bar(client); } public void Bar(Client client) { CompanyDataContext db = new CompanyDataContext(); db.Client.Attach(client); client.SomeValue = "foo"; db.SubmitChanges(); } ``` Here is the article that describing how the detach was implemented. <http://www.codeproject.com/KB/linq/linq-to-sql-detach.aspx>
They really mean it with 'This is not supported.'. Attaching to an object fetched from another data context is not implemented. There are a number of workarounds to the problem, the recommended way is by serializing objects, however this is not easy nor a clean approach. The most simple approach I found is to use a readonly DataContext for fetching objects like this: ``` MyDataContext dataContext = new MyDataContext() { DeferredLoadingEnabled = false, ObjectTrackingEnabled = false }; ``` The objects obtained from this context can be attached to another context but only applies to some scenarios.
Linq2Sql: Manage DataContext
[ "", "c#", "asp.net", "linq-to-sql", "" ]
I have nested dictionaries: ``` {'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'}, u'key1': {'attrs': {'entity': 'r', 'hash': '34njasd3h43b4n3', 'id': '4130-1'}, u'key2': {'attrs': {'entity': 'c', 'hash': '34njasd3h43bdsfsd4n3', 'id': '4130-1-1'}}}, u'key3': {'attrs': {'entity': 'r', 'hash': '34njasasasd3h43b4n3', 'id': '4130-2'}, u'key4': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-1'}}, u'key5': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-2'}}}}, 'someohterthing': 'someothervalue', 'something': 'somevalue'} ``` given an `id` - one of all the `ids` like `4130` to `4130-2-2`. whats the easiest way to navigate to the correct dictionary? If the given `id` is `4130-2-1` then it should reach the dictionary with `key=key5`. No XML approaches please. **Edit(1):** The nesting is between `1` to `4` levels, but I know the nesting before I parse. **Edit(2)**: Fixed the code. **Edit(3)**: Fixed code again for string values of `ids`. Please excuse for the confusion created. This is final I hope :)
Your structure is unpleasantly irregular. Here's a version with a **Visitor** function that traverses the `attrs` sub-dictionaries. ``` def walkDict( aDict, visitor, path=() ): for k in aDict: if k == 'attrs': visitor( path, aDict[k] ) elif type(aDict[k]) != dict: pass else: walkDict( aDict[k], visitor, path+(k,) ) def printMe( path, element ): print path, element def filterFor( path, element ): if element['id'] == '4130-2-2': print path, element ``` You'd use it like this. ``` walkDict( myDict, filterFor ) ``` This can be turned into a generator instead of a **Visitor**; it would `yield path, aDict[k]` instead of invoking the visitor function. You'd use it in a for loop. ``` for path, attrDict in walkDictIter( aDict ): # process attrDict... ```
If you want to solve the problem in a general way, no matter how many level of nesting you have in your dict, then create a recursive function which will traverse the tree: ``` def traverse_tree(dictionary, id=None): for key, value in dictionary.items(): if key == 'id': if value == id: print dictionary else: traverse_tree(value, id) return >>> traverse_tree({1: {'id': 2}, 2: {'id': 3}}, id=2) {'id': 2} ```
How do I traverse and search a python dictionary?
[ "", "python", "parsing", "dictionary", "struct", "nested", "" ]
I have a [pseudorandom number generator](http://en.wikipedia.org/wiki/Pseudorandom_number_generator) (PRNG) with nice properties which uses six `UInt32`s as state. I need to come up with a reasonable way to seed it. Two obvious possibilities are: 1) generate six random numbers using `System.Random` and use them as seeds; 2) generate two `GUID`s with `Guid.NewGuid()`. Which would be better? I do *not* need cryptographic security.
If it needs `UInt32`, then `Random` is more convenient? just `Next()`, `Next()`, `Next()` etc (and cast)... (use the same `Random` instance however - don't create `new Random()` each time). It depends on what the intent is as to whether this offers enough randomness. Since this is just the seed, it should be OK...
Unfortunately System.Random() also requires a seed value. By default it uses the current Tick count which is predictable and not actually random. So you'll need a seed for Random which leads you back to your original question ... I haven't ever used Guid.GetHashCode() as a seed before but my 2 second reaction is that doesn't sound like a bad idea.
Seeding a random number generator in .NET
[ "", "c#", "random", "" ]
What do you guys think about this for a generic singleton? ``` using System; using System.Reflection; // Use like this /* public class Highlander : Singleton<Highlander> { private Highlander() { Console.WriteLine("There can be only one..."); } } */ public class Singleton<T> where T : class { private static T instance; private static object initLock = new object(); public static T GetInstance() { if (instance == null) { CreateInstance(); } return instance; } private static void CreateInstance() { lock (initLock) { if (instance == null) { Type t = typeof(T); // Ensure there are no public constructors... ConstructorInfo[] ctors = t.GetConstructors(); if (ctors.Length > 0) { throw new InvalidOperationException(String.Format("{0} has at least one accesible ctor making it impossible to enforce singleton behaviour", t.Name)); } // Create an instance via the private constructor instance = (T)Activator.CreateInstance(t, true); } } } } ```
Creating a singleton class is just a few lines of code, and with the difficulty of making a generic singleton i always write those lines of code. ``` public class Singleton { private Singleton() {} static Singleton() {} private static Singleton _instance = new Singleton(); public static Singleton Instance { get { return _instance; }} } ``` The ``` private static Singleton _instance = new Singleton(); ``` line removes the need for locking, as a static constructor is thread safe.
Well, it isn't really singleton - since you can't control `T`, there can be as many `T` instances as you like. (removed thread-race; noted the double-checked usage)
A generic singleton
[ "", "c#", "singleton", "generics", "" ]
I have a WebBrowser control which is being instantiated dynamically from a background STA thread because the parent thread is a BackgroundWorker and has lots of other things to do. The problem is that the Navigated event never fires, unless I pop a MessageBox.Show() in the method that told it to .Navigate(). I shall explain: ``` ThreadStart ts = new ThreadStart(GetLandingPageContent_ChildThread); Thread t = new Thread(ts); t.SetApartmentState(ApartmentState.STA); t.Name = "Mailbox Processor"; t.Start(); protected void GetLandingPageContent_ChildThread() { WebBrowser wb = new WebBrowser(); wb.Navigated += new WebBrowserNavigatedEventHandler(wb_Navigated); wb.Navigate(_url); MessageBox.Show("W00t"); } protected void wb_Navigated(object sender, WebBrowserNavigatedEventArgs e) { WebBrowser wb = (WebBrowser)sender; // Breakpoint HtmlDocument hDoc = wb.Document; } ``` This works fine; but the messagebox will get in the way since this is an automation app. When I remove the MessageBox.Show(), the WebBrowser.Navigated event never fires. I've tried supplanting this line with a Thread.Sleep(), and by suspending the parent thread. Once I get this out of the way, I intend to Suspend the parent thread while the WebBrowser is doing its job and find some way of passing the resulting HTML back to the parent thread so it can continue with further logic. *Why does it do this? How can I fix it?* If someone can provide me with a way to fetch the content of a web page, fill out some data, and return the content of the page on the other side of the submit button, all against a webserver that doesn't support POST verbs nor passing data via QueryString, I'll also accept that answer as this whole exercise will have been unneccessary. --- **Solution:** I ended up just not using the BackgroundWorker and slave thread at all at the suggestion of the team architect... Though at the expense of responsiveness :(
`WebBrowser` won't do much unless it is shown and has a UI thread associated; are you showing the form on which it resides? You need to, to use the DOM etc. The form could be off-screen if you don't want to display it to the user, but it won't work well in a service (for example). For scraping purposes, you can normally simulate a regular HTML browwser using `WebClient` etc. IS this not sufficient? You can use tools like "[Fiddler](http://www.fiddlertool.com/)" to investigate the exact request you need to make to the server. For more than that, you might look at the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack), which offers DOM access to HTML without a browser.
The Navigated and DocumentComplete events will not fire if the visibility of the WebBrowser is set to false. You can work around this limitation by making the WebBrowser visible but setting it's location so that it is outside of the user interface like: ``` wb.Visible = true; wb.Left = -wb.Width; // notice the minus sign ```
WebBrowser.Navigated Only Fires when I MessageBox.Show();
[ "", "c#", "multithreading", "delegates", "browser", "apartments", "" ]
I have an NHibernate Dao..lets call it MyClassDao for want of a better name. I am writing the following code. ``` MyClassDao myDao = new MyClassDao(); var values = myDao.GetByCriteria(Restrictions.Eq("Status", someStatusValue)); ``` I am using this in a Unit Test to pull back values from the database. However, it is taking over 30 seconds to run the test which is too long in my opinion...so what I'd like to do is limit the result set being pulled back...say to about 5 values. in sql I would do something like the following to to achieve something like this ``` set rowcount 5 select * from whatever_table set rowcount 0 ``` Is there a way...without using the NHibernate Query language to restrict the size of a result set?
Use ICriteria.SetMaxResults()
You can use the SetMaxResults method on IQuery (if you use HQL) or ICriteria (if you use criteria API).
How do I limit the result set being pulled back by NHibernate's GetByCriteria?
[ "", "c#", "nhibernate", "criteria", "resultset", "restriction", "" ]
I was browsing through the questions and noticed this: ``` SELECT prodid, issue FROM Sales WHERE custid = @custid AND datesold = SELECT MAX(datesold) FROM Sales s WHERE s.prodid = Sales.prodid AND s.issue = Sales.issue AND s.custid = @custid ``` I was wondering what the "@" does in front of custID? Is it just a way of referencing the custID from the table being selected?
The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is zero chance for SQL injection.
@ is used as a prefix denoting stored procedure and function parameter names, and also variable names
What does the "@" symbol do in SQL?
[ "", "sql", "" ]
We use Sharepoint as CMS for our webpages at work. I know how to create controls that can be only visible if you have logged in in SharePoint with: <Sharepoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl1" runat="server" PermissionsString="AddAndCustomizePages"><br /> <Sharepoint:CssLink ID="CssLink1" runat="server"/><br /> </Sharepoint:SPSecurityTrimmedControl> But I want to know how to make controls visible (or whatever) programmatically depending on permissions. I cannot use the methods for .NET windows form authentication like: ``` if (!(HttpContext.Current.User == null) && HttpContext.Current.User.Identity.IsAuthenticated){} ``` because we use this for anonymous users who has another type of log in. Could you provide some code? I know that it must be something like verifying the SPContext.Current.FormContext.
How are the users authenticated? With forms authentication or Windows/active directory? If active directory, then I think in that case you might need to get a reference to the current SPWeb, and then do web.CurrentUser.ID. This might come out null when you are anonymous. If not, try web.SiteUsers.GetByID(web.CurrentUser.ID) and see what you get.
[DoesUserHavePermissions](http://msdn.microsoft.com/en-us/library/ms456041.aspx) You can use this method on the current web to check if the current user has a specific permission. I assume your authenticated users have some permission to check for that the anonymous crowd is denied.
How do I know you have logged in a Sharepoint WebPage?
[ "", "c#", ".net", "sharepoint", "sharepoint-2007", "moss", "" ]
Upcasting is allowed in Java, however downcasting gives a compile error. The compile error can be removed by adding a cast but would anyway break at the runtime. In this case why Java allows downcasting if it cannot be executed at the runtime? Is there any practical use for this concept? ``` public class demo { public static void main(String a[]) { B b = (B) new A(); // compiles with the cast, // but runtime exception - java.lang.ClassCastException } } class A { public void draw() { System.out.println("1"); } public void draw1() { System.out.println("2"); } } class B extends A { public void draw() { System.out.println("3"); } public void draw2() { System.out.println("4"); } } ```
Downcasting is allowed when there is a possibility that it succeeds at run time: ``` Object o = getSomeObject(), String s = (String) o; // this is allowed because o could reference a String ``` In some cases this will not succeed: ``` Object o = new Object(); String s = (String) o; // this will fail at runtime, because o doesn't reference a String ``` When a cast (such as this last one) fails at runtime a [`ClassCastException`](https://docs.oracle.com/javase/10/docs/api/java/lang/ClassCastException.html) will be thrown. In other cases it will work: ``` Object o = "a String"; String s = (String) o; // this will work, since o references a String ``` Note that some casts will be disallowed at compile time, because they will never succeed at all: ``` Integer i = getSomeInteger(); String s = (String) i; // the compiler will not allow this, since i can never reference a String. ```
Using your example, you could do: ``` public void doit(A a) { if(a instanceof B) { // needs to cast to B to access draw2 which isn't present in A // note that this is probably not a good OO-design, but that would // be out-of-scope for this discussion :) ((B)a).draw2(); } a.draw(); } ```
Downcasting in Java
[ "", "java", "casting", "" ]
I want to otherwise block code execution on the main thread while still allowing UI changes to be displayed. I tried to come up with a simplified example version of what I'm trying to do; and this is the best I could come up with. Obviously it doesn't demonstrate the behavior I'm wanting or I wouldn't be posting the question. I just hope it gives some code context to back my poor explanation of the problem I'm hoping to solve. Within a button click handler on a form I have this: ``` private void button2_Click(object sender, EventArgs e) { AutoResetEvent autoResetEvent = new AutoResetEvent(false); new Thread(delegate() { // do something that takes a while. Thread.Sleep(1000); // Update UI w/BeginInvoke this.BeginInvoke(new ThreadStart( delegate() { this.Text = "Working... 1"; this.Refresh(); Thread.Sleep(1000); // gimme a chance to see the new text })); // do something else that takes a while. Thread.Sleep(1000); // Update UI w/Invoke this.Invoke(new ThreadStart( delegate() { this.Text = "Working... 2"; this.Refresh(); Thread.Sleep(1000); // gimme a chance to see the new text })); // do something else that takes a while. Thread.Sleep(1000); autoResetEvent.Set(); }).Start(); // I want the UI to update during this 4 seconds, even though I'm // blocking the mainthread if (autoResetEvent.WaitOne(4000, false)) { this.Text = "Event Signalled"; } else { this.Text = "Event Wait Timeout"; } Thread.Sleep(1000); // gimme a chance to see the new text this.Refresh(); } ``` If I didn't set a timout on the WaitOne() the app would deadlock on the Invoke() call. --- As to why I'd want to do this, I've been tasked with moving one subsystem of an app to do work in a background thread, but still have it block user's workflow (the main thread) only sometimes and for certain types of work related to that subsystem only.
I went with something I haven't seen posted yet which is to use MessageQueues. * The MainThread blocks while waiting for the next message on a queue. * The background thread posts different types of messages to the MessageQueue. * Some of the message types signal the MainThread to update UI elements. * Of course, there is a message to tell the MainThread to stop blocking and waiting for messages. Seems over the top considering the windows message loop already exists somewhere, but it works.
You want to use the "[BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx)" class, which will take most of this pain out of this for you.. but as mentioned before, you'll also want to structure it so that the main thread is updating the UI and the worker is doing the heavy lifting.
In C#, wait on the mainthread while continuing to process UI updates? (.NET 2.0 CF)
[ "", "c#", "multithreading", "" ]
Here is what I am trying to do: Given a date, a day of the week, and an integer `n`, determine whether the date is the `n`th day of the month. For example: * input of `1/1/2009,Monday,2` would be false because `1/1/2009` is not the second Monday * input of `11/13/2008,Thursday,2` would return true because it is the second Thursday How can I improve this implementation? ``` private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n) { int d = date.Day; return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0)); } ```
You could change the check of the week so the function would read: ``` private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){ int d = date.Day; return date.DayOfWeek == dow && (d-1)/7 == (n-1); } ``` Other than that, it looks pretty good and efficient.
The answer is from [this website](http://blog.lab49.com/archives/206). Copy/pasted here in case that site is ever lost. ``` public static DateTime FindTheNthSpecificWeekday(int year, int month,int nth, System.DayOfWeek day_of_the_week) { // validate month value if(month < 1 || month > 12) { throw new ArgumentOutOfRangeException("Invalid month value."); } // validate the nth value if(nth < 0 || nth > 5) { throw new ArgumentOutOfRangeException("Invalid nth value."); } // start from the first day of the month DateTime dt = new DateTime(year, month, 1); // loop until we find our first match day of the week while(dt.DayOfWeek != day_of_the_week) { dt = dt.AddDays(1); } if(dt.Month != month) { // we skip to the next month, we throw an exception throw new ArgumentOutOfRangeException(string.Format("The given month has less than {0} {1}s", nth, day_of_the_week)); } // Complete the gap to the nth week dt = dt.AddDays((nth - 1) * 7); return dt; } ```
How do I determine if a given date is the Nth weekday of the month?
[ "", "c#", ".net", "date", "calendar", "" ]
I am in search for a database with translations so I can have comonly used phrases and words translated by a machine and not by an expensive translator. Is there such a thing as a translation database with words and often used phrases? If you don't know any would you use such a service? edit: the database should only be monitored by people and not some automatic translater since they tend to be VERY bad
Check: [open-tran.eu](http://open-tran.eu/). It is a database of translations taken from various open source projects.
> edit: the database should only be monitored by people and not some automatic translater since they tend to be VERY bad I don't think this is enough. If you're going to translate single words, you need to have some idea of the context in which the word will be used. For instance, consider the english word "row" Does this mean 1. A line of things 2. An argument 3. To move a boat with oars 4. An uproar 5. Several things in succession ("they won four years in a row") These are likely to have very different translations. So instead, it might well be worth keeping a multi-language glossary, where you record the definition of a term and its translation in all the languages you care about, but I think you'll need a professional translator to get the translations right, and the "lookup" will always need to be manual.
Is there something like a translating database for strings?
[ "", "php", "localization", "translation", "" ]
I'm trying to do the following in my Django template: ``` {% for embed in embeds %} {% embed2 = embed.replace("&lt;", "<") %} {{embed2}}<br /> {% endfor %} ``` However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong? Edit: the exact error is: `Invalid block tag: 'embed2'` Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have: ``` embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&lt;", "<")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) ``` However, I now get an error: `'NoneType' object is not callable" on line 35`.
Instead of using a slice assignment to grow a list `embed_list[len(embed_list):] = [foo]` you should probably just do `embed_list.append(foo)` But really you should try unescaping html with a library function rather than doing it yourself. That NoneType error sounds like embed.replace is None at some point, which only makes sense if your list is not a list of strings - you might want to double-check that with some asserts or something similar.
I am quite sure that Django templates does not support that. For your replace operation I would look into different filters. You really should try to keep as much logic as you can in your views and not in the templates.
Syntax error whenever I put Python code inside a Django template
[ "", "python", "django", "templates", "django-templates", "" ]
Is there an easy way to delete an element from an array using PHP, such that `foreach ($array)` no longer includes that element? I thought that setting it to `null` would do it, but apparently it does not work.
There are different ways to delete an array element, where some are more useful for some specific tasks than others. ## Deleting a Single Array Element If you want to delete just one single array element you can use [`unset()`](https://secure.php.net/manual/en/function.unset.php) and alternatively [`array_splice()`](https://secure.php.net/manual/en/function.array-splice.php). ### By key or by value? If you know the value and don't know the key to delete the element you can use [`array_search()`](https://php.net/manual/en/function.array-search.php) to get the key. This only works if the element doesn't occur more than once, since `array_search()` returns the first hit only. ### [`unset()`](https://php.net/manual/en/function.unset.php) Expression Note: When you use `unset()` the array keys won’t change. If you want to reindex the keys you can use [`array_values()`](https://php.net/manual/en/function.array-values.php) after `unset()`, which will convert all keys to numerically enumerated keys starting from 0 (the array remains a [*list*](https://php.net/array_is_list)). Example Code: ``` $array = [0 => "a", 1 => "b", 2 => "c"]; unset($array[1]); // ↑ Key of element to delete ``` Example Output: ``` [ [0] => a [2] => c ] ``` ### [`array_splice()`](https://php.net/manual/en/function.array-splice.php) Function If you use `array_splice()` the (integer) keys will automatically be reindex-ed, but the associative (string) keys won't change — as opposed to `array_values()` after `unset()`, which will convert all keys to numerical keys. Note: `array_splice()` needs the *offset*, not the *key*, as the second parameter; *offset* `= array_flip(array_keys(`*array*`))[`*key*`]`. Example Code: ``` $array = [0 => "a", 1 => "b", 2 => "c"]; array_splice($array, 1, 1); // ↑ Offset of element to delete ``` Example Output: ``` [ [0] => a [1] => c ] ``` `array_splice()`, same as `unset()`, take the array by reference. You don’t assign the return values back to the array. ## Deleting Multiple Array Elements If you want to delete multiple array elements and don’t want to call `unset()` or `array_splice()` multiple times you can use the functions `array_diff()` or `array_diff_key()` depending on whether you know the values or the keys of the elements to remove from the array. ### [`array_diff()`](https://php.net/manual/en/function.array-diff.php) Function If you know the values of the array elements which you want to delete, then you can use `array_diff()`. As before with `unset()` it won’t change the keys of the array. Example Code: ``` $array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"]; $array = array_diff($array, ["a", "c"]); // └────────┘ // Array values to delete ``` Example Output: ``` [ [1] => b ] ``` ### [`array_diff_key()`](https://php.net/manual/en/function.array-diff-key.php) Function If you know the keys of the elements which you want to delete, then you want to use `array_diff_key()`. You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex. Example Code: ``` $array = [0 => "a", 1 => "b", 2 => "c"]; $array = array_diff_key($array, [0 => "xy", "2" => "xy"]); // ↑ ↑ // Array keys of elements to delete ``` Example Output: ``` [ [1] => b ] ``` If you want to use `unset()` or `array_splice()` to delete multiple elements with the same value you can use [`array_keys()`](https://php.net/manual/en/function.array-keys.php) to get all the keys for a specific value and then delete all elements. ### [`array_filter()`](https://www.php.net/manual/en/function.array-filter.php) Function If you want to delete all elements with a specific value in the array you can use `array_filter()`. Example Code: ``` $array = [0 => "a", 1 => "b", 2 => "c"]; $array = array_filter($array, static function ($element) { return $element !== "b"; // ↑ // Array value which you want to delete }); ``` Example Output: ``` [ [0] => a [2] => c ] ```
It should be noted that [`unset()`](http://php.net/unset) will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays: ``` $array = array(0, 1, 2, 3); unset($array[2]); var_dump($array); /* array(3) { [0]=> int(0) [1]=> int(1) [3]=> int(3) } */ $array = array(0, 1, 2, 3); array_splice($array, 2, 1); var_dump($array); /* array(3) { [0]=> int(0) [1]=> int(1) [2]=> int(3) } */ ``` So [`array_splice()`](http://php.net/array_splice) can be used if you'd like to normalize your integer keys. Another option is using [`array_values()`](http://php.net/array_values) after [`unset()`](http://php.net/unset): ``` $array = array(0, 1, 2, 3); unset($array[2]); $array = array_values($array); var_dump($array); /* array(3) { [0]=> int(0) [1]=> int(1) [2]=> int(3) } */ ```
Deleting an element from an array in PHP
[ "", "php", "arrays", "unset", "" ]
I have a string that represents a non indented XML that I would like to pretty-print. For example: ``` <root><node/></root> ``` should become: ``` <root> <node/> </root> ``` Syntax highlighting is not a requirement. To tackle the problem I first transform the XML to add carriage returns and white spaces and then use a [*pre*](http://www.w3.org/TR/html401/struct/text.html#h-9.3.4) tag to output the XML. To add new lines and white spaces I wrote the following function: ``` function formatXml(xml) { var formatted = ''; var reg = /(>)(<)(\/*)/g; xml = xml.replace(reg, '$1\r\n$2$3'); var pad = 0; jQuery.each(xml.split('\r\n'), function(index, node) { var indent = 0; if (node.match( /.+<\/\w[^>]*>$/ )) { indent = 0; } else if (node.match( /^<\/\w/ )) { if (pad != 0) { pad -= 1; } } else if (node.match( /^<\w[^>]*[^\/]>.*$/ )) { indent = 1; } else { indent = 0; } var padding = ''; for (var i = 0; i < pad; i++) { padding += ' '; } formatted += padding + node + '\r\n'; pad += indent; }); return formatted; } ``` I then call the function like this: ``` jQuery('pre.formatted-xml').text(formatXml('<root><node1/></root>')); ``` This works perfectly fine for me but while I was writing the previous function I thought that there must be a better way. So my question is do you know of any better way given an XML string to pretty-print it in an html page? Any javascript frameworks and/or plugins that could do the job are welcome. My only requirement is this to be done on the client side.
From the text of the question **I get the impression that a string result is expected**, as opposed to an HTML-formatted result. If this is so, **the simplest way to achieve this is to process the XML document with the [identity transformation](http://www.w3.org/TR/xslt#copying) and with an [`<xsl:output indent="yes"/>`](http://www.w3.org/TR/xslt#section-XML-Output-Method) instruction**: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> </xsl:stylesheet> ``` When applying this transformation on the provided XML document: ``` <root><node/></root> ``` most XSLT processors (.NET XslCompiledTransform, Saxon 6.5.4 and Saxon 9.0.0.2, AltovaXML) produce the wanted result: ``` <root> <node /> </root> ```
This can be done using [native](https://developer.mozilla.org/en-US/docs/Web/API/XSLTProcessor) javascript tools, without 3rd party libs, extending the @Dimitre Novatchev's answer: ``` var prettifyXml = function(sourceXml) { var xmlDoc = new DOMParser().parseFromString(sourceXml, 'application/xml'); var xsltDoc = new DOMParser().parseFromString([ // describes how we want to modify the XML - indent everything '<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">', ' <xsl:strip-space elements="*"/>', ' <xsl:template match="para[content-style][not(text())]">', // change to just text() to strip space in text nodes ' <xsl:value-of select="normalize-space(.)"/>', ' </xsl:template>', ' <xsl:template match="node()|@*">', ' <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>', ' </xsl:template>', ' <xsl:output indent="yes"/>', '</xsl:stylesheet>', ].join('\n'), 'application/xml'); var xsltProcessor = new XSLTProcessor(); xsltProcessor.importStylesheet(xsltDoc); var resultDoc = xsltProcessor.transformToDocument(xmlDoc); var resultXml = new XMLSerializer().serializeToString(resultDoc); return resultXml; }; console.log(prettifyXml('<root><node/></root>')); ``` Outputs: ``` <root> <node/> </root> ``` [JSFiddle](https://jsfiddle.net/klesun/sgeryvyu/369/) Note, as pointed out by @jat255, pretty printing with [`<xsl:output indent="yes"/>`](https://developer.mozilla.org/en-US/docs/Web/XSLT/Element/output) is not supported by firefox. It only seems to work in chrome, opera and probably the rest webkit-based browsers.
Pretty printing XML with javascript
[ "", "javascript", "xml", "xslt", "pretty-print", "" ]
I'm new to jQuery, and I'm totally struggling with using jQuery UI's `sortable`. I'm trying to put together a page to facilitate grouping and ordering of items. My page has a list of groups, and each group contains a list of items. I want to allow users to be able to do the following: > 1. Reorder the groups > 2. Reorder the items within the groups > 3. Move the items between the groups The first two requirements are no problem. I'm able to sort them just fine. The problem comes in with the third requirement. I just can't connect those lists to each other. Some code might help. Here's the markup. ``` <ul id="groupsList" class="groupsList"> <li id="group1" class="group">Group 1 <ul id="groupItems1" class="itemsList"> <li id="item1-1" class="item">Item 1.1</li> <li id="item1-2" class="item">Item 1.2</li> </ul> </li> <li id="group2" class="group">Group 2 <ul id="groupItems2" class="itemsList"> <li id="item2-1" class="item">Item 2.1</li> <li id="item2-2" class="item">Item 2.2</li> </ul> </li> <li id="group3" class="group">Group 3 <ul id="groupItems3" class="itemsList"> <li id="item3-1" class="item">Item 3.1</li> <li id="item3-2" class="item">Item 3.2</li> </ul> </li> </ul> ``` I was able to sort the lists by putting `$('#groupsList').sortable({});` and `$('.itemsList').sortable({});` in the `document ready function`. I tried using the `connectWith` option for `sortable` to make it work, but I failed spectacularly. What I'd like to do is have the every `groupItemsX` list connected to every `groupItemsX` list but itself. How should I do that? --- I was thinking I needed to specifically not connect a list to itself less there be some sort of circular reference. Granted, I'm not working with Excel, but it seemed like that could cause some sort of never ending recursion that would cause a stack overflow or something. Hmm. Sorry for the pun. Couldn't help myself. Anyway, I was trying to do something like this, and it wasn't working: ``` $('.groupsList').sortable(); // worked great $('.groupsList').each( function () { $(this).sortable( { connectWith: ['.groupsList':not('#'+ $(this).attr('id') )]; }); }); ``` I'm sure I've completely mangled the syntax there, and I suppose that's the reason I had to ask the question in the first place. Is it even necessary or helpful performance-wise to filter the current item out of the list? Both of the answers provided by Adam and JimmyP worked in IE (although they behave really oddly in FireFox, overwriting list items when you try to re-sort). I'll accept one of your answers and vote on the other, but if you have ideas/ suggestions about the filtering, I'd like to hear it.
Can you include the syntax you used for `connectWith`? Did you place the list of other groups inside brackets(even if it's a selector)? That is: ``` ...sortable({connectWith:['.group'], ... } ```
This should work: ``` $('#groupsList').sortable(); $('.itemsList').sortable({ connectWith: $('.itemsList') }); ```
How do I connect multiple sortable lists to each other in jQuery UI?
[ "", "javascript", "jquery", "ajax", "jquery-ui", "jquery-ui-sortable", "" ]
**I am very, very new to MYSQL.I tried to create a table named "option".** **My SQL Query is :** create table option( id int not null primary key auto\_increment, choice varchar(30) ) **While executing this query it shows the following error** Error Code : 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option( id int not null primary key auto\_increment, choice varchar(30) )' at line 1 (0 ms taken) **If I try with the table name as "choice" it is working.** **can we have the table name as "option" in mysql?** thanks
Pick a different name (one that isn't a reserved word in your RDBMS) and save yourself and whoever else might work on it many headaches.
If you want to have a table name Option, you should be able to, just remember that whenever you use the table in a query, you will have to encase it in ` symbols. Like this. ``` `option` ``` The ` key on the top left of your keyboard, with the tilde.
Can we have the table name as "option" in MySQL?
[ "", "sql", "mysql", "database", "" ]
I am using LINQ-to-SQL for an application that queries a legacy database. I need to call a stored procedure, that selects a single integer value. Changing the stored procedure is not an option. The designer creates a method with this signature: ``` private ISingleResult<sp_xal_seqnoResult> NextRowNumber([Parameter(DbType="Int")] System.Nullable<int> increment, [Parameter(DbType="Char(3)")] string dataset) ``` I would like the return type to be int. How do I do this using LINQ-to-SQL ?
This would be trivial with a scalar function (UDF) rather than an SP. However, it should work easily enough - although if the SP is complex (i.e. FMT\_ONLY can't inspect it 100%) then you might need to "help" it... Here's some dbml that I generated from a simplfied SP that returns an integer; you can edit the dbml via "open with... xml editor): ``` <Function Name="dbo.foo" Method="foo"> <Parameter Name="inc" Type="System.Int32" DbType="Int" /> <Parameter Name="dataset" Type="System.String" DbType="VarChar(20)" /> <Return Type="System.Int32" /> </Function> ``` (note you obviously need to tweak the names and data-types). And here is the generated C#: ``` [Function(Name="dbo.foo")] public int foo([Parameter(DbType="Int")] System.Nullable<int> inc, [Parameter(DbType="VarChar(20)")] string dataset) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), inc, dataset); return ((int)(result.ReturnValue)); } ``` If your current SP uses SELECT (instead of RETURN), then the DBML will need to reflect this. You can fix this by hiding the implementation details, and providing a public wrapper in a partial class; for example: ``` <Function Name="dbo.foo" Method="FooPrivate" AccessModifier="Private"> <Parameter Name="inc" Type="System.Int32" DbType="Int" /> <Parameter Name="dataset" Type="System.String" DbType="VarChar(20)" /> <ElementType Name="fooResult" AccessModifier="Internal"> <Column Name="value" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" /> </ElementType> </Function> ``` The above describes an SP that returns a single table with a single column; but I've made the SP "private" to the data-context, and the result-type "internal" to the assembly (hiding it): ``` [Function(Name="dbo.foo")] private ISingleResult<fooResult> FooPrivate( [Parameter(DbType="Int")] System.Nullable<int> inc, [Parameter(DbType="VarChar(20)")] string dataset) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), inc, dataset); return ((ISingleResult<fooResult>)(result.ReturnValue)); } ``` Now *in my own class file* I can add a new partial class (a new .cs file) in the correct namespace, that exposes the method more conveniently: ``` namespace MyNamespace { partial class MyDataContext { public int Foo(int? inc, string dataSet) { return FooPrivate(inc, dataSet).Single().value; } } } ``` (the namespace and context names need to be the same as the actual data-context). This adds a public method that hides the grungy details from the caller. **Don't** edit the designer.cs file directly; your changes will be lost. Only edit either the dbml or partial classes.
RETURN @VALUE as the last statement of the proc. then it will auto detect the type int, string, bool etc and generate the wrapper method accordingly.
LINQ-to-SQL: Stored Procedure that returns a single scalar value?
[ "", "c#", "linq-to-sql", "" ]
I've seen some methods of [checking if a PEFile is a .NET assembly by examining the binary structure](http://www.anastasiosyal.com/archive/2007/04/17/3.aspx). Is that the fastest method to test multiple files? I assume that trying to load each file (e.g. via [Assembly.ReflectionOnlyLoad](http://msdn.microsoft.com/en-us/library/0et80c7k(VS.80).aspx)) file might be pretty slow since it'll be loading file type information. Note: I'm looking for a way to check files programmatically.
Maybe this helps from <https://web.archive.org/web/20110930194955/http://www.grimes.demon.co.uk/dotnet/vistaAndDotnet.htm> > Next, I check to see if it is a .NET assembly. To do this I check to see if the file contains the CLR header. This header contains important information about the location of the .NET code in the file and the version of the framework that was used to write that code. The location of this header is given in the file's Data Directory table. If the data directory item has zero values then the file is unmanaged, if it has non-zero values then the file is a .NET assembly. > > You can test this yourself using the dumpbin utility with the /headers switch. This utility will print the various headers in a file on the command line. At the end of the Optional Header Values you'll see a list of the Data Directories (there will always be 16 of them) and if the COM Descriptor Directory has a non-zero location it indicates that the file is a .NET assembly. The contents of the CLR header can also be listed using the /clrheader switch (if the file is unmanaged this will show no values). XP tests for the CLR header when it executes a file and if the CLR header is present it will initialize the runtime and pass the entry point of the assembly to the runtime, so that the file runs totally within the runtime.
I guess Stormenet's answer isn't technically *programmatic*, so I'll seperate my response into an answer. For best performance, nothing is going to beat opening the file(s) with a `StreamReader`, reading the first (n) bytes and checking for the .NET file signature data structures in the byte stream. Pretty much the same way you'd verify something is a DOS executable: <http://en.wikipedia.org/wiki/DOS_executable> Look for the "MZ" header bytes, which also happen to be the initials of Mark Zbikowski, one of the developers of MS-DOS..
Checking if a file is a .NET assembly
[ "", "c#", ".net", "reflection", "clr", "" ]
Is tight looping in a program bad? I have an application that has two threads for a game-physics simulator. An updateGame thread and a render thread. The render thread is throttled by causing the thread to sleep for some milliseconds (to achieve the frame-rate I want) and the updateGame thread (that updates my in game objects positions based off some physics equations) was previously throttled by a 10 millisecond sleep. However, I recently unthrottled the updateGame thread and the simulation of my objects movement seems to be significantly more realistic now that I have taken out that 10ms sleep. Is it bad to hot loop or have a tight loop? ``` private class UpdateTask implements Runnable { private long previousTime = System.currentTimeMillis(); private long currentTime = previousTime; private long elapsedTime; public void run() { while(true) { currentTime = System.currentTimeMillis(); elapsedTime = (currentTime - previousTime); // elapsed time in seconds updateGame(elapsedTime / 1000f); try { Thread.currentThread().sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } previousTime = currentTime; } } } ``` In this example I'm just sleeping for 1ms (and from my understanding with how millisecond accuracy and the sleep function works this is probably more like 5-10ms. If I sleep for any more than this it starts to have impacts on the accuracy of my collision detection and physics model. Is it a bad practice to have tight loops or loops with 1ms sleeps in them? Is there something else I should do instead?
I read a really great post about efficiently and effectively executing physics calculations loop: [Fix Your Timestep!](http://gafferongames.com/game-physics/fix-your-timestep/) When a game is running that is usually the main application that the user cares about so tight looping is not that big of a deal. What you really should do though schedule your updates. You should know how long -- at your target framerate -- that your frame has to execute. You should measure the time that your frame took and only sleep for the time that your frame took minus that known frame time. That way your system will lock into a frame rate and not vary with the amount of time that your frame takes to render. Another thing is that I don't believe that Thread.sleep has a very good resolution, well over 5 milliseconds, you may want to look for a more accurate timer available for Java.
It's only "bad" if it has an adverse impact on something else in your system. Rather than sleeping for 1ms, you might block on a condition that warrants updating, with a minimum of 1ms. That way you'll always sleep for at least 1ms, and longer if there's nothing to do.
Is tight looping bad?
[ "", "java", "" ]
I have my main GUI thread, and a second thread running inside it's own ApplicationContext (to keep it alive, even when there is no work to be done). I want to call a method on my 2nd thread from my GUI thread, but if I just call thread.Method(); it seems to be running on my main GUI thread and causes my GUI to become unresponsive. What is the best way to call methods on different threads? **Update:** What I'm really looking to do here is communicate between 2 threads, not communicate with a GUI. The GUI just happens to be one of the threads that will need to communicate with my 2nd thread. **Update #2:** Ok, I must really be missing something. I created an event and a delegate and had my worker thread subscribe to the event. But when I call Invoke(MyEvent); from my GUI thread the work that the worker thread does ends up being on the GUI thread and hangs the GUI thread until it's done processing. Is what I'm trying to do even possible, without polling on a static object?
.Net already comes with a `System.ComponentModel.BackgroundWorker` class specifically to handle performing background tasks and communicating with a GUI. Use it.
Wow, I can't believe how may people didn't bother reading the question. Anyways, this is what I do. 1. Create you "message" classes. This stores all the information you want to share. 2. Create a Queue<T> for each thread. Use a SyncLock (C# lock) to read/write to it. 3. When you want to talk to a thread, send it a message object with a **copy** of all the information it needs by adding the message to the queue. 4. The worker thread can then read from the queue, reading and processing each message in order. When there are no messages, simply sleep. Make sure that you don't share objects between the two threads. Once your GUI thread sticks a message in the Queue, the GUI thread no longer owns the message. It cannot hold a reference to the message, or you will get yourself into trouble. This won't give you the best possible performance, but it will be good enough for most applications. And more importantly, it will make it much harder to make a mistake. UPDATE: Don't use a SyncLock and Queue. Instead use a ConcurrentQueue, which will handle any locking automatically for you. You'll get better performance and are less likely to make a mistake.
In C# what is the recommended way of passing data between 2 threads?
[ "", "c#", "multithreading", "" ]
What is the correct syntax to create objects in javascript that will work across the majority of web browsers (by that I mean : IE 6+, Firefox 2+, Opera 9+ ) Is this valid ``` var a = { "class": "Person", "name": "William Shakespeare", "birthday": -12802392000000, "nickname": "Bill" }; ``` Or is this: ``` var a = { class: "Person", name: "William Shakespeare", birthday: -12802392000000, nickname: "Bill" }; ``` And what is the difference between the two?
[@AndreasN is correct](https://stackoverflow.com/questions/380855/json-syntax-for-property-names#380860): the [JSON specification](http://www.json.org/) dictates the use of quotes in order for it to actually be JSON. If you don't use quotes, it may be a valid object literal in Javascript, but it is not JSON. Other services besides browser-side Javascript use JSON (e.g. webservices using php, Java, etc.) and if you construct a string that lacks the quotes, there is no guarantee that it will be parsed correctly -- although I suspect most implementations would be robust enough to do so. FYI it is dangerous in Javascript to directly use eval() on JSON strings from sources which you cannot prevent malicious attacks. Again, see the [JSON site](http://www.json.org/js.html) which gives more of an explanation as well as a very short javascript file which safely parses JSON strings into Javascript objects. **edit:** I guess technically your original question is not about JSON but rather the Javascript's syntax for **object literals**. The difference is that objects constructable from a JSON string will exclude many other possible object literals, e.g.: ``` var a = {cat: "meow", dog: "woof"}; var aname = {cat: "Garfield", dog: "Odie"}; var b = { counter: 0, pow: function(x) { return x+1; }, zap: function(y) { return (counter += y); } }; var c = { all: [a,aname], animals: a, names: aname, }; ``` Object literals "a" and "aname" can be expressed in JSON (by adding quotes to the property names). But object literals "b" and "c" cannot. Object literal "b" contains functions (not allowed in JSON). Object literal "c" above contains references to other variables in a way that is not representable in JSON because some of the references are shared. If you make a change to `c.names` it will also change `c.all[1]` since they share a reference to the same variable. JSON can only express objects that have a tree structure (e.g. each sub-element of the overall object is independent).
The [spec](http://www.json.org/) say to use "". Firefox accept without, but IE doesn't. Pair is defined as ``` string : value ``` Value can be a string string is defined as ``` " chars " ```
JSON syntax for property names
[ "", "javascript", "json", "syntax", "" ]
Is there a Pythonic way to have only one instance of a program running? The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? (Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)
The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux. ``` from tendo import singleton me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running ``` The latest code version is available [singleton.py](https://github.com/pycontribs/tendo/blob/master/tendo/singleton.py). Please [file bugs here](https://github.com/pycontribs/tendo/issues). You can install tend using one of the following methods: * `easy_install tendo` * `pip install tendo` * manually by getting it from <http://pypi.python.org/pypi/tendo>
Simple, ~~cross-platform~~ solution, found in **[another question](https://stackoverflow.com/questions/220525/ensuring-a-single-instance-of-an-application-in-linux#221159)** by [zgoda](https://stackoverflow.com/users/12138/zgoda): ``` import fcntl import os import sys def instance_already_running(label="default"): """ Detect if an an instance with the label is already running, globally at the operating system level. Using `os.open` ensures that the file pointer won't be closed by Python's garbage collector after the function's scope is exited. The lock will be released when the program exits, or could be released if the file pointer were closed. """ lock_file_pointer = os.open(f"/tmp/instance_{label}.lock", os.O_WRONLY) try: fcntl.lockf(lock_file_pointer, fcntl.LOCK_EX | fcntl.LOCK_NB) already_running = False except IOError: already_running = True return already_running ``` A lot like S.Lott's suggestion, but with the code.
Make sure only a single instance of a program is running
[ "", "python", "process", "locking", "mutual-exclusion", "" ]
I am working on someone else's PHP code and seeing this pattern over and over: (pseudocode) ``` result = SELECT blah1, blah2, foreign_key FROM foo WHERE key=bar if foreign_key > 0 other_result = SELECT something FROM foo2 WHERE key=foreign_key end ``` The code needs to branch if there is no related row in the other table, but couldn't this be done better by doing a LEFT JOIN in a single SELECT statement? Am I missing some performance benefit? Portability issue? Or am I just nitpicking?
There is not enough information to really answer the question. I've worked on applications where decreasing the query count for one reason and increasing the query count for another reason *both* gave performance improvements. In the same application! For certain combinations of table size, database configuration and how often the foreign table would be queried, doing the two queries can be much faster than a LEFT JOIN. *But experience and testing is the only thing that will tell you that*. MySQL with moderately large tables seems to be susceptable to this, IME. Performing three queries on one table can often be much faster than one query JOINing the three. I've seen speedups of an order of magnitude.
This is definitely wrong. You are going over the wire a second time for no reason. DBs are very fast at their problem space. Joining tables is one of those and you'll see more of a performance degradation from the second query then the join. Unless your tablespace is hundreds of millions of records, this is not a good idea.
LEFT JOIN vs. multiple SELECT statements
[ "", "sql", "" ]
I am not able to use the breakpoint in Studio with Javascript. I'm able to debug if I use the debugger; I've seen this [Breakpoint not hooked up when debugging in VS.Net 2005](https://stackoverflow.com/questions/163133/breakpoint-not-hooked-up-when-debugging-in-vsnet-2005) question already. I tried the answer and it didn't work. Looking in the Modules window, V.Mvc.Jobtrakt.PDB is loaded properly, but it points to a temp folder C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\dbc0c0c5\f64a99b3\assembly\dl3\9de055b3\eb1303b1\_9760c901\V.Mvc.Jobtrak.pdb: Symbols loaded. I would have thought that it would point to: \JobTrak\Website\V.Mvc.Jobtrak\V.Mvc.Jobtrak\obj\Debug ( this is within the project directory) But regardless of the location I closed VS 2008 and then blew away the temp folder (listed above), the bin and obj folders. Opened VS 2008 and did a clean. I set a break point in the js and it seemed like it would work now ( The breakpoint was filled in) Started to debug and it never breaks on the breakpoint. Look at the break point and it now is a red circle with a red dot and a warning indicator. Hovering over the breakpoint gives me this useful information: The breakpoint will not currently be hit. The location could not be mapped to a client side script. See help for ASPX Breakpoint mapping. I am not being redirected, the breakpoint is with in a function. blah blah blah this should be working. So I was wondering if anyone has any ideas? Is anyone able to set breakpoints in VS2008 and have them work?
try typing "debugger" in the source where you want to break
Make sure you are attached to the correct process. For example, once you have your page loaded in IE, 1. Switch to Visual Studio and go to the Debug menu. 2. Choose "Attach to Process" 3. Find iexplore in the list and select it. 4. Click the "Select..." button. 5. In the dialog, choose "Debug these code types:" and select **only** "Script". 6. Click "OK" 7. Click "Attach" See if that helps get you debugging javascript.
Using breakpoints to debug Javascript in IE and VS2008
[ "", "javascript", "visual-studio-2008", "breakpoints", "" ]
Below is a stored procedure to check if there is a duplicate entry in the database based upon checking all the fields individually (don't ask why I should do this, it just has to be this way). It sounds perfectly straightforward but the SP fails. The problem is that some parameters passed into the SP may have a null value and therefore the sql should read "is null" rather than "= null". I have tried isnull(),case statements,coalesce() and dynamic sql with exec() and sp\_executesql and failed to implement any of these. Here is the code... ``` CREATE PROCEDURE sp_myDuplicateCheck @userId int, @noteType char(1), @aCode char(3), @bCode char(3), @cCode char(3), @outDuplicateFound int OUT AS BEGIN SET @outDuplicateFound = (SELECT Top 1 id FROM codeTable WHERE userId = @userId AND noteType = @noteType AND aCode = @aCode AND bCode = @bCode AND cCode = @cCode ) -- Now set the duplicate output flag to a 1 or a 0 IF (@outDuplicateFound IS NULL) OR (@outDuplicateFound = '') OR (@outDuplicateFound = 0) SET @outDuplicateFound = 0 ELSE SET @outDuplicateFound = 1 END ```
I think you need something like this for each possibly-null parameter: ``` AND (aCode = @aCode OR (aCode IS NULL AND @aCode IS NULL)) ```
If I understand your question correctly, then I encourage you to do a little research on: ``` SET ANSI_NULLS OFF ``` If you use this command in your stored procedure, then you can use = NULL in your comparison. Take a look at the following example code to see how this works. ``` Declare @Temp Table(Data Int) Insert Into @Temp Values(1) Insert Into @Temp Values(NULL) -- No rows from the following query select * From @Temp Where Data = NULL SET ANSI_NULLS OFF -- This returns the rows where data is null select * From @Temp Where Data = NULL SET ANSI_NULLS ON ``` Whenever you SET ANSI\_NULLS Off, it's a good practice to set it back to ON as soon as possible because this may affect other queries that you run later. All of the SET commands only affect the current session, but depending on your application, this could span multiple queries, which is why I suggest you turn ansi nulls back on immediately after this query.
T-SQL Stored Procedure NULL input values cause select statement to fail
[ "", "sql", "t-sql", "stored-procedures", "parameters", "null", "" ]
I'm trying to setup Spring using Hibernate and JPA, but when trying to persist an object, nothing seems to be added to the database. Am using the following: ``` <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="persistenceUnitName" value="BankingWeb" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="generateDdl" value="true" /> <property name="showSql" value="true" /> <property name="databasePlatform" value="${hibernate.dialect}" /> </bean> </property> </bean> <tx:annotation-driven/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/> <bean name="accountManager" class="ssel.banking.dao.jpa.AccountManager" /> <bean name="userManager" class="ssel.banking.dao.jpa.UserManager" /> ``` And in AccountManager, I'm doing: ``` @Repository public class AccountManager implements IAccountManager { @PersistenceContext private EntityManager em; /* -- 8< -- Query methods omitted -- 8< -- */ public Account storeAccount(Account ac) { ac = em.merge(ac); em.persist(ac); return ac; } } ``` Where ac comes from: ``` Account ac = new Account(); ac.setId(mostRecent.getId()+1); ac.setUser(user); ac.setName(accName); ac.setDate(new Date()); ac.setValue(0); ac = accountManager.storeAccount(ac); return ac; ``` Is there anyone who can point out what I'm doing wrong? The persist call returns without throwing exceptions. If afterwards I do `em.contains(ac)`, this returns true. In case anyone needed, here's how Account is defined: ``` @SuppressWarnings("serial") @Entity @NamedQueries({ @NamedQuery(name = "Account.AllAccounts", query = "SELECT a FROM Account a"), @NamedQuery(name = "Account.Accounts4User", query = "SELECT a FROM Account a WHERE user=:user"), @NamedQuery(name = "Account.Account4Name", query = "SELECT a FROM Account a WHERE name=:name"), @NamedQuery(name = "Account.MaxId", query = "SELECT MAX(a.id) FROM Account a"), @NamedQuery(name = "Account.Account4Id", query = "SELECT a FROM Account a WHERE id=:id"), }) public class Account extends AbstractNamedDomain { @Temporal(TemporalType.DATE) @Column(name = "xdate") private Date date; private double value; @ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE}) @JoinColumn(name="userid") private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER) @OrderBy("date") private List<AccountActivity> accountActivity = new ArrayList<AccountActivity>(); public List<AccountActivity> getAccountActivity() { return accountActivity; } public void setAccountActivity(List<AccountActivity> accountActivity) { this.accountActivity = accountActivity; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public void addAccountActivity(AccountActivity activity) { // Make sure ordering is maintained, JPA only does this on loading int i = 0; while (i < getAccountActivity().size()) { if (getAccountActivity().get(i).getDate().compareTo(activity.getDate()) <= 0) break; i++; } getAccountActivity().add(i, activity); } } @MappedSuperclass public abstract class AbstractNamedDomain extends AbstractDomain { private String name; public AbstractNamedDomain() { } public AbstractNamedDomain(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @MappedSuperclass public abstract class AbstractDomain implements Serializable { @Id @GeneratedValue private long id = NEW_ID; public static long NEW_ID = -1; public long getId() { return id; } public void setId(long id) { this.id = id; } public boolean isNew() { return id==NEW_ID; } } ```
Thanks to eric and Juan Manuel's answers, I was able to figure out that the transaction wasn't committed. Adding @Transactional to the storeAccount method did the trick!
I actually came across another way that this can happen. In an injected EntityManager, no updates will ever occur if you have persistence.xml specified like this: `<persistence-unit name="primary" transaction-type="RESOURCE_LOCAL">` You need to remove the transaction-type attribute and just use the default which is JTA.
Spring, Hibernate & JPA: Calling persist on entitymanager does not seem to commit to database
[ "", "java", "hibernate", "spring", "jpa", "persistence", "" ]
I am thinking about a DB Design Problem. For example, I am designing this stackoverflow website where I have a list of Questions. Each Question contains certain meta data that will probably not change. Each Question also contains certain data that will be consistently changing (Recently Viewed Date, Total Views...etc) Would it be better to have a Main Table for reading the constant meta data and doing a join and also keeping the changing values in a different table? OR Would it be better to keep everything all in one table. I am not sure if this is the case, but when updating, does the ROW lock?
When designing a database structure, it's best to [normalize](http://en.wikipedia.org/wiki/Database_normalization) first and change for performance after you've profiled and benchmarked your queries. Normalization aims to prevent data-duplication, increase integrity and define the correct relationships between your data. Bear in mind that performing the join comes at a cost as well, so it's hard to say if your idea would help any. Proper indexing with a normalized structure would be much more helpful. And regarding row-level locks, that depends on the storage engine - some use row-level locking and some use table-locks.
Your initial database design should be based on conceptual and relational considerations only, completely indepedent of physical considerations. Database software is designed and intended to support good relational design. You will hardly ever need to relax those considerations to deal with performance. Don't even think about the costs of joins, locking, and activity type at first. Then further along, put off these considerations until all other avenues have been explored. Your rdbms is your friend, not your adversary.
DB Design: Does having 2 Tables (One is optimized for Read, one for Write) improve performance?
[ "", "sql", "database-design", "" ]
Obviously I can do and `DateTime.Now.After` - `DateTime.Now.Before` but there must be something more sophisticated. Any tips appreciated.
[System.Environment.TickCount](http://msdn.microsoft.com/en-us/library/system.environment.tickcount.aspx) and the [System.Diagnostics.Stopwatch](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) class are two that work well for finer resolution and straightforward usage. See Also: * [Is DateTime.Now the best way to measure a function’s performance?](https://stackoverflow.com/questions/28637/is-datetimenow-the-best-way-to-measure-a-functions-performance) * [High resolution timer in .NET](https://stackoverflow.com/questions/163022/high-resolution-timer-in-net) * [Environment.TickCount vs DateTime.Now](https://stackoverflow.com/questions/243351/environmenttickcount-vs-datetimenow) * [What’s the best way to benchmark programs in Windows?](https://stackoverflow.com/questions/145103/whats-the-best-way-to-benchmark-programs-in-windows)
I would definitely advise you to have a look at `System.Diagnostics.Stopwatch` And when I looked around for more about Stopwatch I found this site; [Beware of the stopwatch](http://kristofverbiest.blogspot.com/2008/10/beware-of-stopwatch.html) There mentioned another possibility > Process.TotalProcessorTime
What is the best way to measure execution time of a function?
[ "", "c#", "performance", "benchmarking", "execution-time", "" ]
As a "look under the covers" tutorial for myself I am building a PHP script to gather emails from a POP3 mailbox. While attempting to make use of binary attachments I am stuck trying to figure out what to do with the attachment information. Given a string that would be gathered from an email: > ------=\_Part\_16735\_17392833.1229653992102 > Content-Type: image/jpeg; name=trans2.jpg > Content-Transfer-Encoding: base64 > X-Attachment-Id: f\_fow87t5j0 > Content-Disposition: attachment; filename=trans2.jpg > > /9j/4AAQSkZJRgABAgEASABIAAD/4QxrRXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEaAAUA > AAABAAAAYgEbAAUAAAABAAAAagEoAAMAAAABAAIAAAExAAIAAAAUAAAAcgEyAAIAAAAUAAAAhodp > > (...) > > EAgEAgEAgEAgEAg8IBQRL/Lbe/tJrScHqZ2lkmE4XUP2XcSDZZ2VvZ28dtbsDIYmhkbRxAIJCAQC > AQCAQf/ScyAQCAQCAQCAQCAQCAQCAQCAQCAQCAQf/9k= > ------=\_Part\_16735\_17392833.1229653992102-- Is there a way to save off the data to disk so that it would be in a usable format?
Pass the data to [base64\_decode()](http://php.net/base64_decode) to get the binary data, write it out to a file with [file\_put\_contents()](http://php.net/file_put_contents)
If you have a lot of data to write out that needs to be decoded before writing I would suggest using stream filters so decode the data as you write it... ``` $fh = fopen('where_you_are_writing', 'wb'); stream_filter_append($fh, 'convert.base64-decode'); // Do a lot of writing here. It will be automatically decoded from base64. fclose($h); ```
Saving a Base64 string to disk as a binary using PHP
[ "", "php", "binary", "base64", "" ]
In the application I'm writing using a combination of development environments and languages, I have need of accessing a cookie from two different subdomains, each on a separate host. The cookie is being set on `www.mydomain.com` using the PHP code that follows, and I'm attempting to access it from `distant.mydomain.com` on a separate host. ``` setcookie('token', base64_encode(serialize($token)), time()+10800, '/', '.mydomain.com'); ``` I'm trying to access the cookie from `distant.mydomain.com` using the following code: ``` if (isset($_COOKIE['token'])) { /* do stuff */ } ``` **The problem: `distant.mydomain.com` is not finding the cookie.** The `if` statement just mentioned returns false, even though the cookie exists. I have verified that the cookie that is set is for `mydomain.com` (by checking my Firefox cookies). I can't think of any reason this wouldn't be working. Using the same `setcookie` code, I have an old application running exclusively on the `www.mydomain.com` host, and that application is able to access the cookie across domains. This makes me suspect that the problem has to do with separate hosts. Just in case any of the following information is pertinent: - `www.mydomain.com` is IIS 6.0 - `distant.mydomain.com` is Apache 2.2.9 - Both servers use PHP 5.2.x - Both servers are operating on Windows Server 2003 If there is any further information I can provide in order to better describe the problem, please let me know!
For the benefit of anyone reading this question the code and information contained in the original post are exactly correct and work fine. The problem is when you introduce other technology. For instance, **I have since learned that sending PHP code through a Python module, one that allows Django to serve PHP files/content, changes a great deal about what is accessible to the script and what is not.** This was eventually discovered following the advice of [Marc Novakowski](https://stackoverflow.com/users/27020/marc-novakowski), who suggested sending `$_COOKIE` to the log in order to find out what was there. I also checked out `$_SERVER` and `$_GET`. It was the emptiness of `$_GET` that tipped me off that the setup I am attempting to use is not as straightforward as I had thought. It was that mistaken understanding that led to not including the information about Django in the original post. Apologies *and* thanks to all who responded to this question!
Cookies set in domain `'.aaa.sub.domain.com'` will collide with identically named cookies set in domain `'.sub.domain.com'` and `'.some.stupidly.obscure.multi.sub.domain.com'` That means (and this took some time to wade thru) if you're going to use the same-named cookie across multiple domains, you must set it once (and once only) in the main/base domain, in this case '.domain.com'; otherwise, the resulting cookie will be indeterminantly and randomly returned arrived at, sometimes the cookie 'jasper' set in .a.sub.domain.com, sometimes the cookie 'jasper' set in .sub.domain.com, sometimes the cookie 'jasper' set in .b.c.d.domain.com, sometimes the cookie 'jasper' set in '.sub.domain.com' and sometimes the cookie 'jasper' set in '.domain.com'
Cookies across subdomains and hosts
[ "", "php", "django", "apache", "iis", "cookies", "" ]
Can I load an stand alone aspx page in another stand alone aspx page using System.Reflection? I am using the ASP.NET 2.0 Web site project model.
Try using [BuildManager.CreateInstanceFromVirtualPath](http://msdn.microsoft.com/en-us/library/system.web.compilation.buildmanager.createinstancefromvirtualpath.aspx). Sample usage: ``` Page p = BuildManager.CreateInstanceFromVirtualPath("~/Default.aspx", typeof(Page)) ``` This answers this specific question, although, based on your comments, I'm not sure that this is what you really want.
Don't know about doing it using Reflection, which may well be possible, but you can capture the output of an aspx or asp page to a string writer using HttpContext.Server.Execute(). I have used this for rendering some complex email templates, but don't know if that is quite what you are after.
Load an ASP.NET 2.0 aspx page using System.Reflection?
[ "", "c#", "asp.net", "reflection", "system.reflection", "" ]
Between [Yahoo! UI Compressor](http://developer.yahoo.com/yui/compressor/), [Dean Edwards Packer](http://dean.edwards.name/packer/) and [jsmin](http://www.crockford.com/javascript/jsmin.html), which produces better results, both in terms of resulting footprint and fewer errors when obfuscating.
Better is a bit subjective here, since there are multiple factors to consider (even beyond those you list): 1. Compressed size doesn't tell the whole story, since an aggressive compressor can result in slower run-time performance due to the additional time needed to run unpacking code prior to browser interpretation. * Errors are easiest to avoid when you control the input code - judicious use of semicolons goes a long way. Run JSLint over your code, and fix any problems reported. * The style and size of the code itself will affect the results, of course. * And finally, it's worth keeping in mind that server-side gzip compression will always result in a smaller download than any code compression, although some code compression tools will combine with gzip more effectively. My recommendation is to run the code you intend to compress through several compressors (an automated comparison tool such as [CompressorRater](http://compressorrater.thruhere.net/) helps...), and choose based on the results - remembering to test, profile and compare the actual page load times afterward.
A great way to compare the best compressors is [The JavaScript CompressorRater](http://compressorrater.thruhere.net/) by Arthur Blake. What you're usually interested in is the size after compressing with GZIP (you should configure your web server to perform the compression). The best results are usually from the [YUI Compressor](http://developer.yahoo.com/yui/compressor/) or [Dojo ShrinkSafe](http://dojotoolkit.org/docs/shrinksafe). The differences were so small that after a while I stopped comparing and I just use the YUI Compressor. **EDIT:** since the original time this question was asked, 2 new minifiers have been released. They're both usually at least as good as, if not better than, the YUI Compressor. * Google's [Closure Compiler](http://code.google.com/closure/compiler/). Includes an aggressive [advanced optimization](http://code.google.com/closure/compiler/docs/api-tutorial3.html) mode that's sometimes applicable. * Microsoft's Ajax Minifier (search [this page](http://aspnet.codeplex.com/releases) for "minifier") **EDIT 2:** * [UglifyJS](https://github.com/mishoo/UglifyJS), chosen by the jQuery team for the official 1.5 release
Which javascript minification library produces better results?
[ "", "javascript", "benchmarking", "jscompress", "minify", "" ]
Let's say I have a simple chunck of XML:- ``` <root> <item forename="Fred" surname="Flintstone" /> <item forename="Barney" surname="Rubble" /> </root> ``` Having fetched this XML in Silverlight I would like to bind it with [XAML](http://en.wikipedia.org/wiki/Extensible_Application_Markup_Language) of this ilke:- ``` <ListBox x:Name="ItemList" Style="{StaticResource Items}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBox Text="{Binding Forename}" /> <TextBox Text="{Binding Surname}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ``` Now I can bind simply enough with LINQ to XML and a nominal class:- ``` public class Person { public string Forename {get; set;} public string Surname {get; set;} } ``` Can it be done without this class? In other words, coupling between the Silverlight code and the input XML is limited to the XAML only, other source code is agnostic to the set of attributes on the item element. **Edit**: The use of XSD is suggested but ultimately it amounts the same thing. XSD->Generated class. **Edit**: An anonymous class doesn't work, Silverlight can't bind them. **Edit**: This needs to be two way, the user needs to be able to edit the values and these values end up in the XML. (Changed original TextBlock to TextBox in sample above.)
See *[Binding to Anonymous types in Silverlight](http://grahammurray.wordpress.com/2010/05/30/binding-to-anonymous-types-in-silverlight/)* for information.
You can do this with an IValueConverter. Here is a simple one: ``` public class XAttributeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var xml = value as XElement; var name = parameter as string; return xml.Attribute(name).Value; } } ``` Then in your Xaml you can reference the type converter and pass the attribute name as the parameter: ``` <ListBox x:Name="ItemList"> <ListBox.Resources> <local:XAttributeConverter x:Name="xcvt" /> </ListBox.Resources> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Converter={StaticResource xcvt}, ConverterParameter=forename}" /> <TextBlock Text="{Binding Converter={StaticResource xcvt}, ConverterParameter=surname}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ``` This is when you bind to the xml loaded in an XElement: ``` XElement xml = XElement.Parse("<root><item forename='Fred' surname='Flintstone' /><item forename='Barney' surname='Rubble' /></root>"); ItemList.ItemsSource = xml.Descendants("item"); ``` Not a super elegant binding syntax, but it does work and is easier than mapping to classes.
Binding XML in Silverlight without nominal classes
[ "", "c#", "xml", "silverlight", "linq-to-xml", "xml-binding", "" ]
I am using a program that talks to my COMM port, but I have made another program that I want to "sniff" the comm port messages and perform it's own actions against those messages in addition. Is this possible in .NET c#?
There are third party libraries/tools/products that expose the traffic f you are interested. Here is one I used for serial port emulation - but I think it provides something you can use: <http://com0com.sourceforge.net/>
If you have control over the first program that talks to you COMM port, why not change the program to pass data received from the port to the 2nd program of yours via remoting or any other type of IPC. Better still if you can write a proxy program that connected to the COMM port, and have 2 of the other program talk to this proxy to get the communication done. Another idea is, if you need to sniff only incoming data, you can get a Y-cable (splitter) and connect to 2 COMM port, each program connects to each COMM port. But you need to make sure the 2nd program is not trying to transmit. In some cases you might need a splitter which only connects the RX pin for the 2nd output. Let me know if you need the diagram. If you don't have 2 COMM, you can easily get a USB-Serial Converter for less than USD10.
In C# how could I listen to a COM (Serial) Port that is already open?
[ "", "c#", "serial-port", "listener", "sniffing", "" ]
I have 2 wav files that I want to concatenate into one file with the two sound tracks. Is there any api for that task or some built in commands in .NET that can I can use in some genius way to make this task possible? Many thanks for the help. :)
If I'm not mistaken, you can just append the bytes from the second file to the end of the first. If there is any header data, you'll want to exclude that (see [here](http://filext.com/file-extension/WAV)) Be advised that you may hear a click or pop between the two clips, as there will be no blending. You could probably get around this by fading (gradually reducing the values for the last few ms to the center value).
If you only need to do this once then your best bet is to use some software specifically for the task. [Praat](http://www.fon.hum.uva.nl/praat/) or [audacity](http://audacity.sourceforge.net/) will do this (join or merge two tracks). Praat can also be scripted so it is possible to script Praat and then call Praat and the script from within a .Net application. Rob
How to concatenate WAV files in C#
[ "", "c#", "merge", "wav", "" ]
I googled for this for a while but can't seem to find it and it should be easy. I want to append a CR to then end of an XML file that I am creating with a Transformer. Is there a way to do this> I tried the following but this resulted in a blank file? ``` Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "file:///ReportWiz.dtd"); xformer.transform(source, result); OutputStream writer = new FileOutputStream(file); Byte b = '\n'; writer.write(b); writer.close(); ```
Simple... just add the [append](http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,%20boolean)) option: ``` new FileOutputStream(f, true /* append */); ```
There are a couple of options here. I assume that your result is a `StreamResult` that you are creating with a `String` specifying the destination file path. You might consider opening a `FileOutputStream` yourself, and constructing your `StreamResult` with that. Then, when the transformer is done, append the line terminator, flush, and close the stream. In the absence of constraints otherwise, I would use this approach. If you want to re-open the file, as shown in the question, you'll need to use a `FileOutputStream` constructor that takes the optional [`append`](http://java.sun.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.lang.String,%20boolean)) argument. Set this to `true` to avoid clobbering the result of the transform that was just completed. You might also explore setting the [`indent`](http://java.sun.com/javase/6/docs/api/javax/xml/transform/OutputKeys.html#INDENT) output property in your transform, or including the necessary line terminator directly in your template.
java append to file
[ "", "java", "xml", "xslt", "jaxp", "transformer-model", "" ]
Hi I have a JSON object that is a 2-dimentional array and I need to pass it to PHP using Ajax.Request (only way I know how). ...Right now I manually serialized my array using a js function...and get the data in this format: s[]=1&d[]=3&[]=4 etc. .... my question is: Is there a way to pass the JSON object more directly/efficientely?..instead of serializing it myself? Thanks for any suggestions, Andrew
You can also use Prototype's function [toJSON()](http://www.prototypejs.org/api/array/tojson) to convert an array into a JSON object. After passing it to server via Ajax call, simply use PHP's function [json\_decode()](http://us.php.net/json_decode) to decode the object.
Pass the object as a JSON-string to PHP, and in PHP use the builtin json\_decode to get a PHP-object from the string. In Javascript, use a "stringify" function on your object to get it as a string, library available for example here: <https://github.com/douglascrockford/JSON-js/blob/master/json2.js>
Best way to pass JSON from Browser to PHP using Ajax.Request
[ "", "php", "json", "prototypejs", "ajax.request", "" ]
``` void some_func(int param = get_default_param_value()); ```
Default parameter can be a subset of the full set of expressions. It must be bound at compile time and at the place of declaration of the default parameter. This means that it can be a function call or a static method call, and it can take any number of arguments as far as they are constants and/or global variables or static class variables, but not member attributes. The fact that it is bound at compile time and in the place where the function is declared also means that if it makes use of a variable, that variable will be used even if a different variable shadows the original at the place of the function call. ``` // Code 1: Valid and invalid default parameters int global = 0; int free_function( int x ); class Test { public: static int static_member_function(); int member_function(); // Valid default parameters void valid1( int x = free_function( 5 ) ); void valid2( int x = free_function( global ) ); void valid3( int x = free_function( static_int ) ); void valid4( int x = static_member_function() ); // Invalid default parameters void invalid1( int x = free_function( member_attribute ) ); void invalid2( int x = member_function() ); private: int member_attribute; static int static_int; }; int Test::static_int = 0; // Code 2: Variable scope int x = 5; void f( int a ); void g( int a = f( x ) ); // x is bound to the previously defined x void h() { int x = 10; // shadows ::x g(); // g( 5 ) is called: even if local x values 10, global x is 5. } ```
They don't have to be! A default parameter can be any expression within certain limitations. It is evaluated every time the function is called.
Must default function parameters be constant in C++?
[ "", "c++", "" ]
Just for the sake of experimentation, I've been trying to determine different ways to non-destructively chain `window.onload` functions in a web browser. This is the idea of what I have so far: ``` var load = window.onload; var newFunction = function(){ alert("ha!"); } window.onload = function(){ load(); newFunction(); } ``` The problem I see with this is that every time you chain a function, it adds another level of function calls to the stack. Is there a better way to go about this that doesn't add unnecessary depth to the call stack?
May be it will be better to use addEventListener/attachEvent? [Advanced event registration models](http://www.quirksmode.org/js/events_advanced.html)
You could have a look at [jQuery](http://jquery.com/) how they handle that. From the [jQuery docs](http://docs.jquery.com/Events/ready#fn): > You can have as many $(document).ready events on your page as you like. The functions are then executed in the order they were added.
Javascript Window.Onload Function Chaining
[ "", "javascript", "function", "onload", "method-chaining", "" ]
Our company (xyz) is moving a lot of our Flash code to Python. In Flash, we have a shared library between our Flash apps - package xyz. We can make changes to the package without fear of breaking other apps when they are deployed because Flash compiles their code and includes the contents of the library. We deploy the final SWF via RPM, and we're done. Updates to App1 and App2 won't ever break App3. How would you approach this in Python, the shared library dependency. App1, App2 and App3, could all require xyz-lib.rpm, and all use the same library files, but an updated xyz-lib.rpm would have to be explicitly tested against App1,2,3 *every time* there was a new library, and this is just onerous. My current favorite solution - I could make app1.rpm include the library from when it was packaged - effectively some sort of static linking of the library. This, however, feels inelegant. (although the only additional cost is hard drive space == cheap.) I know that solid management of the shared library is probably the best solution, but I keep trying to factor in that all the developers are human, and will make mistakes. We're going to make mistakes, and I don't want a deployment of app1 to break app2 and app3 - it's just a lot more to test and debug for.
I also favour the solution of packing everything together and limit the dependency on the OS libraries to the minimal (glibc and that's it). Hard drive is cheap, customer and support time is not. On windows, it's trivial with py2exe + InnoSetup. On Linux, it looks like [bbfreeze](http://pypi.python.org/pypi/bbfreeze/0.95.4) is the right way to handle this. Quoting from the homepage, it offers: * zip/egg file import tracking : bbfreeze tracks imports from zip files and includes whole egg files if some module is used from an eggfile. Packages using setuputils' pkg\_resources module will now work (new in 0.95.0) * binary dependency tracking : bbfreeze will track binary dependencies and will include DLLs and shared libraries needed by a frozen program.
"explicitly tested against App1,2,3 every time there was a new library" actually isn't that onerous. Two things. * You need a formal set of API unit tests that the library *must* pass. This is just the API, not every nuance of functionality. If this passes, then your changes are good to go. If this fails, your changes broke the API. * You also need a set of unit tests for functionality, separate from the API. This is bigger, and might be classified as "onerous". Once you start unit testing, you get addicted. Once you have reasonably complete tests, this problem is easy to manage.
Best way of sharing/managing our internal python library between applications
[ "", "python", "deployment", "shared-libraries", "projects-and-solutions", "" ]
I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head. I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file: ``` sviewlog = logging.getLogger('MyApp.views.scans') view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log') view_log_handler.setLevel(logging.INFO) view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')) sviewlog.addHandler(view_log_handler) ``` Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this? Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.
Allow me to answer my own question. The underlying problem here is that settings.py gets imported twice, or maybe even more (See [here](http://www.mail-archive.com/django-users@googlegroups.com/msg39059.html)). (I still don't understand why this is. Maybe some Django expert could explain that to me.) This seems to be true of some other modules as well. At this point I don't think it's wise to make assumptions about how many times settings.py will be imported. For that matter, such assumptions aren't safe in general. I've had this code in places other than settings.py, and the results are similar. You have to code around this. That is, you have to check your logger for existing handlers before adding additional handlers to it. This is a bit ugly because it's perfectly reasonable to have multiple handlers -- even of the same type -- attached to one logger. There are a few solutions to dealing with this. One is check the handlers property of your logger object. If you only want one handler and your length > 0, then don't add it. Personally I don't love this solution, because it gets messy with more handlers. I prefer something like this (thanks to Thomas Guettler): ``` # file logconfig.py if not hasattr(logging, "set_up_done"): logging.set_up_done=False def set_up(myhome): if logging.set_up_done: return # set up your logging here # ... logging.set_up_done=True ``` I must say, I wish the fact that Django imports settings.py multiple times were better documented. And I would imagine that my configuration is somehow cause this multiple import, but I'm having trouble finding out what is causing the problem and why. Maybe I just couldn't find that in their documents, but I would think that's the sort of thing you need to warn your users about.
As of version 1.3, Django uses standard python logging, configured with the `LOGGING` setting (documented here: [1.3](http://docs.djangoproject.com/en/1.3/ref/settings/#std:setting-LOGGING), [dev](http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGGING)). Django logging reference: [1.3](http://docs.djangoproject.com/en/1.3/topics/logging/), [dev](http://docs.djangoproject.com/en/dev/topics/logging/).
Python logging in Django
[ "", "python", "django", "logging", "python-logging", "" ]
Given an instance `x` of `Callable<T>`, how can I run `x` in a separate process such that I can redirect the standard input and output of the process? For example, is there a way to build a `Process` from a `Callable`? Is there a standard `Executor` that gives control over input and output? [UPDATE] It's not important that the `Callable` execute in a new process as opposed to a new thread. What I want is to put the `Callable` instance in a "harness", so that I can control its stdin/stdout. AFAIK, this calls for a new process.
More generally: > Given an instance x of Callable utilizing global variables A and B, how can I run x concurrently such that x sees custom values for A and B, rather than the "original" values of A and B? And the best answer is, don't use global variables. Dependency inject things like that. Extend Callable and add methods setStdIn, setStdOut (and setStdErr if you need it). I know this isn't the answer you're looking for, but the solutions I have seen for this all require a new process, and the only way you are getting that Callable into a new process is to change the code of the Callable so it is serializable, or provides a class name, or some other hack, so instead of making changes that will give you a nasty, brittle solution, just do it right\* \* "right" being to use the widely accepted pattern of dependency injection to provide loose coupling. YMMV UPDATE: In response to comment 1. Here is your new interface: ``` import java.io.InputStream; import java.io.PrintStream; import java.util.concurrent.Callable; public interface MyCallable<V> extends Callable<V> { void setStdIn(InputStream in); void setStdOut(PrintStream out); } ``` and your tasks would look like: ``` import java.io.InputStream; import java.io.PrintStream; public class CallableTask implements MyCallable<Object> { private InputStream in = System.in; private PrintStream out = System.out; public void setStdIn(InputStream in) { this.in = in; } public void setStdOut(PrintStream out) { this.out = out; } public Object call() throws Exception { out.write(in.read()); return null; } ``` } No need for a process. Any solution (even one using processes) is almost certainly going to require code changes to the Callables in some way. This is the simplest (just replace System.out with this.out).
stdin/stdout can be redirected for the entire system, but I'm not sure it can be redirected for a single thread--you are always just getting it from System. (You can make System.out go to another stream though, I've used that to catch stack traces before there was a method to get the trace as a string) You could redirect stdin/stdout, run the callable then redirect it back, but if anything else uses System.out while it's redirected, that will also go to your new file. The methods would be System.setIn() and System.setOut() (and System.setErr()) if you want to go that route.
Java: Run a Callable in a separate process
[ "", "java", "multithreading", "process", "stdout", "stdin", "" ]
``` public class Address { public string ZipCode {get; set;} } public class Customer { public Address Address {get; set;} } ``` how can I access eitther "ZipCode" or "Address.ZipCode" with reflection? For example: ``` Typeof(Customer).GetProperty("ZipCode")? ```
You'd need something like: ``` PropertyInfo addressProperty = typeof(Customer).GetProperty("Address"); ProportyInfo zipCodeProperty = addressProperty.PropertyType.GetProperty("ZipCode"); object address = addressProperty.GetValue(customer, null); object zipCode = zipCodeProperty.GetValue(address, null); ``` Basically if you want to take a string "Address.ZipCode" and navigate down it, you need to split it by "." and then call GetProperty on the appropriate type at every step to get the property itself, then PropertyInfo.GetValue to get the next value in the chain. Something like this: ``` public static object FollowPropertyPath(object value, string path) { Type currentType = value.GetType(); foreach (string propertyName in path.Split('.')) { PropertyInfo property = currentType.GetProperty(propertyName); value = property.GetValue(value, null); currentType = property.PropertyType; } return value; } ``` Call it like this: ``` object zipCode = FollowPropertyPath(customer, "Address.ZipCode"); ``` Note that this works on the compile-time types of the properties. If you want it to cope with the execution time type (e.g. if customer.Address didn't have a ZipCode property, but the actual type returned by Address did) then change `property.PropertyType` to `property.GetType()`. Also note that this doesn't have any error handling etc :)
Jon Skeet's answer is fine, I had to extend his method a bit though, in order to account for derived instances within the property path: ``` public static class ReflectorUtil { public static object FollowPropertyPath(object value, string path) { if (value == null) throw new ArgumentNullException("value"); if (path == null) throw new ArgumentNullException("path"); Type currentType = value.GetType(); object obj = value; foreach (string propertyName in path.Split('.')) { if (currentType != null) { PropertyInfo property = null; int brackStart = propertyName.IndexOf("["); int brackEnd = propertyName.IndexOf("]"); property = currentType.GetProperty(brackStart > 0 ? propertyName.Substring(0, brackStart) : propertyName); obj = property.GetValue(obj, null); if (brackStart > 0) { string index = propertyName.Substring(brackStart + 1, brackEnd - brackStart - 1); foreach (Type iType in obj.GetType().GetInterfaces()) { if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { obj = typeof(ReflectorUtil).GetMethod("GetDictionaryElement") .MakeGenericMethod(iType.GetGenericArguments()) .Invoke(null, new object[] { obj, index }); break; } if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof(IList<>)) { obj = typeof(ReflectorUtil).GetMethod("GetListElement") .MakeGenericMethod(iType.GetGenericArguments()) .Invoke(null, new object[] { obj, index }); break; } } } currentType = obj != null ? obj.GetType() : null; //property.PropertyType; } else return null; } return obj; } public static TValue GetDictionaryElement<TKey, TValue>(IDictionary<TKey, TValue> dict, object index) { TKey key = (TKey)Convert.ChangeType(index, typeof(TKey), null); return dict[key]; } public static T GetListElement<T>(IList<T> list, object index) { return list[Convert.ToInt32(index)]; } } ``` Using property.PropertyType will get you the property type defined on the obj class, while using obj.GetType() will get you the actual type of the property's instance. EDIT: @Oliver - you're absolutely right, thanks for noting that. I adjusted the method to allow for generic Lists and Dictionaries. While I don't like the parsing part, I used Marc Gravell's clever idea in [this thread](https://stackoverflow.com/questions/852233/getting-values-of-a-generic-idictionary-using-reflection) to get the indexer property's values.
Best way to get sub properties using GetProperty
[ "", "c#", "reflection", "getproperty", "" ]
I am using a makefile system with the pvcs compiler (using Microsoft Visual C++, 2008 compiler) and I am getting several link errors of the form: > `error LNK2019: unresolved external symbol __imp__RegisterFilter@8 referenced in function _main` This is happening DESPITE using the `extern "C"` declaration, viz.: ``` extern "C" int CLRDUMP_API RegisterFilter( LPCWSTR pDumpFileName, unsigned long DumpType ); ``` Also, in the makeexe.mak, the library is being linked in as: $(COMPILEBASE)\lib\clrdump.lib \ To be honest, I am not an expert at makefiles, and I am changing over a system from Microsoft Visual C++ 6.0 to 2008. This change-over may have something to do with the link errors, as the system used to work before. Any help would really be appreciated. Thanks in Advance, Sincerely, Joseph **-- Edit 1 --** Does anyone know how to turn verbose on in the makefile system of pvcs? Note that the above function is already a compiler-decorated version, having ``` __imp__RegisterFilter@8 ``` whereas the C++ function is just ``` RegisterFilter ``` Thanks for the help, but if anyone can post a more complete solution, that would also be very appreciated. Sincerely, Joseph **-- Edit 2 --** Some kind person posted this, but when I signed in it disappeared: The imp prefix indicates that this function is imported from a DLL. Check the definition of `CLRDUMP_API` - is it `__declspec(dllimport)`? See this article for more information. There was a working link, but I've lost that, however I suppose one can always search the topic. Thanks, whoever you were! **-- Edit 3 --** Thanks ChrisN (I'm not yet allowed to vote). Despite using the refresh button, your answer disappeared, but then re-appeared after I posted a cut-n-paste. This is my definition of that: ``` define CLRDUMP_API __declspec(dllimport) __stdcall ``` I assume that the \_\_stdcall is OK? **-- Edit 4 --** While I appreciate the efforts of those who answered, particularly ChrisN, at least on my particular system, the link error remains. So if anyone has any further insight, I'd appreciate it. Thanks again.
I was creating a simple Win32 c++ application in VS2005 and I was getting this error: ``` LNK2019: unresolved external symbol __imp__somefunction ``` This application was using property sheets, hence it required this header (prsht.h). The solution to my problem was as follows: in program **Properties→Configuration Properties→Linker→General**, I set **Additional Library Directories** to `"C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Lib"`. Also in program **Properties→Configuration Properties→Linker→Command line** for the **Additional Options**, I added `ComCtl32.Lib ComDlg32.Lib`. My program is now compiling without any problems. My two cents: you need to identify all the libraries that your program requires. Hint: check all the headers you have included, you need to make sure that your linker can see them.
The `__imp_` prefix indicates that the linker expects this function to be imported from a DLL. Is the clrdump library from [this page](http://www.debuginfo.com/tools/clrdump.html)? If so, note that `extern "C"` is not used in the header file supplied with the library. I confirmed this using the following command: ``` dumpbin /exports clrdump.lib ``` which produces the following output for `RegisterFilter` - this is a mangled C++ function name: > `?RegisterFilter@@YGHPBGK@Z (int __stdcall RegisterFilter(unsigned short const *,unsigned long))` I tried creating a sample program using clrdump.lib using Visual Studio 2008. Here's my code: ``` #include <windows.h> #include "ClrDump.h" int _tmain(int argc, _TCHAR* argv[]) { RegisterFilter(L"", 0); return 0; } ``` Building this produced the following linker error: > `LNK2019: unresolved external symbol "__declspec(dllimport) int __stdcall RegisterFilter(wchar_t const *,unsigned long)" (__imp_?RegisterFilter@@YGHPB_WK@Z)` The code builds OK with Visual C++ 6.0. Notice that the `dumpbin` output shows the first parameter to `RegisterFilter` as `unsigned short const *` but the linker error shows `wchar_t const *`. In Visual C++ 6.0, `wchar_t` is normally a typedef for `unsigned short`, whereas in later versions it is a distinct built-in type. To work around the problem in Visual Studio 2008, I set the "Treat wchar\_t as Built-in Type" option to "No" (specify `/Zc:wchar_t-` on the compiler command line), and the code now builds OK. Sorry for the confusion with my previous answer. I hope this is more helpful!
Clrdump (C++) error LNK2019: unresolved external symbol __imp__RegisterFilter@8 referenced in function _main
[ "", "c++", "visual-studio", "makefile", "clrdump", "" ]
I was just wondering how I could *automatically* increment the build (and version?) of my files using Visual Studio (2005). If I look up the properties of say `C:\Windows\notepad.exe`, the Version tab gives "File version: 5.1.2600.2180". I would like to get these cool numbers in the version of my dll's too, not version 1.0.0.0, which let's face it is a bit dull. I tried a few things, but it doesn't seem to be out-of-box functionality, or maybe I'm just looking in the wrong place (as usual). I work with mainly web projects.... I looked at both: 1. <http://www.codeproject.com/KB/dotnet/Auto_Increment_Version.aspx> 2. <http://www.codeproject.com/KB/dotnet/build_versioning.aspx> and I couldn't believe it so much effort to do something is standard practice. EDIT: **It does not work in VS2005 as far I can tell (<http://www.codeproject.com/KB/dotnet/AutoIncrementVersion.aspx>)**
In visual Studio 2008, the following works. Find the AssemblyInfo.cs file and find these 2 lines: ``` [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` You could try changing this to: ``` [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.*")] ``` But this won't give you the desired result, you will end up with a Product Version of **1.0.\*** and a File Version of **1.0.0.0**. Not what you want! However, if you remove the second of these lines and just have: ``` [assembly: AssemblyVersion("1.0.*")] ``` Then the compiler will set the File Version to be equal to the Product Version and you will get your desired result of an automatically increment product and file version which are in sync. E.g. **1.0.3266.92689**
open up the AssemblyInfo.cs file and change ``` // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` to ``` [assembly: AssemblyVersion("1.0.*")] //[assembly: AssemblyFileVersion("1.0.0.0")] ``` you can do this in IDE by going to project -> properties -> assembly information This however will only allow you to auto increment the Assembly version and will give you the > Assembly File Version: A wildcard ("\*") is not allowed in this field message box if you try place a \* in the file version field. So just open up the assemblyinfo.cs and do it manually.
Can I automatically increment the file build version when using Visual Studio?
[ "", "c#", "asp.net", "visual-studio", "version-control", "assemblyinfo", "" ]
I created a simple dialog-based application, and in the default CDialog added three buttons (by drag-and-dropping them) using the Visual Studio editor. The default OK and Cancel buttons are there too. I want to set the focus to button 1 when I click button 3. I set the property Flat to true in the properties for muy buttons. I coded this: ``` void CbuttonfocusDlg::OnBnClickedButton3() { // TODO: Add your control notification handler code here GetDlgItem(IDC_BUTTON1)->SetFocus(); Invalidate(); } ``` But the boder in button1 is never drawn. The caret (the dotted line indicating focus) is only drawn if I pressed TAB any time before clicking button 3. I want the button to look exactly as it looks after I click it. Showing the dotted line inside the button programatically, would be a plus. What I want: [![http://i33.tinypic.com/11t8pkl.png](https://i.stack.imgur.com/z8l0f.png)](https://i.stack.imgur.com/z8l0f.png) What I get: [![http://i37.tinypic.com/160q5hw.png](https://i.stack.imgur.com/CgqLi.png)](https://i.stack.imgur.com/CgqLi.png)
This draws the thick border around the button: ``` static_cast<CButton*>(GetDlgItem(IDC_BUTTON1))->SetButtonStyle(BS_DEFPUSHBUTTON); ``` A more elegant way to do this would be to define a CButton member variable in CbuttonfocusDlg and associate it to the IDC\_BUTTON1 control, and then calling ``` this->m_myButton.SetButtonStyle(BS_DEFPUSHBUTTON); ``` This makes the button to which I'm setting the focus the default button, but note that when the focus goes to a control (inside the dialog) that is not a button, the default button is once more the original default button set in the dialog resource, in this case the "Ok" button.
Use `WM_NEXTDLGCTL`. See [Reymond Chen's "How to set focus in a dialog box"](http://blogs.msdn.com/oldnewthing/archive/2004/08/02/205624.aspx): ``` void SetDialogFocus(HWND hdlg, HWND hwndControl) { SendMessage(hdlg, WM_NEXTDLGCTL, (WPARAM)hwndControl, TRUE); } ```
How to SetFocus to a CButton so that the border and focus dotted line are visible?
[ "", "c++", "mfc", "setfocus", "cdialog", "cbutton", "" ]
Here's a fictitious example of the problem I'm trying to solve. If I'm working in C#, and have XML like this: ``` <?xml version="1.0" encoding="utf-8"?> <Cars> <Car> <StockNumber>1020</StockNumber> <Make>Nissan</Make> <Model>Sentra</Model> </Car> <Car> <StockNumber>1010</StockNumber> <Make>Toyota</Make> <Model>Corolla</Model> </Car> <SalesPerson> <Company>Acme Sales</Company> <Position> <Salary> <Amount>1000</Amount> <Unit>Dollars</Unit> ... and on... and on.... </SalesPerson> </Cars> ``` the XML inside SalesPerson can be very long, megabytes in size. I want to deserialize the tag, **but** not deserialize the SalesPerson XML element instead keeping it in raw form "for later on". Essentially I would like to be able to use this as a Objects representation of the XML. ``` [System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)] public class Cars { [XmlArrayItem(typeof(Car))] public Car[] Car { get; set; } public Stream SalesPerson { get; set; } } public class Car { [System.Xml.Serialization.XmlElementAttribute("StockNumber")] public string StockNumber{ get; set; } [System.Xml.Serialization.XmlElementAttribute("Make")] public string Make{ get; set; } [System.Xml.Serialization.XmlElementAttribute("Model")] public string Model{ get; set; } } ``` where the SalesPerson property on the Cars object would contain a stream with the raw xml that is within the <SalesPerson> xml element after being run through an XmlSerializer. Can this be done? Can I choose to only deserialize "part of" an xml document? Thanks! -Mike p.s. example xml stolen from [How to Deserialize XML document](https://stackoverflow.com/questions/364253/how-to-deserialize-xml-document)
It might be a bit old thread, but i will post anyway. i had the same problem (needed to deserialize like 10kb of data from a file that had more than 1MB). In main object (which has a InnerObject that needs to be deserializer) i implemented a IXmlSerializable interface, then changed the ReadXml method. We have xmlTextReader as input , the first line is to read till a XML tag: ``` reader.ReadToDescendant("InnerObjectTag"); //tag which matches the InnerObject ``` Then create XMLSerializer for a type of the object we want to deserialize and deserialize it ``` XmlSerializer serializer = new XmlSerializer(typeof(InnerObject)); this.innerObject = serializer.Deserialize(reader.ReadSubtree()); //this gives serializer the part of XML that is for the innerObject data reader.close(); //now skip the rest ``` this saved me a lot of time to deserialize and allows me to read just a part of XML (just some details that describe the file, which might help the user to decide if the file is what he wants to load).
The accepted [answer](https://stackoverflow.com/a/2251545/193414) from user271807 is a great solution but I found, that I also needed to set the xml root of the fragment to avoid an exception with an inner exception saying something like this: ``` ...xmlns=''> was not expected ``` This exception was trown when I tried to deserialize only the inner Authentication element of this xml document: ``` <?xml version=""1.0"" encoding=""UTF-8""?> <Api> <Authentication> <sessionid>xxx</sessionid> <errormessage>xxx</errormessage> </Authentication> </ApI> ``` So I ended up creating this extension method as a reusable solution **- warning contains a memory leak, see below:** ``` public static T DeserializeXml<T>(this string @this, string innerStartTag = null) { using (var stringReader = new StringReader(@this)) using (var xmlReader = XmlReader.Create(stringReader)) { if (innerStartTag != null) { xmlReader.ReadToDescendant(innerStartTag); var xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(innerStartTag)); return (T)xmlSerializer.Deserialize(xmlReader.ReadSubtree()); } return (T)new XmlSerializer(typeof(T)).Deserialize(xmlReader); } } ``` **Update 20th March 2017:As the comment below points out, there is a memory leak problem when using one of the constructors of XmlSerializer, so I ended up using a caching solution as shown below:** ``` /// <summary> /// Deserialize XML string, optionally only an inner fragment of the XML, as specified by the innerStartTag parameter. /// </summary> public static T DeserializeXml<T>(this string @this, string innerStartTag = null) { using (var stringReader = new StringReader(@this)) { using (var xmlReader = XmlReader.Create(stringReader)) { if (innerStartTag != null) { xmlReader.ReadToDescendant(innerStartTag); var xmlSerializer = CachingXmlSerializerFactory.Create(typeof (T), new XmlRootAttribute(innerStartTag)); return (T) xmlSerializer.Deserialize(xmlReader.ReadSubtree()); } return (T) CachingXmlSerializerFactory.Create(typeof (T), new XmlRootAttribute("AutochartistAPI")).Deserialize(xmlReader); } } } /// <summary> /// A caching factory to avoid memory leaks in the XmlSerializer class. /// See http://dotnetcodebox.blogspot.dk/2013/01/xmlserializer-class-may-result-in.html /// </summary> public static class CachingXmlSerializerFactory { private static readonly ConcurrentDictionary<string, XmlSerializer> Cache = new ConcurrentDictionary<string, XmlSerializer>(); public static XmlSerializer Create(Type type, XmlRootAttribute root) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (root == null) { throw new ArgumentNullException(nameof(root)); } var key = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", type, root.ElementName); return Cache.GetOrAdd(key, _ => new XmlSerializer(type, root)); } public static XmlSerializer Create<T>(XmlRootAttribute root) { return Create(typeof (T), root); } public static XmlSerializer Create<T>() { return Create(typeof (T)); } public static XmlSerializer Create<T>(string defaultNamespace) { return Create(typeof (T), defaultNamespace); } public static XmlSerializer Create(Type type) { return new XmlSerializer(type); } public static XmlSerializer Create(Type type, string defaultNamespace) { return new XmlSerializer(type, defaultNamespace); } } ```
How to deserialize only part of an XML document in C#
[ "", "c#", "xml", "xml-serialization", "serialization", "" ]
I have to choose a technology to connect my **Application/Presentation Layer** (Java Based) with the **Service Layer** (Java Based). Basically looking up appropriate Spring Service from the Business Delegate Object. There are so many options out there that it is confusing me. Here are the options I've narrowed down to but not sure.. * Spring RMI * Apache Camel * Apache ServiceMix (ESB) * Iona FUSE (ESB) Here is what I want to know 1. If you have worked on (or evaluated) any of these, which choice do You think is more appropriate? (and it wouldn't hurt to tell me why :) 2. Are there other technologies that I should be looking at as well? 3. As of now I do **not** see Application and Service layer being distributed but I do not want to rule out this possibility in future. Is this a good idea to design to provide this flexibility? Any help would be useful. Thanks!
It mostly boils down to do you want to use Spring Remoting (which Spring RMI and [Apache Camel](http://activemq.apache.org/camel/spring-remoting.html) are implementations of) - or do you want to use JAX-WS for web services (which CXF or Metro implement). i.e. do you want automatic remoting for your POJOs - or do you want WS with WSDL contracts and so forth. Once you've decided on the remoting technology; your next decision is do you want to bundle it inside your application as a library (e.g. Spring RMI or Camel) - or do you want to deploy it in an ESB container like ServiceMix to be able to hot-redeploy modules and so forth. If the latter is your choice then use Apache ServiceMix - or use the FUSE ESB if you want a commercial distribution with more documentation, frequent releases, commercial support and so forth.
Spring Remoting would seem like the simplest approach. It also would leave you open to more complex approaches in the future if that is the direction you want to take. From the limited view of your requirements, I would stick with a simple solution with a lower learning curve, and leave the ESB till you determine you actually need it. The KISS principle is a wonderful thing.
Making a Service Layer call from Presentation layer
[ "", "java", "spring", "jakarta-ee", "soa", "esb", "" ]
I am using a third party application and would like to change one of its files. The file is stored in XML but with an invalid doctype. When I try to read use a it errors out becuase the doctype contains "file:///ReportWiz.dtd" (as shown, with quotes) and I get an exception for cannot find file. Is there a way to tell the docbuilder to ignore this? I have tried setValidate to false and setNamespaceAware to false for the DocumentBuilderFactory. The only solutions I can think of are * copy file line by line into a new file, omitting the offending line, doing what i need to do, then copying into another new file and inserting the offending line back in, or * doing mostly the same above but working with a FileStream of some sort (though I am not clear on how I could do this..help?) ``` DocumentBuilderFactory docFactory = DocumentBuilderFactory .newInstance(); docFactory.setValidating(false); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file); ```
Tell your DocumentBuilderFactory to ignore the DTD declaration like this: ``` docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); ``` See [here](http://xerces.apache.org/xerces2-j/features.html) for a list of available features. You also might find JDOM a lot easier to work with than org.w3c.dom: ``` org.jdom.input.SAXBuilder builder = new SAXBuilder(); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); org.jdom.Document doc = builder.build(file); ```
Handle resolution of the DTD manually, either by returning a copy of the DTD file (loaded from the classpath) or by returning an empty one. You can do this by setting an entity resolver on your document builder: ``` EntityResolver er = new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if ("file:///ReportWiz.dtd".equals(systemId)) { System.out.println(systemId); InputStream zeroData = new ByteArrayInputStream(new byte[0]); return new InputSource(zeroData); } return null; } }; ```
Java change and move non-standard XML file
[ "", "java", "xml", "dom", "parsing", "" ]
I'm looking for turn-key [ANTLR](http://www.antlr.org/) grammar for C# that generates a usable Abstract Syntax Tree (AST) and is either back-end language agnostic or targets C#, C, C++ or D. It doesn't need to support error reporting. P.S. I'm not willing to do hardly any fix-up as the alternative is not very hard.
This may be waaaay too late, but you can get a [C# 4 grammar](http://www.antlr3.org/grammar/list.html).
Here's a [C# grammar](http://www.antlr.org/grammar/1151612545460/CSharpParser.g) link, as well as an overview of [C# and ANTLR](http://www.manuelabadia.com/blog/PermaLink,guid,ff1dc504-f854-40b4-bfe7-250ce91efad7.aspx). There are others for the other languages you mentioned [here](http://www.antlr.org/grammar/list).
C# ANTLR grammar?
[ "", "c#", "antlr", "" ]
Optimization of PHP code via runtime benchmarking is straight forward. Keep track of $start and $end times via microtime() around a code block - I am not looking for an answer that involves microtime() usage. What I would like to do is measure the time it takes PHP to get prepared to run it's code - code-parse/op-code-tree-building time. My reasoning is that while it's easy to just include() every class that you **might** need for every page that you have on a site, the CPU overhead can't be "free". I'd like to know how "expensive" parse time really is. I am assuming that an opcode cache such as APC is **not** part of the scenario. Would I be correct that measurement of parse time in PHP is something that would have to take place in mod\_php? **EDIT**: If possible, taking into account `$_SERVER['DOCUMENT_ROOT']` usage in code would be helpful. Command solutions might take a bit of tinkering to do this (but still be valuable answers).
Yes. There is. ``` <?php return; rest of the code ?> ``` or ``` <?php whole code; $%^parse erorr!@! ?> ``` and then compare time of running empty script ``` time php empty.php ``` with time it takes to run (or fail) regular script with the additions I've mentioned above: ``` time php test.php ``` I've used this method on large files and PHP5.3 on Core2Duo 2.4Ghz can parse between 1.5 and 4.5MB of PHP code per second (it depends very much on complexity of the code of course).
One method could be timing the execution of the script from the command line. In Linux for example: ``` $ time php5 -r 'echo "Hello world";' Hello world real 0m1.565s user 0m0.036s sys 0m0.024s ``` Does that help at all? Perhaps it is helpful for discovering relative times between different scripts, but it may not be indicative of time taken through the Apache module
Is there a way to measure parse time in PHP?
[ "", "php", "benchmarking", "opcode-cache", "" ]
The following doesn't work, because it doesn't wait until the process is finished: ``` import subprocess p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True) p.wait() ``` Any idea how to run a shortcut and wait that the subprocess returns ? **Edit:** originally I was trying this without the **shell** option in my post, which caused Popen to fail. In effect, `start` is not an executable but a shell command. This was fixed thanks to Jim.
You will need to invoke a shell to get the subprocess option to work: ``` p = subprocess.Popen('start /B MOZILL~1.LNK', shell=True) p.wait() ``` This however will still exit immediately (see @R. Bemrose). If `p.pid` contains the correct pid (I'm not sure on windows), then you could use [`os.waitpid()`](http://docs.python.org/library/os.html#os.waitpid) to wait for the program to exit. Otherwise you may need to use some win32 com magic.
cmd.exe is terminating as soon as start launches the program. This behavior is documented (in start /? ): > If Command Extensions are enabled, > external command invocation through > the command line or the START command > changes as follows: ... > When executing an application that is > a 32-bit GUI application, CMD.EXE > does not wait for the application to terminate before returning to > the command prompt. This new behavior does NOT occur if executing > within a command script. How this is affected by the /wait flag, I'm not sure.
Run a shortcut under windows
[ "", "python", "windows", "" ]