Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I know how to control the number of decimals, but how do I control the number of zeros specifically? For example: ``` 104.06250000 -> 104.0625 119.00000 -> 119.0 72.000000 -> 72.0 ```
I don't think there is a pre-defined format for this - format in python are inherited from C, and I am pretty sure you don't have the desired format in C. Now, in python 3, you have the **format** special function, where you can do your own formatting. Removing the last zeros in python is very easy: just use the strip method: ``` a = 1.23040000 print str(a).rstrip('0') ``` If you want to keep a 0 after the decimal point, that's not very difficult either.
How about using the decimal module? From the [documentation](http://docs.python.org/library/decimal.html): "The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is the customary presentation for monetary applications. For multiplication, the “schoolbook” approach uses all the figures in the multiplicands. **For instance, 1.3 \* 1.2 gives 1.56 while 1.30 \* 1.20 gives 1.5600.**" The [normalize()](http://docs.python.org/library/decimal.html#decimal.Decimal.normalize) function removes trailing zeros: ``` >>> from decimal import * >>> d1 = Decimal("1.30") >>> d2 = Decimal("1.20") >>> d3 Decimal("1.5600") >>> d3.normalize() Decimal("1.56") ```
Printing floats with a specific number of zeros
[ "", "python", "floating-point", "" ]
Can Windows drivers be written in Python?
Yes. You cannot create the "classic" kernel-mode drivers. However, starting with XP, Windows offers a [User-Mode Driver Framework](http://www.microsoft.com/whdc/driver/wdf/UMDF.mspx). They can't do everything, obviously - any driver used in booting the OS obviously has to be kernel-mode. But with UMDF, you only need to implement COM components. Besides boot-time drivers, you also can't write UMDF drivers that: * Handle interrupts * Directly access hardware, such as direct memory access (DMA) * have strict timing loops * Use nonpaged pool or other resources that are reserved for kernel mode
The definitive answer is not without embedding an interpreter in your otherwise C/assembly driver. Unless someone has a framework available, then the answer is no. Once you have the interpreter and bindings in place then the rest of the logic could be done in Python. However, writing drivers is one of the things for which C is best suited. I imagine the resulting Python code would look a whole lot like C code and defeat the purpose of the interpreter overhead.
Can Windows drivers be written in Python?
[ "", "python", "windows", "drivers", "" ]
I'm using the python OpenCV bindings and at the moment I try to isolate a colorrange. That means I want to filter out everything that is not reddish. I tried to take only the red color channel but this includes the white spaces in the Image too. What is a good way to do that?
Use a different color space: <http://en.wikipedia.org/wiki/HSL_color_space>
Use the HSV colorspace. Select pixels that have an H value in the range that you consider to contain "red," and an S value large enough that you do not consider it to be neutral, maroon, brown, or pink. You might also need to throw out pixels with low V's. The H dimension is a circle, and red is right where the circle is split, so your H range will be in two parts, one near 255, the other near 0.
How to isolate a single color in an image
[ "", "python", "image-processing", "opencv", "color-space", "" ]
What's the DB2 Version of TSQL Print? I've tried ``` Print 'TableName:X' ``` And ``` Select 'X' As 'TableName' ```
Use sysibm.sysdummy1. It is a dummy table you can use to print constants values. Print 'TableName:X' would be: ``` select 'TableName:X' from sysibm.sysdummy1; ``` And Select 'X' As 'TableName' would be: ``` select 'X' as TableName from sysibm.sysdummy1; ``` Similarly if you want to print the current date, etc you can use: ``` select current date FROM sysibm.sysdummy1; ```
Within the Command Line Processor I think ECHO is the most similar function to T-SQL's PRINT function. See <http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0002006.htm>. For example: ``` ECHO 'Whatever you want printed'; ```
DB2 Print analog
[ "", "sql", "db2", "" ]
I have an HTML table with various rows, each has a delete button with a class. On the `DocumentReady` event I wire up all buttons with this class to handle the `click` event. On the `click` event, it does a `jQuery` `POST` which deletes data from the database and returns the table with the removed row. If I go to click another delete button it doesn't do anything as if the `click` event is not wired up. I have tried wiring it up in the `OnSuccess` event as well as `DocumentReady` but nothing.
Please do post your `jQuery` code responsible for that whole logic. Just as a shot in the dark I'd suggest you'll have to use: ``` $(".button").live("click",function(){...}) ``` instead of ``` $(".button").click(...) ```
I would use the live binding function in jquery to be able to bind to all specified elements at any time of creation: <http://docs.jquery.com/Events/live>
Wire up button click events after AJAX post
[ "", "javascript", "jquery", "" ]
I have some classes that are used as Singletons. They share some basic functionality and extend the same ancestor from a library which in turn isn't normally used as a Singleton. If I put the common functionality in a base class that inherits from the common ancestor, I get a class which makes no sense to instantiate, so I made it abstract. Also, because the classes are all used as Singletons, they should all have an init() and a getInstance() method, which are both static. All the constructors are of course non-public. Now, since `static` is an illegal modifier for abstract methods, the following doesn't work, although this would be exactly what I want: ``` class Base extends LibraryClass { protected Base() { // ... constructor } // ... common methods // ILLEGAL! public static abstract void init(); public static abstract <T extends Base>T getInstance(); } class A extends Base { private static A _INSTANCE; private A() { super(); } public static void init() { _INSTANCE = new A(); } public static A getInstance() { return _INSTANCE; } } ``` I could just leave out the illegal lines in the base class and be done with it. But how do I express that every child of Base *must* have these methods?
This is not possible in Java. Existence of `static` methods can't be enforced; neither by `abstract` nor by using an `interface`. My solution was to use IoC in a way: I created a factory class for singletons. It would save the singletons in a map. The key would be the class. This way, I could say: ``` A singleton = Factory.create (A.class); ``` The major advantage of this design: I can create a `Factory.replace()` method where test cases can override the singletons.
A common way to deal with adding singleton semantics to a class for which it may be inconvenient to add the semantics correctly is to implement the singleton functionality in a wrapper class. For example: ``` public class UsefulThing { } public final class SingletonOfUsefulThing { private static UsefulThing instance; private SingletonOfUsefulThing() {} public UsefulThing getInstance() { if (instance == null) { instance = new UsefulThing(); } return instance; } } ``` This allows you to give some of the primary singleton benefits to a class without some of the consequences that implementing the singleton semantics in the class directly forces you to deal with and allows some room for changing the specific type of the class you're exposing as a singleton (via using a factory to create the instance, for example, instead of `new`.
How can I have a Singleton that's derived from an abstract base type in Java?
[ "", "java", "inheritance", "singleton", "" ]
I accidentally removed /Library/Python on OS X Leopard. How can I reinstall that?
`/Library/Python` contains your python site-packages, which is the local software you've installed using commands like `python setup.py install`. The pieces here are third-party packages, not items installed by Apple - your actual Python installation is still safe in /System/Library/etc... In other words, the default OS leaves these directories mostly blank... nothing in there is critical (just a readme and a path file). In this case, you'll have to : 1. Recreate the directory structure: 2. Re-install your third-party libraries. The directory structure on a default OS X install is: > /Library/Python/2.3/site-packages > /Library/Python/2.5/site-packages
If you'd like, I'll create a tarball from a pristine installation. I'm using MacOSX 10.5.7, and only 12K.
Reinstall /Library/Python on OS X Leopard
[ "", "python", "macos", "osx-leopard", "reinstall", "" ]
I currently have a 5D array in the variable called template written into 1D array called template1D, with a hash table of 3456 (8 \* 12 \* 3 \* 4 \* 3) entries. In Matlab, the multi-dimensional array was accessed as follows: ``` template{idx_r, idx_l, idx_rho, idx_alpha, idx_beta} ``` However, as I have the indices going from 0-7, 0-11, 0-2, 0-3, and 0-2 respectively, I'm not entirely sure what would be the easiest way to retrieve an overall index number from these five indices in order to obtain the right segment in the template array properly. What would be the easiest method to make such hash functions properly?
Although you can certainly do the math yourself to compute the linear index (as pointed out by [Tal](https://stackoverflow.com/questions/919353/5d-array-hash-table/919404#919404)), it would be cleaner and easier to read using the built-in function [SUB2IND](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sub2ind.html) (as pointed out by [Loren](https://stackoverflow.com/questions/919353/5d-array-hash-table/920506#920506)). For your example, you would use it in the following way: ``` index = sub2ind([8 12 3 4 3], idx_r, idx_l, idx_rho, idx_alpha, idx_beta); ``` If all of your indices are 0-based, you would have to add 1 to each of them before passing them to SUB2IND. **EDIT:** If you would like to see how to correctly compute linear indices by yourself in MATLAB, such that they agree with the results from SUB2IND, here's the code you would use: ``` index = (((idx_beta*4 + idx_alpha)*3 + idx_rho)*12 + idx_l)*8 + idx_r + 1; ``` **NOTE** that the indices that need to be used with this equation have to be 0-based, while the indices passed to SUB2IND have to be 1-based. To generalize this equation to an arbitrary number of dimensions **N**: ``` index = (...(idx(N)*sz(N-1) + idx(N-1))*sz(N-2) + ...)*sz(1) + idx(1) + 1; ``` or more succinctly: ``` index = 1 + sum(idx.*cumsum([1 sz(1:(N-1))])); ``` where **idx** is an array of 0-based index values for each dimension and **sz** is an array of the sizes of each dimension.
Not sure exactly what you are trying to do here, but have you considered the functions ind2sub and sub2ind? They may help. You may need to worry about 0 versus 1-based indices as MATLAB is 1-based. --Loren
5D array hash table
[ "", "c++", "matlab", "hashtable", "" ]
Basically what I want, istwo public methods with slightly different return values to call the same method to do whatever work is needed. They both return the return value of the private method, however the private method will know how to return the correct value depending on the public method that called it. Example methods: ``` public Map<Type1, Type3> doSomething1(); public Map<Type2, Type3> doSomething2(); private Map<Type1/Type2, Type3> doSomething(); ``` So, in the above example, doSomething() returns either Type1 or Type2 as the Map's key-type, depending on which public method called it. It would be able to perform a simple check, and populate the map with objects of the correct type. Maybe this can be done through some clever Java reflection? I'm not sure. It all seems pretty dodgy, so if there's a much better way to go about this, I'm all ears.
I strongly suggest that reflection-mojo should be avoided here. A function must do one thing propertly, and must not depend on who call it. A better way to do the same would be to refactor doSomething() into smaller functions, create two new functions called doSomethingFor1() and doSomethingFor2(). Both these functions can reuse the refactored parts of the old doSomething(). Now have doSomething1() call and use doSomethingFor1(). Likewise, doSomething2() should use doSomethingFor2(). cheers, jrh.
**Please note:** *I've misunderstood the question, so this answer is opposite of what the question is as asking for. I will leave this up for reference as community wiki, but this does not answer the original question.* If there were a common subtype to `Type1` and `Type2` called `SuperType`, then saying that the first type is `? extends SuperType` would work. Here's a little example that uses `Integer` and `Double` as the two types, and their common ancestor as `Number`: ``` private Map<Integer, String> doSomethingForInteger() { HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(10, "Hello"); return map; } private Map<Double, String> doSomethingForDouble() { HashMap<Double, String> map = new HashMap<Double, String>(); map.put(3.14, "Apple"); return map; } public Map<? extends Number, String> doSomething(boolean b) { if (b) return doSomethingForInteger(); else return doSomethingForDouble(); } ``` Here, the `doSomething` method will return two types of `HashMap`s depending on the `boolean` that is passed in. Either `HashMap<Integer, String>` or `HashMap<Double, String>` is returned by the `doSomething` method. Actually calling up `doSomething` with a `boolean` can be accomplished like this: ``` Map<? extends Number, String> map1 = doSomething(true); Map<? extends Number, String> map2 = doSomething(false); ``` `map1` will end up with `Hashmap<Integer, String>`, while `map2` will get `Hashmap<Double, String>`.
Changing a return type depending on the calling method
[ "", "java", "generics", "reflection", "return-value", "typing", "" ]
Is the LINQ `Count()` method any faster or slower than `List<>.Count` or `Array.Length`?
In general slower. LINQ's Count in general is an `O(N)` operation while `List.Count` and `Array.Length` are both guaranteed to be `O(1)`. However it some cases LINQ will special case the `IEnumerable<T>` parameter by casting to certain interface types such as `IList<T>` or `ICollection<T>`. It will then use that Count method to do an actual `Count()` operation. So it will go back down to `O(1)`. But you still pay the minor overhead of the cast and interface call.
The `Enumerable.Count()` method checks for `ICollection<T>`, using `.Count` - so in the case of arrays and lists, it is not much more inefficient (just an extra level of indirection).
Is the Linq Count() faster or slower than List.Count or Array.Length?
[ "", "c#", ".net", "linq", "" ]
I want to subtract between two date time values using SQL in MySQL such that I get the interval in minutes or seconds. Any ideas? I want to run a SQL query that retrieves uses from a database who have logged in like 10 minutes from the time.
There are functions `TIMEDIFF(expr1,expr2)`, which returns the value of `expr1-expr2`, and `TIME_TO_SEC(expr3)`, which expresses `expr3` in seconds. Note that `expr1` and `expr2` are datetime values, and `expr3` is a time value only. Check [this link](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timediff) for more info.
[TIMESTAMPDIFF](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff) is like TIMEDIFF which Matthew states, except it returns the difference of the two datetimes in whatever units you desire (seconds, minutes, hours, etc). For example, ``` SELECT TIMESTAMPDIFF(MINUTE,LogOutTime,LogInTime) AS TimeLoggedIn FROM LogTable ``` Would return the number of minutes the user was logged in (assuming you stored this kind of thing in a table like that).
How do I subtract using SQL in MYSQL between two date time values and retrieve the result in minutes or second?
[ "", "mysql", "sql", "date", "" ]
In looking over my Query log, I see an odd pattern that I don't have an explanation for. After practically every query, I have "select 1 from DUAL". I have no idea where this is coming from, and I'm certainly not making the query explicitly. The log basically looks like this: ``` 10 Query SELECT some normal query 10 Query select 1 from DUAL 10 Query SELECT some normal query 10 Query select 1 from DUAL 10 Query SELECT some normal query 10 Query select 1 from DUAL 10 Query SELECT some normal query 10 Query select 1 from DUAL 10 Query SELECT some normal query 10 Query select 1 from DUAL ...etc... ``` Has anybody encountered this problem before? MySQL Version: 5.0.51 Driver: Java 6 app using JDBC. mysql-connector-java-5.1.6-bin.jar Connection Pool: commons-dbcp 1.2.2 The validationQuery was set to "select 1 from DUAL" (obviously) and apparently the connection pool defaults testOnBorrow and testOnReturn to true when a validation query is non-null. One further question that this brings up for me is whether or not I actually **need** to have a validation query, or if I can maybe get a performance boost by disabling it or at least reducing the frequency with which it is used. Unfortunately, the developer who wrote our "database manager" is no longer with us, so I can't ask him to justify it for me. Any input would be appreciated. I'm gonna dig through the API and google for a while and report back if I find anything worthwhile. EDIT: added some more info EDIT2: Added info that was asked for in the correct answer for anybody who finds this later
It could be coming from the connection pool your application is using. We use a simple query to test the connection. Just had a quick look in the source to mysql-connector-j and it isn't coming from in there. The most likely cause is the connection pool. Common connection pools: **commons-dbcp** has a configuration property `validationQuery`, this combined with `testOnBorrow` and `testOnReturn` could cause the statements you see. **c3p0** has `preferredTestQuery`, `testConnectionOnCheckin`, `testConnectionOnCheckout` and `idleConnectionTestPeriod` For what's it's worth I tend to configure connection testing and checkout/borrow even if it means a little extra network chatter.
I have performed 100 inserts/deltes and tested on both DBCP and C3PO. DBCP :: testOnBorrow=true impacts the response time by more than 4 folds. C3P0 :: testConnectionOnCheckout=true impacts the response time by more than 3 folds. Here are the results : DBCP – BasicDataSource Average time for 100 transactions ( insert operation ) testOnBorrow=false :: 219.01 ms testOnBorrow=true :: 1071.56 ms Average time for 100 transactions ( delete opration ) testOnBorrow=false :: 223.4 ms testOnBorrow=true :: 1067.51 ms C3PO – ComboPooledDataSource Average time for 100 transactions ( insert operation ) testConnectionOnCheckout=false :: 220.08 ms testConnectionOnCheckout=true :: 661.44 ms Average time for 100 transactions ( delete opration ) testConnectionOnCheckout=false :: 216.52 ms testConnectionOnCheckout=true :: 648.29 ms Conculsion : Setting testOnBorrow=true in DBCP or testConnectionOnCheckout=true in C3PO impacts the performance by 3-4 folds. Is there any other setting that will enhance the performance. -Durga Prasad
SELECT 1 from DUAL: MySQL
[ "", "java", "mysql", "connection-pooling", "apache-commons-dbcp", "" ]
I have an object with a field that can be a number of object types. This object is encoded in a single table with a discriminator column for the field's subtypes. Each of these subtypes have their fields mapped to a column in the parent objects table. I cannot seem to model this in hibernate. The code bellow will return null for `getSubfield()` regardless of what subtype data is in the table. *Schema* ``` id type whosit whatsit +----+------+--------+---------+ | 1 | "A" | "test" | null | | 2 | "B" | null | "test" | +----+------+--------+---------+ ``` *Domain Objects* ``` @Entity public class Parent { protected @Id @GeneratedValue int id; protected Subfield subfield; public Subfield getSubfield() {return subfield;} } @Embeddable @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING) public abstract class Subfield {} @DiscriminatorValue("A") public class TypeA extends Subfield { public String whosit; } @DiscriminatorValue("B") public class TypeB extends Subfield { public String whatsit; } ``` *"SELECT p FROM parent p"* ``` {id=1,subfield=null} {id=2,subfield=null} ``` Is it possible to accomplish what I want with this object model, or do I need to get a bit more creative (this is a legacy database, changing the schema is not preferred)
Ok you can't easily change the schema, but how about adding a couple of views?
As pointed by the asker, hibernate does not support inheritance of embeddable classes (<https://hibernate.atlassian.net/browse/HHH-1910>). According to the Eclipse wiki, the JPA does not specify this behavior, but EclipseLink does support it (<http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/Embeddable#Inheritance>). My suggestion is to smash the class hierachy entirely inside Subfield. Horrible, but should work until this is solved.
Hibernate Embeddable Inheritance
[ "", "java", "hibernate", "inheritance", "mapping", "" ]
Why do closures exist for anonymous methods? Why not just pass state into the method without the overhead of a new class being generated with the closure variables being copied in? Isn't this just a throwback to "making everything global?" Someone talk me down, I feel like i'm missing something here...
Purely, convenience... you don't know how much state you are going to need when defining, for example, a `Predicate<T>` - consider: ``` List<int> data = new List<int> {1,2,3,4,5,6,7,8,9,10}; int min = int.Parse(Console.ReadLine()), max = int.Parse(Console.ReadLine()); List<int> filtered = data.FindAll(i => i >= min && i <= max); ``` here we've passed two additional bits of state into `Predicate<T>` (`min` and `max`) - but we can't define `List<T>.FindAll(Predicate<T>)` to know about that, as that is a caller detail. The alternative is to write the classes ourselves, but that is hard, even if we are lazy: ``` class Finder { public int min, max; public bool CheckItem(int i) { return i >= min && i <= max;} } ... Finder finder = new Finder(); finder.min = int.Parse(Console.ReadLine()); finder.max = int.Parse(Console.ReadLine()); List<int> filtered = data.FindAll(finder.CheckItem); ``` I don't know about you, but I prefer the version with the closure... especially when you consider how complex it gets when you have multiple contextual levels. I want the compiler to worry about it. Consider also how often you use such constructs, especially for things like LINQ: you wouldn't want to have to do it any other way...
The overhead of creating a new class probably isn't something to worry about. It's just a convenient way for the CLR to make bound variables (those captured by the closure) available on the heap. They are still only accessible within the scope of the closure, so they're at all not "global" in the traditional sense. I believe the reason for their existence is mainly convenience for the programmer. In fact, it's purely that as far as I'm concerned. You could emulate the behaviour of a closure pretty well before they existed in C#, but you don't get any of the simplicity and syntactical sugar that C# 3.0 offers. The entire point about closures is that *you don't need to pass the variables in the parent scope to the function*, because they're automatically bound. It's much easier and cleaner for the programer to work with, really, if you consider that the alternative is *true* global variables.
Closures for anonymous methods in C# 3.0
[ "", "c#", "c#-3.0", "closures", "anonymous-methods", "anonymous", "" ]
As soon as I started programming C# (ASP.NET) I was surprised at how restrictive constants were. So far, I haven't used them much and I feel I missed the concept. How would you guys make use of constants in a typical ASP.NET application? How would declare a constant `struct` such as `System.Drawing.Color`? Would you guys use `readonly` when `const` cannot be used? I would like to find out how people are using `const` and `readonly` and to discuss alternatives if any.
Constants are for defining things in your program that should not change, but need to be referenced multiple times. ``` const int SLEEP_TIME = 500; //500 MS = .5 Seconds //Do Something Thread.Sleep(SLEEP_TIME); //Do Something else Thread.Sleep(SLEEP_TIME); //Do yet another something. ``` Now if you want to change SLEEP\_TIME you can do it in one place. As for a constant struct I'd usually use an enum ``` enum State { Stopped = 0, Running = 1, Paused = 2 } ``` Readonly is useful for references that need to be assigned once ``` private static readonly Logger = new TextLogger(); ``` And if you need to change something (ie: initialize something to null, then change it), it by definition can't be const.
Just from my experience, I've found that a lot of things that I think are constant, really aren't. I end up using a lot of external settings files to hold the information in (who wants to recompile a site if a color changes?) That said, I've found constants REALLY good for working with array indexes. It helps clarify their intent. For example... ``` //not readable - variable names don't help either string a = (string)source[0]; int b = (int)source[1]; bool c = (bool)source[2]; ``` Or the same thing with constants... ``` const int 0 = NAME_COLUMN; const int 1 = AGE_COLUMN; const int 2 = IS_ADMIN_COLUMN; //even with bad variable names, we know what they are string a = (string)source[NAME_COLUMN]; int b = (int)source[AGE_COLUMN]; bool c = (bool)source[IS_ADMIN_COLUMN]; ```
What are some examples or uses of constants in ASP.NET web applications?
[ "", "c#", "asp.net", "" ]
I know that when Windows is shutting down, it sends a [WM\_QUERYENDSESSION](http://msdn.microsoft.com/en-us/library/aa376890(VS.85).aspx) message to each application. This makes it easy to detect when Windows is shutting down. However, is it possible to know if the computer going to power-off or is it going to restart after Windows has shutdown. I am not particularly hopeful, considering the documentation at MSDN has this to say about `WM_QUERYENDSESSION`: "...it is not possible to determine which event is occurring," but the cumulative cleverness of stackoverflow never ceases to amaze me.
From [here](http://www.wholetomato.com/forum/topic.asp?ARCHIVE=true&TOPIC_ID=3397): > You can read the DWORD value from > "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shutdown > Setting" to determine what the user > last selected from the Shut Down > dialog. A bit of a roundabout solution, but it should do the trick.
In Windows 7 (and probably also in Vista / 8 / Server) you could use the system events to track whether Windows is shutting down (and powering off the computer) or just restarting. Every time a shutdown/reboot is initiated (by any means - clicking the button in Start menu, or programmatically), Windows 7 writes one or two events in the System log, source USER32, event ID 1074. You can see these events recorded if you open the Event Viewer from Administrative Tools (filter the System log to see only ID 1074). The description (message) of these events contains the shutdown type. So you could parse the description of the most recent event of this type (after the shutdown was initiated), looking for the necessary word (shutdown, reboot/restart). I didn't try to see the shutdown type written in the event when using the power button to gracefully shutdown Windows (I usually disable this function), but some site suggests that it states a "power off" type instead of "shutdown" - so check it out, if you need to be sure. Or simply look for a "reboot" type - if it's not found, then a "shutdown" type is assumed. In Windows XP, from my experience, an event 1074 is recorded only if the shutdown/reboot is done programmatically (e.g. during a program install or using the shutdown.exe utility). So it does not register the shutdowns initiated from the shell (Explorer), but perhaps you could combine this method with reading the value from registry as proposed in another answer. Also, keep in mind that in WinXP the message of event 1074 contains the word "restart" no matter what the real type of shutdown is, so you should look at the "Shutdown Type:" field, which will state either "shutdown" or "reboot". Related to this, an event ID 1073 is recorded whenever Windows fails to shutdown/reboot for some reason (e.g. if an application doesn't allow to shutdown as a response to WM\_QUERYENDSESSION). In that case the message will also contain words as "shutdown", "reboot" or "power off" - in WinXP. For Win7 this type of event is less useful in our case, since it won't make any difference between shutdown and reboot. But for WinXP - if you only need to intercept the shutdown/reboot, perform some actions, then continue the corresponding shutdown or reboot process - it should work as expected.
How to detect whether Windows is shutting down or restarting
[ "", "c++", "winapi", "api", "shutdown", "restart", "" ]
In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start\_time) and 5:00pm (end\_time). ``` selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time) ``` (as I expected)I get an error of: ``` "ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." ``` So I know I can use \_\_year so I tried. ``` selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time) ``` I get an error of: ``` "FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?" ```
You could filter in python instead using the db's mechanisms: ``` for e in Entry.objects.all(): if i.entered.hour>= 9 and i.entered.hour < 17 :# or break down to minutes/seconds list.append(e) ``` but both solutions are ugly, i think. Steve, you have to decide, what is less ugly for you: * processsing a lot of data in a for-loop, * or use .extra(..) and by-passing the orm-system
I don't believe there's built-in support for this, but you can pass [extra where-clause](http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none) parameters (warning: some possibility of introducing DB-dependent behaviour here). For example, on Postgres, something like: ``` Entry.objects.extra(where=['EXTRACT(hour from entered) >= 12 and '\ 'EXTRACT(hour from entered) < 17']) ``` If you're using potentially unsafe input to determine the values `12` and `17`, note that you can also specify a params option to extra that will ensure proper quoting and escaping, and then use the standard sql `%s` placeholders in your where statement.
How do I filter by time in a date time field?
[ "", "python", "django", "" ]
is there any C# method that works similar to Convert.ToBase64String but doesn't generate anything except alphanumeric output? Thanks!
You're probably looking at using something like Base32 encoding then. There is a Base32 encoder/decoder for C# [here](http://www.atrevido.net/blog/2004/01/13/Base32%2BIn%2BNET.aspx) by Michael Giagnocavo. It uses a combination of capitalized letters and numbers. There's also a related discussion on StackOverflow [here](https://stackoverflow.com/questions/641361/base32-decoding). **EDIT:** And if by any chance this is for URL-safe related Base64 encoding, just do Base64 and replace "+" with "-" and "/" with "\_". But I'm guessing, you may not want it for that.
The answers are a bit outdated now. For the benefit of future searchers: The best way to handle this now in C# is: ``` byte[] b; // fill your byte array somehow string s = System.Web.HttpServerUtility.UrlTokenEncode(b); ``` This returns a Base64-encoded string that is URL-safe (which is what you said you were really after in the comments to your question). You can then decode it again using, you guessed it: ``` byte[] b = System.Web.HttpServerUtility.UrlTokenDecode(s); ```
C# Method like Base64String, but only alphanumeric (no plus or slash)
[ "", "c#", "encoding", "base64", "alphanumeric", "" ]
the output is like below restored in a output.txt file: ``` array ( 'IMType' => '1', 'Email' => 'test@gmail.com', 'SignupName' => 'test11', 'Password' => '11111', 'Encrypted' => '', 'Confirm' => '11111', 'OldPassword' => '', 'Name' => 'test', 'SignupProvinceText' => 'province', 'SignupCity' => 'cityname', 'Street' => 'street x.y', 'SignupIndustry' => 'IT', 'SignupCompany' => 'jobirn', 'SignupJt' => 'engineer', 'CellPhoneNum' => '', 'linked_in' => '', ) ``` it's in fact output of `var_export(my_variable,true)`,but how to read it into a variable again?
like this: ``` $dumpStr = var_export($var,true); eval('$somevar = ' . $dumpStr . ';'); ``` <https://www.php.net/manual/en/function.eval.php>
Perhaps you want to serialize object and then unserialize? <http://php.net/serialize>
how to read output of var_export into a variable in PHP?
[ "", "php", "import", "" ]
I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this: ``` def generate_data(): ... do some analysis and return complex object e.g. list ... class Coo: data_member = generate_data() ... rest of class code ... ``` The function `generate_data` takes a long while to complete and returns data that remains constant in the scope of a running program. I don't want it to run every time class Coo is instantiated. Also, to verify, as long as I don't assign anything to `data_member` in `__init__`, it will remain "static"? What if a method in Coo appends some value to `data_member` (assuming it's a list) - will this addition be available to the rest of the instances? Thanks
You're right on all counts. `data_member` will be created once, and will be available to all instances of `coo`. If any instance modifies it, that modification will be visible to all other instances. Here's an example that demonstrates all this, with its output shown at the end: ``` def generate_data(): print "Generating" return [1,2,3] class coo: data_member = generate_data() def modify(self): self.data_member.append(4) def display(self): print self.data_member x = coo() y = coo() y.modify() x.display() # Output: # Generating # [1, 2, 3, 4] ```
As others have answered you're right -- I'll add one more thing to be aware of: If an instance modifies the object `coo.data_member` itself, for example ``` self.data_member.append('foo') ``` then the modification is seen by the rest of the instances. However if you do ``` self.data_member = new_object ``` then a new *instance* member is created which overrides the class member and is only visible to that instance, not the others. The difference is not always easy to spot, for example `self.data_member += 'foo'` vs. `self.data_member = self.data_member + 'foo'`. To avoid this you probably should always refer to the object as `coo.data_member` (not through `self`).
Pythonic Way to Initialize (Complex) Static Data Members
[ "", "python", "class", "" ]
I'm in a situation where I'd like to instantiate an object of a type that will be determined at runtime. I also need to perform an explicit cast to that type. Something like this: ``` static void castTest(myEnum val) { //Call a native function that returns a pointer to a structure IntPtr = someNativeFunction(..params..); //determine the type of the structure based on the enum value Type structType = getTypeFromEnum(val); structType myStruct = (structType)Marshal.PtrToStructure(IntPtr, structType); } ``` This is obviously not valid code, but I hope it conveys the essence of what I'm trying to do. The method I'm actually working on will have to perform the marshaling operation on ~35 different types. I have several other methods that will need to do something similar with the same set of types. So, I'd like to isolate the type-determining logic from these methods so that I only need to write it once, and so that the methods stay clean and readable. I must admit to being a total novice at design. Could anyone suggest a good approach to this problem? I suspect there might be an appropriate design pattern that I'm unaware of.
There are several ways you can create an object of a certain type on the fly, one is: ``` // determine type here var type = typeof(MyClass); // create an object of the type var obj = (MyClass)Activator.CreateInstance(type); ``` And you'll get an instance of MyClass in obj. Another way is to use reflection: ``` // get type information var type = typeof(MyClass); // get public constructors var ctors = type.GetConstructors(BindingFlags.Public); // invoke the first public constructor with no parameters. var obj = ctors[0].Invoke(new object[] { }); ``` And from one of ConstructorInfo returned, you can "Invoke()" it with arguments and get back an instance of the class as if you've used a "new" operator.
You can *mostly* do what you're describing, but since you don't know the type at compile-time, you'll have to keep the instance loosely-typed; check its type at each point you use it, and cast it appropriately then (this will not be necessary with c# 4.0, which supports [dynamics](http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx)): ``` Type type = CustomGetTypeMethod(); var obj = Activator.CreateInstance(type); ... if(obj is MyCustomType) { ((MyCustomType)obj).Property1; } else if (obj is MyOtherCustomType) { ((MyOtherCustomType)obj).Property2; } ```
Instantiate an object with a runtime-determined type
[ "", "c#", ".net", "design-patterns", "runtime", "" ]
Is it recommended to check the Page.IsPostBack in a user control Page\_Load Event like ``` protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { } } ``` I am getting wierd results Edit ~ Here is the thing. When the main form is loaded, I use Request.QueryString to get the customer id which I then place in a SESSION variable. On the control Load event I read the SESSION variable to get the data for that customer. So, do I need to check PostBack at the control level? Edit ~ Here is the load event of the control ``` protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { //Getting and storing the customer account number if (string.IsNullOrEmpty((string)Session["CustomerNumber"])) { Session["CustomerNumber"] = cust.GetCustomerNumber(myHelper.GetCustomerIDFromQueryString()); LoadProductData(); } } } ``` Here is the myHelper Class ``` static class myHelper { public static Guid GetCustomerIDFromQueryString() { //Getting the GUID (used as customerid in CRM) from the URL request of the selected account. return Sql.ToGuid(System.Web.HttpContext.Current.Request["ID"]); } } ``` }
If you use "!IsPostBack" in page load, when the user click other control it do a postBack, so you don't get your data. I hope that helps you.
Just checking it for no reason? Absolutely not. If you should do something only on first load and not on subsequent post backs then it's the pattern that should be used.
Checking Page.IsPostBack in user controls
[ "", "c#", "asp.net", "postback", "" ]
I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.
Everyone is being very polite in answering this question: "it depends"... "you should test"... and so forth. True, the question does not go into great detail about the application and network topographies involved, but if the question is even being asked, then it's likely a) the DB is "local" to the application (on the same subnet, or the same machine, or in memory), and b) the webservice is not. After all, the OP uses the phrases "external service" and "display on your own site." The phrase "parsing it once or however many times you need to each day" also suggests a set of data that doesn't exactly change every second. The classic SOA myth is that the network is always available; going a step further, I'd say it's a myth that the network is always available with low latency. Unless your own internal systems are crap, sending an HTTP query across the Internet will always be slower than a query to a local DB or DB cluster. There are any number of reasons for this: number of hops to the remote server, outage or degradation issues that you can't control on the remote end, and the internal processing time for the remote web service application to analyze your request, hit its own persistence backend (aka DB), and return a result. Fire up your app. Do some latency and response times to your DB. Now do the same to a remote web service. Unless your DB is also across the Internet, you'll notice a huge difference. It's not at all hard for a competent technologist to scale a DB, or for you to completely remove the DB from caching using memcached and other paradigms; the latency between servers sitting near each other in the datacentre is monumentally less than between machines over the Internet (and more secure, to boot). Even if achieving this scale requires some thought, it's under your control, unlike a remote web service whose scaling and latency are totally opaque to you. I, for one, would not be too happy with the idea that the availability and responsiveness of my site are based on someone else entirely. Finally, what happens if the remote web service is unavailable? Imagine a world where every request to your site involves a request over the Internet to some other site. What happens if that other site is unavailable? Do your users watch a spinning cursor of death for several hours? Do they enjoy an Error 500 while your site borks on this unexpected external dependency? If you find yourself adopting an architecture whose fundamental features depend on a remote Internet call for every request, think very carefully about your application before deciding if you can live with the consequences.
First off -- measure. Don't just assume that one is better or worse than the other. Second, if you really don't want to measure, I'd guess the database is a bit faster (assuming the database is relatively local compared to the web service). Network latency usually is more than parse time unless we're talking a really complex database or really complex XML.
Is it more efficient to parse external XML or to hit the database?
[ "", "python", "mysql", "xml", "django", "parsing", "" ]
I have a data-bound, templated control, and inside the templated area I create a control with an event handler, like so: ``` <tnl:DisplayTree ID="DisplayTree1" runat="server" KeyPropertyName="Id" ParentPropertyName="ParentDemographic" DataSourceID="DemographicObjectSource"> <ItemTemplate> <asp:CheckBox ID="DemogSelector" runat="server" OnCheckedChanged="DemogSelector_OnCheckedChanged" /> &nbsp; <asp:Label ID="InlineEditLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Name") %>'></asp:Label> </ItemTemplate> </tnl:DisplayTree> ``` Within the event handler, I would like to be able to detect the Key of the item for which the control was created. For example: ``` protected void DemogSelector_OnCheckedChanged(object sender, EventArgs e) { CheckBox selector = (CheckBox)sender; DisplayTree.TreeNode treeNode = (DisplayTree.TreeNode)selector.Parent.Parent.Parent.Parent; Label1.Text += (int)treeNode.Key + ", "; } ``` As you can see, this approach requires close knowledge of the hierarchy within my DisplayTree.TreeNode class (i.e. I have to know that sender.Parent.Parent.Parent.Parent is where I'll find the DisplayTree.TreeNode object). I would like to make it a bit more robust, so that if my TreeNode hierarchy changes or something, I can access the key without difficulty. What's the best way for me to make this Key available from within the event handler?
Best way is to add a custom attribute to your checkbox ``` <asp:CheckBox ID="DemogSelector" runat="server" oncheckedchanged="DemogSelector_CheckedChanged" AutoPostBack="true" key='<%# Eval("Id") %>'/> ``` And then access it using ``` string key = (sender as CheckBox).Attributes["key"]; ```
One potential way is to add an extension method to the checkbox, which finds the TreeNode for you, it could be implemented as some loop which recursively searches the parents until the TreeNode is found. That way you just call selector.FindTreeNode(), of course this would fail on any checkbox called outside of your structure.
ASP.NET: Access DataItem from an Event Handler
[ "", "c#", "asp.net", "" ]
When you open the [yahoo main page](http://uk.yahoo.com) at the top there is a search section that contains links like: Web, Images, Video, More When clicking on the link the chosen section is activated and the text of the search button is being changed. The only part of the page that is updated is the search part at the top and **the other parts of the website remain unaffected.** My question is how is this implemented? And more importantly **how similar behaviour could be implemented in .net using VS 2008?** Are the links really links or different elements that only mimic the links behaviour? Does it need to be ajax, or just everything is preloaded and hidden using some css techniques? Is the same technique used in the news section on the same page when changing tabs: News, Sport, Entertainment, Video? Thank you
This is actually done with CSS and Javascript: ``` <ul id='menu'> <li><a href="#web_search" class='active'>Web</a></li> <li><a href="#image_search">Image</a></li> <li><a href="#video_search">Video</a></li> <li><a href="#local_search">Local</a></li> </ul> <div id='web_search' class='search'></div> <div id='image_search' class='search' style='display: none;'></div> <div id='video_search' class='search' style='display: none;'></div> <div id='local_search' class='search' style='display: none;'></div> ``` Then Javascript (example uses jQuery, can be done many ways...): ``` $('a','#menu').click(function() { $('div.search').hide(); $('a.active', '#menu').removeClass('active'); $($(this).addClass('active').attr('href')).show(); $(this).blur(); return false; }); ``` [And this is an example of it in action](http://jsbin.com/amube). The styling and such would all be CSS.
After doing a quick inspection of the search field using [Firebug](http://getfirebug.com/), it appears that clicking on each of search type links (Web, Images, etc) simply modifies the DOM. This includes adding fields, removing fields, toggling class names, etc. I wouldn't be surprised if hidden fields are also being manipulated. Behavior like this is accomplished using JavaScript. Specifically (and at a very high-level), there are event handlers attached to the links each of which modify the DOM in their own way. It can definitely be implemented using Visual Studio 2008 as it's really (and likely) nothing more than CSS, JavaScript, and HTML. .NET really wouldn't come into play until you're ready to take the specified query and begin running it against your data store. [Paolo's answer](https://stackoverflow.com/questions/978591/search-type-links-in-yahoo-how-to-implement-similar-behaviour/978634#978634) gives a really good, straight-forward example of how that behavior can be emulated.
Search type links in Yahoo - how to implement similar behaviour
[ "", "asp.net", "javascript", "html", "css", "" ]
I have to create an image gallery where user can select some images and then process them. The selection should be done via Ctrl+LeftClick of the mouse. It works well in FF and IE8, but when I Ctrl+click in Opera, new dialog "Save as" appears which causes saving the clicked image. How do I prevent opening the dialog in Opera? (it's probably system setting) I haven't still found any solution. The question at [Opera](http://my.opera.com/community/forums/topic.dml?id=240344) remains unanswered since June,2008 :( Is it even possible? Ctrl+Click is standard way in OS, that's probably the problem - adapting desktop behaviour to web.
In Opera, it is possible to set this behavior in `Tools->Preferences->Content->JavaScript Options->Allow script to detect context menu events`. This is unchecked by default, which means that most users will see the browser's context menu. This was added to prevent "context menu hijacking"; unfortunately, this limits all browser apps to the left mouse button. You could have the user `rightclick->Edit site preferences->Scripting->Allow script to detect context menu events`; this should allow your site to use this functionality.
I don't believe this is possible - I'd advise a different key mapping for Opera (or indeed all browsers) For example, Opera has an option where the right click context menu cannot be disabled by javascript - as a protection for Opera users.
How to prevent the 'Save (image) as' dialog on Ctrl+click in Opera
[ "", "javascript", "browser", "selection", "opera", "" ]
I have a confirm step in one of my pages. Desired action: * user clicks 'submit' and an AJAX request is made that does the appropriate action and returns a confirm dialog * user 'confirms' and then the form is submitted using a standard post. So for the first part I'm fine using the jQuery form plugin: ``` $('form').ajaxForm(...options...); ``` For the second part I'd like to submit the form again, but non-ajax. Basically I want to do this: ``` $('form').submit(); ``` And have it do an actual browser post. The problem is that $('form').submit() just triggers the ajax submit. Is there a way to use the form for both purposes?
``` $('forms-submit-button').click() ``` ..does that work , for the second submit? :) :)
Can't you just unregister the submit event handler after you've ajax-posted the results? Why do you need to post the same data twice, by the way? If the data haven't changed between the Ajax post and the regular one, why is the regular one needed?
jQuery Forms - Ajax and normal submit the same form
[ "", "javascript", "jquery", "ajax", "forms", "jquery-forms-plugin", "" ]
I am not sure exactly what I am asking....The guys that do the software development for the company I work for write everything in VB. I am currently the Web developer for this company and I specialize in Flex apps. I am thinking about expanding into their area. But I do not want to do VB, I don't mean to bash on VB but the coding syntax is not for me. So I am wondering if Java can integrate with VB? Also not sure if it matters but I think everything they do is procedural, and I will be doing OOP. Thanks.
There are lots of integration opportunities, but before examining them, if I were you I would re-examine the question itself. It should be exceptional to introduce a new language into an established project. The desires or aesthetic preference or skillset of a single developer is not a good enough justification to do so. Introducing a new language into a project should be a strategic decision for the project, not a backhanded one. If you do choose to expand the core languages used to develop the system, * **COM interop** is possible with [JACOB](http://danadler.com/jacob/). I believe IBM has a bridge as well.(Check alphaworks) * **Java-.NET bridging** is possible via [JNBridge](http://www.jnbridge.com/) and other bridges. This makes sense only if VB.NET is in use. * **SOAP, XML document exchange, REST** suitable over a services boundary. It requires TCP or HTTP or some network protocol. * **common data stores** can serve as a rendezvous point. Both Java and VB can read and update data in SQL Server, Oracle, MSMQ, MQSeries, and so on. Even a filesystem can be an integration point. Think of data format as related to, but ideally independent of, the integration mechanism. What I mean is: You can use an XML document for integration, whether it is stored in a database, or sent over a REST interface, or stored in a filesystem, or put/get on a queue. You can use a comma-separated file over any of those mechanisms as well.
Potentially they could expose a service layer via soap or something simpler? Also you could always work against the same database with different languages however unless most of the logic is in stored procedures (not necessarily recommending this approach) then you end up with repeated code.
Can Java apps integrate with VB apps?
[ "", "java", "vb6", "interop", "" ]
What is the purpose of having more than one class in a Java file ? I am new to Java. **Edited:** That can be achieved by creating a inner class inside a public class, right?
Yes, it can. However, there can only be one *public top-level* class per `.java` file, and public top-level classes must have the same name as the source file. The purpose of including multiple classes in one source file is to bundle related support functionality (internal data structures, support classes, etc) together with the main public class. Note that it is always OK not to do this--the only effect is on the readability (or not) of your code.
If you want to implement a public class, you must implement it in a file with the same name as that class. A single file can contain one public and optionally some private classes. This is useful if the classes are only used internally by the public class. Additionally the public class can also contain inner classes. Although it is fine to have one or more private classes in a single source file, I would say that is more readable to use inner and anonymous classes instead. For example one can use an anonymous class to define a Comparator class inside a public class: ``` public static Comparator MyComparator = new Comparator() { public int compare(Object obj, Object anotherObj) { } }; ``` The Comparator class will normally require a separate file in order to be public. This way it is bundled with the class that uses it.
Can a java file have more than one class?
[ "", "java", "class", "" ]
I'm not sure if I'm using "standard" terms, but this is a basic OO question I'm trying to resolve. I'm coding a windows form. I don't want logic in the form event handler, so I just make a call to a custom object from there. At the custom object, there are two sets of logic. 1. The "controller" logic, which decides what needs to get done and when. 2. The actual business logic that does what needs to be done (for example a control that performs a math operation and returns results, etc.). My question is, does OO architecture allow for having both of these in a single object? Or is it recommended to split them out into a "controller" object and a "business logic" object? Is there a design pattern I should refer to for this? For the time being, I've started down the route of combining them into one object. This object has a "start" method which contains the controller logic. This method then calls other methods of the object as needed, and ultimately returns results to the caller of the object.
In general, you should probably have these in two different objects, but there's a qualifier on that. It may make sense, if your project is small enough and your object model is not complex enough, to have the functionality composed into one object; however, if your functionality is complex enough, it's almost certainly going to be better for you to segregate the controller and the business objects. At the very least, design the system with an eye towards separating the controller and the business objects at a later point, if you don't completely separate them now.
What you're doing is a form of "fat controller" architecture. These days software development is trending toward thin controllers. **OO design is all about decoupling.** If you internalize only one thing about OO programming, let it be that. Check out "[Domain-Driven Design *Quickly*](http://www.infoq.com/minibooks/domain-driven-design-quickly)." This free e-book is a condensed introduction to the concepts covered in Eric Evans' important book "Domain-Driven Design." Getting educated in these concepts should help you to understand how to separate business logic from the controller, or service layer.
oo question - mixing controller logic and business logic
[ "", "c#", ".net", "design-patterns", "oop", "" ]
I am trying to set up ehcache replication as documented here: <http://ehcache.sourceforge.net/EhcacheUserGuide.html#id.s22.2> This is on a Windows machine but will ultimately run on Solaris in production. The instructions say to set up a provider as follows: ``` <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446, timeToLive=32"/> ``` And a listener like this: ``` <cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties="hostName=localhost, port=40001, socketTimeoutMillis=2000"/> ``` My questions are: Are the multicast IP address and port arbitrary (I know the address has to live within a specific range but do they have to be specific numbers)? Do they need to be set up in some way by our system administrator (I am on an office network)? I want to test it locally so am running two separate tomcat instances with the above config. What do I need to change in each one? I know both the listeners can't listen on the same port - but what about the provider? Also, are the listener ports arbitrary too? I've tried setting it up as above but in my testing the caches don't appear to be replicated - the value added in one tomcat's cache is not present in the other cache. Is there anything I can do to debug this situation (other than packet sniffing)? Thanks in advance for any help, been tearing my hair out over this one!
> I want to test it locally so am > running two separate tomcat instances > with the above config. As I have just submitted an answer regarding cherouvims [related question](https://stackoverflow.com/questions/1313410/ehcache-auto-discovery-via-multicast-between-2-instances-on-the-same-host) I'd just like to highlight here too that they are in fact providing an example doing something similar at least (multiple nodes per host, though one instance only): see section *Full Example* in the [RMI Distributed Caching](http://www.ehcache.org/documentation/2.7/replication/rmi-replicated-caching.html) documentation. It's indeed important to change the TCP port for each `cacheManagerPeerListenerFactory` but the multicast settings can (I'd think they must) stay the same: you can see this in action within the [ehcache.xml's](http://ehcache.svn.sourceforge.net/viewvc/ehcache/trunk/core/src/test/resources/distribution/) for the *Full Example* mentioned above: the port number is increased one by one from 40001 up to 40006 per node while the multicast settings stay identical. If you have obeyed that, your problem might just be related to Tomcat running on Windows - see the related paragraph within section *Common Problems* in [RMI Distributed Caching](http://www.ehcache.org/documentation/2.7/replication/rmi-replicated-caching.html): > There is a bug in Tomcat and/or the JDK where any RMI listener will > fail to start on Tomcat if the installation path has spaces in it. > [...] > As the default on Windows is to install Tomcat in "Program Files", > this issue will occur by default.
One mistake I encountered during EHCache peer replication. This might be useful so someone attempting peer replication on a single local box. I wanted to run 3 peer-replicated instances of EhCache on a single Windows Vista box using peerDiscovery=automatic (the eventual target environment was Linux). The peer-replication did not work. Oddly, all EhCache instances were starting-up without any errors or complaints in the log. Took me a while to figure my mistake; without anything in the logs I had to grok around: I was using the same listenerPort (40001) in the peer listener configuration for each of the EhCache instances. Using different listenerPorts (40001, 40002...) did the trick. ``` <cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties="port=40001, socketTimeoutMillis=3000"/> <cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties="port=40002, socketTimeoutMillis=3000"/> ``` Note that this is the 'peer listener' configuration that needed different port numbers. The multicast 'peer discovery' still uses identical multicast address and port numbers for every ehcache instance.
Setting up ehcache replication - what multicast settings do I need?
[ "", "java", "ehcache", "multicast", "" ]
I have a Java question about generics. I declared a generic list: ``` List<? extends MyType> listOfMyType; ``` Then in some method I try instantiate and add items to that list: ``` listOfMyType = new ArrayList<MyType>(); listOfMyType.add(myTypeInstance); ``` Where `myTypeInstance` is just an object of type `MyType`; it won't compile. It says: > The method add(capture#3-of ? extends > MyType) in the type List<capture#3-of > ? extends MyType> is not applicable > for the arguments (MyType) Any idea?
You cannot do a "put" with extends . Look at [Generics - Get and Put rule](https://stackoverflow.com/questions/1292109/generics-get-and-put-rule).
Consider: ``` class MySubType extends MyType { } List<MySubType> subtypeList = new ArrayList<MySubType>(); List<? extends MyType> list = subtypeList; list.add(new MyType()); MySubType sub = subtypeList.get(0); ``` `sub` now contains a `MyType` which is very wrong.
List<? extends MyType>
[ "", "java", "list", "generics", "bounded-wildcard", "" ]
I've recently gotten quite fond of [netbeans](http://www.netbeans.org/) for my php work because of the XDebug integration. It has made me all but forget about [textmate](http://www.macromates.com) (which imho still beats netbeans for the little things) What do you think is the one awesome netbeans feature I should know about, and more importantly why and how do I use it? I'm asking this to optimize my skills in the use of the IDE and based on the idea that what works well for others might just work for me (and hopefully others).
The [Subversion Integration](http://subversion.netbeans.org/) directly on the IDE and the [Local History](http://blogs.oracle.com/plamere/entry/saved_by_netbeans_local_history) are of my must-use, favorite features.
I've found another great snip of genius i wanted to share: you can do custom code folding (not really related to php, just netbeans) just put this into a code file: ``` // <editor-fold defaultstate="collapsed" desc="getters and setters"> some boring code you don't need to see every time here // </editor-fold> ``` That'll behave similar to `#region`s in visual studio or `pragma mark`s in xcode. but unlike `region`s, it doesn't screw up the working of your code, it's really just a comment!
Any netbeans features that will make my day?
[ "", "php", "netbeans", "" ]
I saw this piece of code: ``` var request = (HttpWebRequest) WebRequest.Create("http://www.google.com"); ``` Why do you need to cast `(HttpWebRequest)`? Why not just use `HttpWebRequest.Create`? And why does `HttpWebRequest.Create` make a `WebRequest`, not a `HttpWebRequest`?
The `Create` method is static, and exists only on `WebRequest`. Calling it as `HttpWebRequest.Create` might look different, but its actually compiled down to calling `WebRequest.Create`. It only appears to be on `HttpWebRequest` because of inheritance. The `Create` method internally, uses the factory pattern to do the actual creation of objects, based on the `Uri` you pass in to it. You could actually get back other objects, like a `FtpWebRequest` or `FileWebRequest`, depending on the `Uri`.
`WebRequest` is an abstract class, which has a factory method `Create` that, depending on the URL passed in, creates an instance of a concrete subclass. Whether you need or want `HttpWebRequest httpreq = (HttpWebRequest)WebRequest.Create(strUrl);` instead of `WebRequest req = WebRequest.Create(strUrl);` depends on your needs, and on what kind of URLs you pass in. If you only pass in HTTP: URL's, then the former code allows you to access the properties and methods the subclass `HttpWebRequest` implements in addition to those defined on the base class `WebRequest`. But if you passed in a FTP: URL then the attempt to cast to `HttpWebRequest` would fail. The latter is generic and won't fail on any of the types of supported URL's but of course without casting to any subclass you can only access the properties and methods the base class defines. *-- via Martin Honnen*
C# HttpWebRequest vs WebRequest
[ "", "c#", "httpwebrequest", "" ]
In my MVVM application, I have a Direct3d render window that shows a bunch of 3d meshes in a scene. In that render window, I want to be able to click on one of those 3d meshes in the scene and move it around, having it follow the mouse cursor. This is typical 3d editor stuff, moving a mesh along in screen space. So I need to be able to get the current mouse position, preferably relative to that Direct3d render window. What's a method to do that? Thanks! Edit: Changing the wording since it was too generic and led to confusion.
[InputManager.Current.PrimaryMouseDevice is probably your best bet.](http://msdn.microsoft.com/en-us/library/system.windows.input.mousedevice_members.aspx) Wrap it up in an interface that exposes the info you need and inject it using your favorite IoC framework.
I think this is the wrong way to think about the MVVM pattern. Let me illustrate this by changing your question slightly. *If you have some custom text editing control, what would be the best way to pass keystroke events to the ViewModel?* Wouldn't it be better to bind the the data to the control and then update the data through the binding as the control is manipulated? So, you have a list of objects you want to show in a 3D view? Pass the objects as a they are, and use template binding to bind each object type to a DataTemplate describing the 3D object, which includes bindings to the X,Y,Z items in the object.
Passing the current mouse position to a ViewModel?
[ "", "c#", "wpf", "xaml", "mvvm", "" ]
I use Eclipse as my IDE, and when I run my application I wish the application itself to run as root. My program currently checks if it is root, and if not it restarts itself with `gksudo`. The output, however, isn't written to the console. I can't use `sudo`, since it doesn't give me a graphical prompt. (While my program is CLI, Eclipse doesn't permit console interaction afaict) What's the "right" way to be elevating my application?
Restrictive execution dominates. I believe that Eclipse does permit console interaction, but a quick and dirty, brute force approach would be to use suid if you're not concerned about security. Or throw up your own graphical prompt in Tkinter/other and use a bit of [Expect magic](http://sourceforge.net/projects/pexpect/) to spawn and respond to the sudo process. Careful with these, however :)
It may not be an ideal solution, but the rare times that I need this same functionality I end up just running Eclipse as root.
Run a Python project in Eclipse as root
[ "", "python", "eclipse", "root", "sudo", "gksudo", "" ]
Let's say I have a class: ``` class NumberCollection { public: typedef std::set<int> SetType; typedef SetType::iterator iterator; void insert(int n); iterator begin(); iterator end(); size_t size() const; iterator difficultBegin(); iterator difficultEnd(); size_t difficultSize() const; private: SetType easySet_, difficultSet_; } ``` Where `insert()` adds an element to `easySet_`. `difficultSet_`'s members change depending on the members of `easySet_`. The problem I am having is that, multiple insertions means that `difficultSet_` is constantly recalculated. So I want `difficultSet_` to be calculated lazily (i.e., only when `difficultBegin()`, `difficultEnd()`, or `difficultSize()` are called). The problem is, then I actually have to make `difficultSet_` into a `mutable` because otherwise `difficultSize()` cannot operate on it. So now my class declaration looks like ``` class NumberCollection { public: typedef std::set<int> SetType; typedef SetType::iterator iterator; void insert(int n); iterator begin(); iterator end(); size_t size() const; iterator difficultBegin(); iterator difficultEnd(); size_t difficultSize() const; private: SetType easySet_; mutable SetType difficultSet_; mutable bool upToDate_; } ``` I feel like this is bad design though. Is there a better way?
That's totally the way to do it. Const can mean binary const, or it can mean conceptually const. Using mutable means you're doing the later, which is fine.
To help understand why to use mutable, we can explore other options. You can solve the same problem using *const\_cast*: ``` size_t NumberCollection::difficultSize() const { if(!upToDate_) { NumberCollection& nonConst = const_cast<NumberCollection&>(*this); nonConst.difficultSet_ = PerformExpensiveCalculationFunction(); nonConst.upToDate_ = true; } // etc.... } ``` Having offered this solution, I'll say that it's inferior to using *mutable*. If a member is marked as *mutable*, then simply by looking at the header I can gather how you are treating it. I don't get this information if you use *const\_cast*. But then somebody might take the other side of the debate, and say that it's better not to expose implementation details in the header.
Dealing with lazy computation in C++ classes
[ "", "c++", "constants", "lazy-evaluation", "mutable", "" ]
The trusty old preprocessor directive in C# appear to work great when I write: ``` #if DEBUG ... (Some code) ... #endif ``` However, attributes enclosed in the conditional block appear to continue to get processed and I get errors indicating such. For instance, surrounding an `[AssemblyVersion(...)]` within the conditional block appears to have no affect. I can go into the details as to why we want to conditionally ignore the [AssemblyVersion(..)], but it's irrelevant. Any ideas?
This works correctly for me. In my AssemblyInfo.cs file, I have the following: ``` #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif ``` Looking at the compiled assembly in Reflector, I see the correct attributes. You should make sure that your DEBUG symbol is only defined in the project **properties** and not any where else in your code as an actual #define DEBUG instruction. If you have it defined directly in code it will only be in effect for that file, not the entire project. Defining it in the project properties will cause it be in effect for the entire project.
I figured it out! There was a key piece of information I neglected to mention: that it was a Workflow project (Guid {14822709-B5A1-4724-98CA-57A101D1B079}). It turns out that there is a bug with the workflow project type, specifically the Workflow.Targets file that is included in the build file. It appears that the preprocessor acts as though the DEBUG constant is defined. You can repro the issue by creating a workflow project and adding this to the AssemblyInfo file: ``` #if DEBUG [assembly: AssemblyFileVersion("1.0.0.0")] #endif ``` Then try a release build. I filed this with MS: <https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=466440> Best regards! -Sean
How do I conditionally enable attributes in C#? "#if DEBUG" isn't working
[ "", "c#", "attributes", "c-preprocessor", "" ]
I've got a situation where I want to get a regexp from the user and run it against a few thousand input strings. In the manual I found that the `RegExp` object has a `.compile()` method which is used to speed things up ins such cases. But why do I have to pass the regexp string to it again if I already passed them in the constructor? Perhaps constructor does the `compile()` itself?
The [`RegExp().compile()` method is deprecated](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/compile). It's basically the same as the constructor, which I assume is why it was deprecated. You should only have to use the constructor nowadays. In other words, you used to be able to do this: ``` var regexp = new RegExp("pattern"); regexp.compile("new pattern"); ``` But nowadays it is not any different from simply calling: ``` var regexp = new RegExp("pattern"); regexp = new RegExp("new pattern"); ```
And with Opera 11, running `RegExp.compile()` will actually cause errors. Evidently, when Opera "compiles" a regex, it wraps the `re.source` string in forward slashes (e.g. `re.source == "^(.)"` becomes `"/^(.)/"`). If you manually compile the regex, Opera doesn't recognize this fact and goes ahead and compiles it again (`re.source` becomes `"//^(.)//"`). Each compile results in an extra set of forward slashes, which changes the meaning of the regular expression and results in errors.
Javascript: what's the point of RegExp.compile()?
[ "", "javascript", "regex", "compilation", "" ]
I'm new to C# and I've been working on a small project to get the feel with Visual Studio 2008. I'm designing the GUI in C#, and I have a TabControl with three GroupBoxes. These three GroupBoxes are anchored to the left and right of the screen and work perfectly when resized horizontally. I would like these three boxes to take up 33% of the height of the screen, and gracefully resize. I've tried messing around with anchoring, but I can't seem to find the answer. I've also been searching for something similar, but unfortunately, searching for positioning containers yields all CSS and HTML stuff. This seems like a pretty common thing to do, but I can't seem to find an easy to way to do it. If someone could point me in the right direction, I'd greatly appreciate it. Thanks!
Try out the [TableLayoutPanel](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx). I believe it does exactly what you want. It allows you to define columns and rows within its area, specifying their width (for columns) and height (for rows) in percentages or pixels. You can then drop a group box into each cell and set its Dock property to Fill, and it will nicely resize along with the cell when the TableLayoutPanel resizes (which can be easily achieved by using docking or anchoring).
This is really a shot in the dark but maybe you could try using split-panels ? Edit: I've just checked in Visual Studio and I think the TableLayoutPanel might do what you want. Edit2: dang, beaten to the punch :)
C# Containers -- Filling a Space Vertically on Resize
[ "", "c#", "user-interface", "resize", "containers", "fill", "" ]
I'm trying to put some folders on my hard-drive into an array. For instance, vacation pictures. Let's say we have this structure: * Set 1 + Item 1 of Set 1 + Item 2 of Set 1 + Item ... of Set 1 * Set 2 + Subset 1 of Set 2 - Item 1 of Subset 1 of Set 2 - Item ... of Subset 1 of Set 2 + Subset 2 of Set 2 + Random file, not a dir. * Set 3 * ... I want to have something like that, as an array. Meaning I have 1 big array and in that array are more arrays. Each set and subset gets its own array. I'm trying to make it look something like this: ``` Array ( [Set 1] => Array([0] => Item 1 of Set 1, [1] => Item 1 of Set 1,...) [Set 2] => Array([Subnet 1] => Array([0] => Item 1 of Subset 1 of Set 2,[1] => ...), [Subnet 2] => Array([0] => ..., ..., ...), ..., [0] => Random File) [set 3] => Array(...) ... ) ``` I came across this: <http://www.the-art-of-web.com/php/dirlist/> But that's not what I'm looking for. I've been meddling with it but it's giving me nothing but trouble. Here's an example, view source for larger resolution(no clicking apparently...). ![Example](https://i637.photobucket.com/albums/uu91/Vordreller/IMG_6038.jpg)
I recommend using [DirectoryIterator](https://www.php.net/directoryiterator) to build your array Here's a snippet I threw together real quick, but I don't have an environment to test it in currently so be prepared to debug it. ``` $fileData = fillArrayWithFileNodes( new DirectoryIterator( '/path/to/root/' ) ); function fillArrayWithFileNodes( DirectoryIterator $dir ) { $data = array(); foreach ( $dir as $node ) { if ( $node->isDir() && !$node->isDot() ) { $data[$node->getFilename()] = fillArrayWithFileNodes( new DirectoryIterator( $node->getPathname() ) ); } else if ( $node->isFile() ) { $data[] = $node->getFilename(); } } return $data; } ```
A simple implementation without any error handling: ``` function dirToArray($dir) { $contents = array(); # Foreach node in $dir foreach (scandir($dir) as $node) { # Skip link to current and parent folder if ($node == '.') continue; if ($node == '..') continue; # Check if it's a node or a folder if (is_dir($dir . DIRECTORY_SEPARATOR . $node)) { # Add directory recursively, be sure to pass a valid path # to the function, not just the folder's name $contents[$node] = dirToArray($dir . DIRECTORY_SEPARATOR . $node); } else { # Add node, the keys will be updated automatically $contents[] = $node; } } # done return $contents; } ```
Deep recursive array of directory structure in PHP
[ "", "php", "arrays", "recursion", "" ]
We have a bit of a battle going on in our development team over this. I would love to hear what others think about this.
In the actual code? No, not unless you're going to have lots of people working on the code who are familiar with .NET but not with C#. In member names? Absolutely. For instance, suppose `Convert.ToSingle` had been called `Convert.ToFloat` - that would be totally confusing for F# developers, for whom "`float`" means "64 bit floating point". My general rule is C# aliases for implementation, CLR types for member names. If you want to find some arguments in favour of using the CLR type names everywhere, Jeff Richter recommends that in "CLR via C#". (If you haven't already got it, buy a copy regardless of this matter - it's a wonderful book.) I didn't agree with the arguments he put forward, but there are some there, anyway.
I generally use the C# alias when declaring a variable, but the CLR types for the static members. I guess I just like the visual distinction it provides.
Can anyone give me a REALLY good reason to use CLR type names instead of C# type names (aliases) in code (as a general practice)?
[ "", "c#", "clr", "" ]
Does anyone know how to set up auto completion to work nicely with python, django, and vim? I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project directory, then I also run pysmell in the project directory. Vim doesn't pick up the django tags, though, and they don't get auto completed. Does anyone know how to set up auto completion in vim so that it will complete the long django functions (like get\_object\_or\_404) as well as classes/functions in my own code? I have poked around on google but haven't found any good resources. Thanks.
First off, thank you for asking this question, as it forced me to figure this out myself and it's great! Here is the page I used as a reference: [PySmell v0.6 released : orestis.gr](http://github.com/orestis/pysmell/tree/v0.6) 1. Install PySmell using the `setup.py install` command. 2. Generate the `PYSMELLTAGS` file for django by going to your `site-packages/django` directory and running: `pysmell . -o ~/PYSMELLTAGS.django` 3. Copy that file to your project directory, and then ran `pysmell .` to generate the project PYSMELLTAGS file 4. Make sure pysmell is in your `PYTHONPATH` (`export PYTHONPATH=${PYTHONPATH}:/path/to/pysmell/`) 5. Run vim (`vim .`) 6. Source `pysmell.vim` (`:source /path/to/pysmell/pysmell.vim`) 7. Set the autocomplete command (`:set omnifunc=pysmell#Complete`) 8. Type ^x^o to autocomplete and it should work I realize this is not a sustainable solution, but you should be able to use this as a start to getting it setup to always work (e.g., add the export to your .bashrc, add the :source to your .vimrc, setup `autocmd FileType python set omnifunc=pysmell#Complete`, etc.) Let me know if this is enough to get you started. It worked for me! **Edit** I simply added this to my .vimrc and as long as the `PYSMELLTAGS` & `PYSMELLTAGS.django` files are in my project root, it works fine without any other work: ``` python << EOF import os import sys import vim sys.path.append("/usr/local/python/lib/python2.5/site-packages") EOF exe ":source ~/src/pysmell/pysmell.vim" autocmd FileType python set omnifunc=pysmell#Complete ```
As I wrote in other places, I developed Jedi. I really think it is far better than all the existing solutions (even PyCharm). <https://github.com/davidhalter/jedi-vim> It is built upon pythoncomplete and much much more powerful! It works for complex code:![completion](https://i.stack.imgur.com/uTCI5.png) And has additional features: ![enter image description here](https://i.stack.imgur.com/5Irvi.png) There is a list of all possible features: * builtin functions/classes support * complex module / function / class structures * ignores syntax and indentation errors * multiple returns / yields * tuple assignments / array indexing / dictionary indexing * exceptions / with-statement * \*args / \*\*kwargs * decorators * descriptors -> property / staticmethod / classmethod * closures * generators (yield statement) / iterators * support for some magic methods: `__call__`, `__iter__`, `__next__`, `__get__`, `__getitem__`, `__init__` * support for list.append, set.add, list.extend, etc. * (nested) list comprehensions / ternary expressions * relative imports * `getattr()` / `__getattr__` / `__getattribute__` * function annotations (py3k feature, are ignored right now, but being parsed. I don't know what to do with them.) * class decorators (py3k feature, are being ignored too, until I find a use case, that doesn't work with Jedi) * simple/usual `sys.path` modifications * `isinstance` checks for if/while/assert
Vim, Python, and Django autocompletion (pysmell?)
[ "", "python", "django", "vim", "" ]
A vector is out by 0.000000001f so the test is failing. Doing the logic in my head yeilds -1.0f, -1.0f but when I wrote the code to pass the test (Using the built in Vector methods) the answer comes back as -0.999999999f, -0.999999999f which is still 'right'. This is C# (Vector2 class provided by the XNA framework) by the way, so I tried adding an epsilon value to each the x and y parameter of the Vector but this didn't work. The way I see it is that by coding the answer, I'm writing the production code. E.g. it would be the same. Surely this is not the right. Any advice?
Please see my answer [here](https://stackoverflow.com/questions/588004/is-javascripts-math-broken/588014#588014). It is not about C#, but the same logic applies.
Unit testing frameworks usually provide asserts for floats that take a precision. For example in Visual Studio Test you can write: ``` Assert.AreEqual(1.0f, 0.9999999999f, 1e-3); // passes Assert.AreEqual(1.0f, 0.9f, 1e-3); // fails ```
Unit testing failing due to 0.000000001f inaccuarcy
[ "", "c#", "unit-testing", "" ]
I'm trying to figure out how to work this thing out .. For some reason, it ends at a certain point.. I'm not very good at recursion and I'm sure the problem lies somewhere there.. Also, even if I checked for cFileName != "..", it still shows up at the end, not sure why but the "." doesn't show up anymore.. ``` void find_files( wstring wrkdir ) { wstring temp; temp = wrkdir + L"\\" + L"*"; fHandle = FindFirstFile( temp.c_str(), &file_data ); if( fHandle == INVALID_HANDLE_VALUE ) { return; } else { while( FindNextFile( fHandle, &file_data ) ) { if( file_data.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY && wcscmp(file_data.cFileName, L".") != 0 && wcscmp(file_data.cFileName, L"..") != 0 ) { find_files( wrkdir + L"\\" + file_data.cFileName ); } else if( file_data.dwFileAttributes != FILE_ATTRIBUTE_HIDDEN && file_data.dwFileAttributes != FILE_ATTRIBUTE_SYSTEM ) { results << wrkdir << "\\" << file_data.cFileName << endl; } } } } ``` After changing those, the program doesn't enumerate the remaining files left.. For example, if there is a sub folder named test, it enumerates everything inside test but doesn't finish enumerating the files inside the original directory specified.
From the [FindFirstFile](http://msdn.microsoft.com/en-us/library/aa364418(VS.85).aspx) documentation: > If the function fails or fails to > locate files from the search string in > the lpFileName parameter, the return > value is INVALID\_HANDLE\_VALUE and the > contents of lpFindFileData are > indeterminate. You should only exit from the one iteration not the whole program: ``` if( fHandle == INVALID_HANDLE_VALUE ) { return; } ``` And this may solve your other problem: ``` else if( file_data.dwFileAttributes != FILE_ATTRIBUTE_HIDDEN && file_data.dwFileAttributes != FILE_ATTRIBUTE_SYSTEM && wcscmp(file_data.cFileName, L".") != 0 && wcscmp(file_data.cFileName, L"..") != 0 ) { results << wrkdir << "\\" << file_data.cFileName << endl; } ``` Also see @fretje's answer as well. It gives another problem that your code has. **Updated new:** You need to use fHandle as a local variable as well, not global variable. Change to: ``` HANDLE fHandle = FindFirstFile( temp.c_str(), &file_data ); ```
You are changing the value of your local `wrkdir` variable: ``` wrkdir = wrkdir + L"\\" + file_data.cFileName; find_files( wrkdir ); ``` I think you have to call `find_files` there like this: ``` find_files( wrkdir + L"\\" + file_data.cFileName ); ``` and not change the value of `wrkdir`.
recursive file search
[ "", "c++", "windows", "winapi", "recursion", "" ]
In SQL Server 2005, is there a concept of a one-time-use, or local function declared inside of a SQL script or Stored Procedure? I'd like to abstract away some complexity in a script I'm writing, but it would require being able to declare a function. Just curious.
You can call `CREATE Function` near the beginning of your script and `DROP Function` near the end.
You can create temp stored procedures like: ``` create procedure #mytemp as begin select getdate() into #mytemptable; end ``` in an SQL script, but not functions. You could have the proc store it's result in a temp table though, then use that information later in the script ..
Can I create a One-Time-Use Function in a Script or Stored Procedure?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "scripting", "" ]
My goal is to echo the argument passed to a function. For example, how can this be done? ``` $contact_name = 'foo'; function do_something($some_argument){ // echo 'contact_name' .... How??? } do_something($contact_name); ```
You can't. If you want to do that, you need to pass the names as well, e.g: ``` $contact_name = 'foo'; $contact_phone = '555-1234'; function do_something($args = array()) { foreach ($args as $name => $value) { echo "$name: $value<br />"; } } do_something(compact('contact_name', 'contact_phone')); ```
Straight off the PHP.net [variables](https://www.php.net/manual/en/language.variables.php#49997) page: ``` <?php function vname(&$var, $scope=false, $prefix='unique', $suffix='value') { if($scope) $vals = $scope; else $vals = $GLOBALS; $old = $var; $var = $new = $prefix.rand().$suffix; $vname = FALSE; foreach($vals as $key => $val) { if($val === $new) $vname = $key; } $var = $old; return $vname; } ?> ```
In PHP, How to Convert an Argument Name into a String
[ "", "php", "string", "arguments", "" ]
I need to show timestamp as shown below in my .Net application: 13/12/2007 5:04 PM EST or 13/12/2007 5:04 PM CST depending upon the US timezone. How do i achieve this functionality using C#?? Thanks for reading.
``` Console.WriteLine(DateTime.Now + " " + TimeZone.CurrentTimeZone.StandardName); ``` returns 6/10/2009 7:45:14 PM Central Standard Time TimeZone.CurrentTimeZone.StandardName will return the long name and I believe you will have to modify your code a bit to get the abr. for each zone.
You can just call a DateTime's `.ToLongDateString()` method and it will format the result according to the settings on the local system.
Showing Datetime using C#
[ "", "c#", "datetime", "" ]
I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?
In the file that has the script, you want to do something like this: ``` import os dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'relative/path/to/file/you/want') ``` This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its [package resources API](http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources) instead. **UPDATE**: I'm responding to a comment here so I can paste a code sample. :-) > Am I correct in thinking that `__file__` is not always available (e.g. when you run the file directly rather than importing it)? I'm assuming you mean the `__main__` script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7): ``` #foo.py import os print os.getcwd() print __file__ #in the interactive interpreter >>> import foo /Users/jason foo.py #and finally, at the shell: ~ % python foo.py /Users/jason foo.py ``` However, I do know that there are some quirks with `__file__` on C extensions. For example, I can do this on my Mac: ``` >>> import collections #note that collections is a C extension in Python 2.5 >>> collections.__file__ '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib- dynload/collections.so' ``` However, this raises an exception on my Windows machine.
It's 2018 now, and Python has already evolved to the `__future__` long time ago. So how about using the amazing [`pathlib`](https://docs.python.org/3/library/pathlib.html) coming with Python 3.4 to accomplish the task instead of struggling with `os`, `os.path`, `glob` , `shutil`, etc. So we have 3 paths here (possibly duplicated): * `mod_path`: which is the path of the *simple helper script* * `src_path`: which contains *a couple of template files* waiting to be copied. * `cwd`: *current directory*, the destination of those template files. and the problem is: **we don't have** the full path of `src_path`, only know **its relative path** to the `mod_path`. Now let's solve this with the amazing [`pathlib`](https://docs.python.org/3/library/pathlib.html): ``` # Hope you don't be imprisoned by legacy Python code :) from pathlib import Path # `cwd`: current directory is straightforward cwd = Path.cwd() # `mod_path`: According to the accepted answer and combine with future power # if we are in the `helper_script.py` mod_path = Path(__file__).parent # OR if we are `import helper_script` mod_path = Path(helper_script.__file__).parent # `src_path`: with the future power, it's just so straightforward relative_path_1 = 'same/parent/with/helper/script/' relative_path_2 = '../../or/any/level/up/' src_path_1 = (mod_path / relative_path_1).resolve() src_path_2 = (mod_path / relative_path_2).resolve() ``` In the future, it's just that simple. --- Moreover, we can select and check and copy/move those template files with [`pathlib`](https://docs.python.org/3/library/pathlib.html): ``` if src_path != cwd: # When we have different types of files in the `src_path` for template_path in src_path.glob('*.ini'): fname = template_path.name target = cwd / fname if not target.exists(): # This is the COPY action with target.open(mode='wb') as fd: fd.write(template_path.read_bytes()) # If we want MOVE action, we could use: # template_path.replace(target) ```
Relative paths in Python
[ "", "python", "relative-path", "path", "" ]
Is there an easy way to convert jQuery code to regular javascript? I guess without having to access or understand the jQuery source code.
The easiest way is to just learn how to do DOM traversing and manipulation with the plain DOM api (you would probably call this: normal JavaScript). This can however be a pain for some things. (which is why libraries were invented in the first place). Googling for "javascript DOM traversing/manipulation" should present you with plenty of helpful (and some less helpful) resources. The articles on this website are pretty good: <http://www.htmlgoodies.com/primers/jsp/> And as Nosredna points out in the comments: be sure to test in all browsers, because now jQuery won't be handling the inconsistencies for you.
This will get you 90% of the way there ; ) ``` window.$ = document.querySelectorAll.bind(document) ``` For Ajax, the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) is now [supported on the current version of every major browser](http://caniuse.com/#search=fetch). For `$.ready()`, [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) has [near universal support](https://caniuse.com/#search=DOMContentLoaded). [You Might Not Need jQuery](http://youmightnotneedjquery.com/?hn) gives equivalent native methods for other common jQuery functions. [Zepto](https://zeptojs.com/) offers similar functionality but weighs in at 10K zipped. There are custom Ajax builds for jQuery and Zepto as well as some [micro frameworks](http://microjs.com/#ajax), but jQuery/Zepto have solid support and 10KB is only ~1 second on a 56K modem.
Is there an easy way to convert jquery code to javascript?
[ "", "javascript", "jquery", "code-conversion", "" ]
I'm currently looking at upgrading the logging mechanism in a medium-to-large-sized Java codebase. Messages are currently logged using static methods on a `Debug` class, and I have recommended switching from this to something like SLF4J or commons-logging. The application architect prefers that I encapsulate the dependency on SLF4J (possibly by wrapping it up in the aforementioned `Debug` class). This will make it easier to change the logging implementation in the future. This seems like overkill to me, as SLF4J is already abstracting the concrete logging implementation. Is it worth wrapping a 3rd-party logging abstraction like SLF4J in *another* home-grown abstraction?
I entirely agree with you: wrappers of wrappers of wrappers are getting out of hand. I suspect that architect doesn't realize how SLF4J in particular can easily wrap any other logging system, so that "changing implementation" is perfectly feasible without yet another layer of wrappage.
I guess the motivation behind the architect's desire to wrap the wrapper (i.e. SLF4J), is to isolate your application from SLF4J. Clearly, invoking the SLF4J API from within your application creates a dependency on SLF4J. However, it is equally legitimate to want to apply the isolation principle repeatedly as discussed below. It reminds me of Richard Dawkins' question: If God created the universe, then who created God? Indeed, you could also apply the isolation principle on the wrapper that wraps SLF4J. The cause of isolation would be ill served if the SLF4J-wrapper was somehow inferior to SLF4J. Although possible, it is rather rare for a wrapper to equal or surpass the original. SWT can be cited as a noteworthy counter-example. However, SWT is a sizable project with a significant cost. More to the point, an SLF4J-wrapper by definition depends on SLF4J. It is bound to have the same general API. If in the future a new and significantly different logging API comes along, code that uses the wrapper will be equally difficult to migrate to the new API as code that used SLF4J directly. Thus, the wrapper is not likely to future-proof your code, but to make it heavier by adding an additional indirection. In short, even if you didn't have anything better to do, you shouldn't waste your time wrapping SLF4J because the added value of your wrapper is guaranteed to be near zero. The topic is also broached in an [SLF4J FAQ entry](http://slf4j.org/faq.html#optional_dependency).
Is it worth wrapping a logging framework in an additional layer?
[ "", "java", "logging", "encapsulation", "slf4j", "apache-commons-logging", "" ]
I wanted to use [JET (Java Emitter Templates)](http://www.eclipse.org/modeling/m2t/downloads/?project=jet) in my Netbeans projects, but had to find out that JET heavily depends on Eclipse libraries. Is there something similar to JET, but as a standalone project? Something which is open source and well maintained? Futhermore, is "code generation" the common term for such tools?
I ended up using **ERB (Ruby's template engine)**. Works great in Netbeans! I define custom ant task which generates source files by calling ERB (whose results are placed inside a non-versioned special directory). The ant task is overriding Netbeans' **"-pre-compile"** task.
If you are using Maven, you can use JET templates with the [maven-jet-plugin](http://mvnrepository.com/artifact/com.tikal/tikal-maven-jet-plugin). This seems to be the [source code](https://github.com/mark2b/maven-jet-plugin). And here the [documentation](https://github.com/mark2b/maven-jet-plugin/tree/master/src/site/apt). It is not actively maintained but works pretty well and follows the JET spec. I've used it with templates and skeletons. It's self contained, doesn't depend on Eclipse, and doesn't introduce any transitive dependencies to your project.
Is there something like JET (Java Emitter Templates) but without Eclipse-dependencies?
[ "", "java", "code-generation", "eclipse-jet", "" ]
I have some Java (5.0) code that constructs a DOM from various (cached) data sources, then removes certain element nodes that are not required, then serializes the result into an XML string using: ``` // Serialize DOM back into a string Writer out = new StringWriter(); Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "no"); tf.transform(new DOMSource(doc), new StreamResult(out)); return out.toString(); ``` However, since I'm removing several element nodes, I end up with a lot of extra whitespace in the final serialized document. Is there a simple way to remove/collapse the extraneous whitespace from the DOM before (or while) it's serialized into a String?
You can find empty text nodes using XPath, then remove them programmatically like so: ``` XPathFactory xpathFactory = XPathFactory.newInstance(); // XPath to find empty text nodes. XPathExpression xpathExp = xpathFactory.newXPath().compile( "//text()[normalize-space(.) = '']"); NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET); // Remove each empty text node from document. for (int i = 0; i < emptyTextNodes.getLength(); i++) { Node emptyTextNode = emptyTextNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } ``` This approach might be useful if you want more control over node removal than is easily achieved with an XSL template.
Try using the following XSL and the `strip-space` element to serialize your DOM: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" omit-xml-declaration="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> ``` <http://helpdesk.objects.com.au/java/how-do-i-remove-whitespace-from-an-xml-document>
How to strip whitespace-only text nodes from a DOM before serialization?
[ "", "java", "xml", "dom", "whitespace", "" ]
I am currently working on a large-scale website, that is very dynamic, and so needs to store a large volume of information in memory on a near-permanent basis (things like configuration settings for the checkout, or the tree used to implement the menu structure). This information is not session-specific, it is consistent for every thread using the website. What is the best way to hold this data globally within ASP, so it can be accessed when needed, instead of re-loaded on each use?
Any `AppSettings` in `web.config` are [automatically cached](https://stackoverflow.com/questions/274762/asp-net-where-how-is-web-config-cached) (i.e., they aren't read from the XML every time you need to use them). You could also manually [manipulate the cache yourself](http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx). **Edit**: Better links... * [Add items to the cache](http://msdn.microsoft.com/en-us/library/18c1wd61.aspx) * [Retrieve items from the cache](http://msdn.microsoft.com/en-us/library/6hbbsfk6.aspx) * [Caching Application Data](http://msdn.microsoft.com/en-us/library/6hbbsfk6.aspx)
It's not precisely clear whether your information is session specific or not...if it is, then use the ASP Session object. Given your description of the scale, you probably want to look at storing the state in Sql Server: <http://support.microsoft.com/kb/317604> That's the 101 approach. If you're looking for something a little beefier, then check out memcached (that's pronounced Mem-Cache-Dee): <http://www.danga.com/memcached/> That's the system that apps like Facebook and Twitter use. Good luck!
Hold global data for an ASP.net webpage
[ "", "c#", "asp.net", "memory-management", "global", "" ]
Hey I'm automating PowerPoint and Excel from a C# WinForms application; what I do is read slides from PowerPoint and save them in Excel and then quit both apps. Excel quits successfully but PowerPoints doesn't quits. The problem is when I convert first time it doesnt quits, but when I convert again it does. Here is my code ``` try { PowerPoint.Application ppApp; PowerPoint.Presentation ppPres; List<Company> companies = new List<Company>(); ppApp = new PowerPoint.Application(); ppApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue; ppApp.WindowState = Microsoft.Office.Interop.PowerPoint.PpWindowState.ppWindowMinimized; ppPres = ppApp.Presentations.Open(fileTxtBox.Text, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue); int slides = ppPres.Slides.Count; for (int slide = 1; slide <= slides; slide++) { int rows = 1; PowerPoint.Cell cell; int shape = 1; for (; shape < ppPres.Slides[slide].Shapes.Count; shape++) { if (ppPres.Slides[slide].Shapes[shape].HasTable == Microsoft.Office.Core.MsoTriState.msoTrue) { cell = ppPres.Slides[slide].Shapes[shape].Table.Cell(1, 1); if (cell.Shape.TextFrame.TextRange.Text.Trim().ToLower().Contains("realized")) { rows = ppPres.Slides[slide].Shapes[shape].Table.Rows.Count; break; } } } Company comp = new Company(rows); InitializeCompany(ref comp, ppPres.Slides[slide]); companies.Add(comp); } SaveInExcel(companies); ppPres.Close(); ppPres = null; ppApp.Quit(); ppApp = null; return; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { GC.Collect(); GC.WaitForPendingFinalizers(); } ```
Shutting down your Microsoft Office application can seem tricky to get right at first, but once you establish the correct order of operations, it's actually not very hard at all. Releasing your MS Office application can be done safely and effectively in two stages: (1) First release all the minor objects to which you do not hold a reference within a named variable. You do this via a call to [GC.Collect()](http://msdn.microsoft.com/en-us/library/system.gc.collect.aspx) and then [GC.WaitForPendingFinalizers()](http://www.bing.com/search?setlang=en-US&mkt=en-US&q=gc.waitforpendingfinalizers) . Note that if you are using Visual Studio Tools for Office (VSTO), then you need to call this pair of commands **twice** in order to get the COM objects to successfully release. You are not using VSTO, however, so calling them once is sufficient. (2) Then explicitly release the objects which you hold via a named variable using a call to [Marshall.FinalReleaseComObject()](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.finalreleasecomobject.aspx) on each variable you have. Remember to explicitly release **all** variables that you have to COM components. If you miss even one, then your MS Office application will hang. In your code, you seem to have three named variables that hold a reference to your PowerPoint application: `ppApp`, `ppPres`, and `cell`. Taking this all into account, I think that your cleanup should look something like the following, which makes use of `using System.Runtime.InteropServices` either within the namespace or at the top of the code document: ``` // using System.Runtime.InteropServices // Cleanup: GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.ReleaseComObject(cell); ppPres.Close(); Marshal.ReleaseComObject(ppPres); ppApp.Quit(); Marshal.ReleaseComObject(ppApp); ``` Give it a try, I think this should work for you... (If not, you might have to show even more of your code.) For further information, I give a detailed explanation on how to properly release an Excel application here: [How to properly clean up Excel interop objects in C#](https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c/159419#159419). Hope this helps, let us know how it goes... -- Mike
Here is a MSDN article that describes the problem and solution <http://msdn.microsoft.com/en-us/library/aa679807%28office.11%29.aspx> basically recomondation is to do(Note : two iterations of GC.Collect() ``` GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); ```
PowerPoint Launched via C# does not Quit
[ "", "c#", "com", "powerpoint", "" ]
Following snippet wouldn't compile. With following error: > Cannot implicitly convert type 'Container<ChildClass>' to 'Container<BaseClass>' ``` class BaseClass {} class ChildClass : BaseClass {} class Container<T> where T : BaseClass {} class Program { static void Main() { // why doesn't this work? Container<BaseClass> obj = new Container<ChildClass>(); } } ``` Is this by design? If it is, what is the reason?
(made wiki, in case of dups) C# (3.0) doesn't support covariance of lists etc. C# 4.0 will support **limited** [co|contra]variance, but [still not lists](http://marcgravell.blogspot.com/2009/02/what-c-40-covariance-doesn-do.html). The problem is that with: ``` Container<BaseClass> obj = new Container<ChildClass>(); ``` I could do: ``` obj.Add(new SomeOtherSubclass()); // SomeOtherSubclass : BaseClass ``` which would compile, but not work. This behaviour *is* supported for arrays, but largely for historic reasons.
Yo, If you want the killer article on covariance/contravariance on C#, check out the eric lippert blog, "fabulous adventures in coding". First, this is my favortie blog's name, and second eric wrote the best sequence of articles on (co|contra)variance: <http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx> This is as good as [Breaking Bad](http://epguides.com/BreakingBad/).
C#: No implict conversion from Class<Child> to Class<Base>
[ "", "c#", "generics", "inheritance", "language-features", "language-design", "" ]
I have a column where some users are not entering spaces (i.e.: .........................................) and it is stretching my TD column. Is there a way to force line breaks in html with a simple option? If not, I think I am going to have to break the line up myself, which would not be optimal, as I would have to determine the best places to break a line, and I don't want to do that. I am looking for something that will work in the 3 main browsers (ie/firefox/safari) Here is my code: ``` <td valign="top"> <br> <strong><?php echo $common->stripHtml($row['one_liner']); ?></strong> <br> <hr> <?php if (strlen($row['self_description']) > 240) { echo substr($common->stripHtml($row['self_description']), 0, 240)."... <a href='viewprofile.php?i=".$row['user_id']."'>more</a>"; } else { echo $common->stripHtml($row['self_description']); } ?> </td> ```
A fixed-width cell combined with hiding overflow content should do the trick The CSS: ``` table { table-layout:fixed; } table td { overflow:hidden; } ``` Targeting this HTML: ``` <!-- This width specification ought to be in the top-most <td> or <th> --> <td width="100" >...</td> ```
While you could manually add line breaks with PHP, you can also use the "[overflow](http://www.w3schools.com/css/pr_pos_overflow.asp)" CSS property to determine how the cell should display its data. If you set the overflow to "auto", a scrollbar should appear within the cell, and if you set the overflow to "hidden", the contents will be hidden beyond the width you have set.
Setting the Max length in a <TD>
[ "", "php", "html", "" ]
I have a field in a table that is boolean, a range of records have no value (not true or false). How do I write my SQL statement to find these? I have tried the following SQL statements without success: ``` 1) SELECT * FROM table WHERE field = NULL 2) SELECT * FROM table WHERE field != TRUE AND field != FALSE ``` Any help would be greatly appreciated. Many Thanks, Ben
In TSQL, you need to use `IS` rather than `=` when comparing with `NULL`: ``` SELECT * FROM table WHERE field IS NULL ```
Try ``` select * from table where field IS null ```
Checking database for NULL boolean value
[ "", "sql", "postgresql", "null", "boolean", "" ]
I need to set an arbitrary style to a span via javascript. I know I can do things like: `span.style.height="250px"`; But I need to be able to insert a random full style definition from a template for example ``` float:left; text-decoration:underline; cursor:pointer; color:blue; ``` Is there a way to do that in Javascript? Something like: `element.style="all style definition here";`
How about the .style.cssText property? [Here's Microsoft's explanation.](http://msdn.microsoft.com/en-us/library/ms533698(VS.85).aspx) Throw it the styles you'd like to apply like so: ``` document.getElementById('myEl').style.cssText = 'float:left;margin-top:75px;'; ``` As for browser support, although it was IE-proprietary I believe it's well-supported (works in the IEs, FF3, and Safari 3.2 WIN at least).
If you want it to be lightweight, create a function such as: ``` function setStyles(element, styles) { for(var s in styles) { element.style[s] = styles[s]; } } ``` Then you would pass the styles in as an object literal: ``` setStyles(element, {float: "left", textDecoration: "underline", cursor: "pointer", color: "blue"}); ``` Note that the style references passed in have to follow the naming from a JavaScript standpoint, since the function simply changes the styles by accessing the element's `style` object through JavaScript. If you must take your style input from a string then you could quite easily parse it and create the object literal.
setting a whole style string to an element from javascript (not individual style parameters)
[ "", "javascript", "css", "stylesheet", "" ]
How can I dynamically create an array in C#?
You can also use the `new` operator just like with other object types: ``` int[] array = new int[5]; ``` or, with a variable: ``` int[] array = new int[someLength]; ```
I'd like to add to Natrium's answer that generic collections also support this .ToArray() method. ``` List<string> stringList = new List<string>(); stringList.Add("1"); stringList.Add("2"); stringList.Add("3"); string[] stringArray = stringList.ToArray(); ```
Dynamically Create an Array in C#
[ "", "c#", "" ]
What would this line of C# using Lambda expression be in VB.Net? ``` string s = blockRenderer.Capture(() => RenderPartialExtensions.RenderPartial(h, userControl, viewData)); ``` Something with function of - but I can't figure out exactly how...
It should be something like this: ``` Dim s As String = blockRenderer.Capture(Function() RenderPartialExtensions.RenderPartial (h, userControl, viewData)) ```
Check out this online [C# to VB.NET converter](http://www.developerfusion.com/tools/convert/csharp-to-vb/). It doesn't always get things perfect, but it does a pretty good job all the times I've used it. ``` Dim s As String = blockRenderer.Capture(Function() RenderPartialExtensions.RenderPartial(h, userControl, viewData)) ```
Lambda expression from C# to VB.Net
[ "", "c#", "vb.net", "lambda", "" ]
i want to convert my window application, that i developed in VS2005 using C#, as an Add in for Visual Studio 2005. How can i do it.?
There is a nice quick start tutorial in here : <http://www.codeproject.com/KB/macros/LineCounterAddin.aspx> It was enough for me to start.
You could try looking at [MSDN](http://msdn.microsoft.com/en-us/vsx/default.aspx) or [books](https://rads.stackoverflow.com/amzn/click/com/0470230843), but you might find the VS2005 information hidden behind the VS2008 stuff...
How to create addin for VS2005.?
[ "", "c#", "visual-studio", "" ]
My app needs to open an Access mdb file and an xml file (which are stored in bin\Release) to read and write data. The question is, if I am to publish it, how should I include them so that the setup file will install them into the same folder that the exe will run from (Local Settings\Apps\2.0(...))? I already tried adding them to the project but then they ended up in the next folder to the one containing the exe. Alternatively: If I can't with vc# express, is there another way to do this (through a 3rd party software maybe)? Thanks :)
<http://wix.sourceforge.net/> WiX - Windows Installer XML is an OS tool you can use to build an installer you can tell it where to put each file and create folders, etc.
Visual Studio Standard Edition and up also include a built-in designer for creating installation files that can do what you're asking for. If you want to stick with Express, WiX is probably the better choice, though.
(msvc# express) publish c# project to include a file (e.g. .MDB, .XML)
[ "", "c#", "publish", "" ]
I have a python script that i want to run from the command line but unsure how to run it. Thanks :)
`python myscript.py`
I do it this way: ``` C:\path\to\folder> yourscript.py ```
windows command line and Python
[ "", "python", "windows", "command-line", "" ]
I'm looking to use a local webserver to run a series of python scripts for the user. For various unavoidable reasons, the python script must run locally, not on a server. As a result, I'll be using HTML+browser as the UI, which I'm comfortable with, for the front end. I've been looking, therefore, for a lightweight web server that can execute python scripts, sitting in the background on a machine, ideally as a Windows service. Security and extensibility are not high priorities as it's all running internally on a small network. Should I run a native python webserver as a Windows service (in which case, how)? Or is it just as easy to install Apache onto the user's machine and run as CGI? Since this is all local, performance is not an issue either. Or am I missing something obvious?
Don't waste a lot of time creating Windows service. Don't waste a lot of time on Windows Apache. Just make a Python service that responds to HTTP requests. Look at <https://docs.python.org/2/library/basehttpserver.html> <https://docs.python.org/3/library/http.server.html> for version 3 Python offers an HTTP server that you can extend with your server-side methods. Look at <http://docs.python.org/library/wsgiref.html> Python offers a WSGI reference implementation that makes your server easy and standards-compliant. Also <http://fragments.turtlemeat.com/pythonwebserver.php> --- "I'm trying to *avoid* making the user run python stuff from the command prompt." I don't see how clicking a web page is any different from clicking desktop icons. Starting a web server based on Python is relatively easy, once you have the web server. First, build the server. Later, you can make sure the server starts. Let's look at some ways. 1. Your user can't use a random browser to open your local page. They need a bookmark to launch "localhost:8000/myspecialserverinsteadofthedestop/" That bookmark can be a .BAT file that (1) runs the server, (2) runs firefox with the proper initial URL. 2. You can put the server in the user's start-this menu. 3. You can make your Python program a windows "service".
The wasiest step would be navigate to folder where your files are located and running http.server module ``` cd /yourapp python3 -m http.server ``` the you should see something like this in console > Serving HTTP on 0.0.0.0 port 8000 (<http://0.0.0.0:8000/>) ...
How can I create an local webserver for my python scripts?
[ "", "python", "webserver", "simplehttpserver", "" ]
I'm trying to load a java .class file dynamically and call it by reflection. I've got a class called Foo; it has an empty constructor and has one method called doit() which takes a String argument and returns a String. Also it reverses the String. Here is my code: ``` URL url = new URL("file://C:/jtest/"); URLClassLoader loader = new URLClassLoader(new URL[]{url}); Class<?> cl = loader.loadClass("Foo"); Constructor<?> cons = cl.getConstructor((Class[])null); Object ins = cons.newInstance(new Object[]{}); Method meth = cl.getDeclaredMethod("doit", String.class); Object ret = meth.invoke(ins, new Object[]{"!dlroW olleH"}); System.out.println((String)ret); ``` As expected this prints "Hello World!". However, it takes about **30 seconds** to complete. I know reflection is slow, but I expect it to be 10 ms or something. I'm using Eclipse with JRE 1.6.0\_13, and I'm running Windows Vista. What am I doing wrong here? Thanks. **Edit:** I've profiled the code, and all of its time is used in the third line(loadClass()). Everything else happens instantly. **Edit:** I've put the code in a loop; the slow function somehow gets optimized and takes 30 seconds only on the first loop. **Edit:** I've found the solution. Instead of: `URL url = new URL("file://C:/jtest/");` I changed it to: `URL url = new URL("file:/C:/jtest/");` Now it works perfectly. I don't know why it works, but I don't see how I (and 5 other people) could have missed that. Now I feel dumb..
At 30 seconds, you should be able to "profile" your code and see exactly where the problem lies (in loading of the class? in creating the instance? in looking up the method? etc?) Since it's taking 30 seconds (and not something much smaller, on the order of 10ms or so), you can just use `System.out.println(new Date());` between each line of your code. I suspect you'll find it's the loader.loadClass(String) taking so long - and I suspect that you'll find you either have a very long classpath, or a classpath that includes a network resource of some sort.
For your info: Maybe a bit late for you, but I stumbled upon the same issue and found this post. It looks like the // is forcing a remote search, if you run with -verbose:class there is a UnknownHostException loaded so this must be thrown internally during class loading. I tried the following: URL url = new URL("file://localhost/C:/jtest/"); and this works (almost) as quickly as your single slash solution.
Java classloading running extremely slow?
[ "", "java", "performance", "reflection", "" ]
For performance reasons, I am using the the [Curiously Reoccuring Template Pattern](http://ubiety.uwaterloo.ca/~tveldhui/papers/techniques/techniques01.html) to avoid virtual functions. I have lots of small commands which execute millions of times. I am trying to fit this into the Command Pattern. I want to add tons of commands to a queue, and then iterate through them executing each one by one. Each Command uses a CRTP to avoid virtual functions. The problem I am running into is that the Command pattern is typically implemented using a vector of pointers. But when the Command class is templated, it becomes hard to pass around generic Command pointers. I'm not a C++ expert, so perhaps there is an obvious way to store a vector of templated command objects? I have been trying to use something like: ``` boost:ptr_vector commands; AddCommand(Command* command) { commands.push_back(command); } ``` The problem is `Command` is not a type, so `Command* command` gives a compile error. I need to use `Command<CommandType>`, but that won't work because I need the queue to hold different types of commands. Any ideas for solutions? Or are virtual functions my only option? ADDED: The command objects are part of a monte carlo simulation algorithm. So you might have, Command be a random number from a normal distribution, where the parameters of the normal distribution are part of the class. So the command pattern fits very nicely. I have lots of calls, in a particular order, to functions that need to maintain state.
The CRTP does its magic by resolving the run time type of the object at compile time so that the compiler can inline the function calls. If you have a vector of pointers to a generic type, the compiler cannot determine the specific concrete type, and will not be able to do its compile time resolution. From just the information you have in your question, I think virtual functions are your best option. However, virtual functions are not that slow. They are slower than an in-lined function, sure, but in many cases they are plenty fast enough! Especially if your process is bounded by I/O time instead of processing time. [One of the answers](https://stackoverflow.com/questions/667634/what-is-the-performance-cost-of-having-a-virtual-method-in-a-c-class/667680#667680) to [this question](https://stackoverflow.com/questions/667634/what-is-the-performance-cost-of-having-a-virtual-method-in-a-c-class) has some more in depth discussion of this issue. To summarize, the overhead for a virtual function call will likely be measured in nanoseconds. It is more complicated than that, but the point is that you shouldn't be afraid of virtual functions unless your function is doing something really trivial like a single assignment. You said that your commands were small, so perhaps this is the case. I'd try doing a quick prototype with virtual functions and see if that gives acceptable performance.
Unless you are building your command queue during compile time, what you want is impossible.
Command pattern without virtual functions (C++)
[ "", "c++", "performance", "design-patterns", "templates", "virtual-functions", "" ]
In C# i want to create a panel that has the properties of a MDI container ie. isMdiContainer = true. I tried something like this ``` form.MDIParent = this.panel1; ``` But that dont work. Any suggestions?
You could create custom form, remove all borders, and toolbars to make it look as closely to a panel as possible. Then make that new custom form a MdiContainer. Basically, you can only set the IsMDIContainer property on a Form. This means that only a form can be a MdiContainer.
It is possible to create an MDI-panel and show forms in that panel, something like the code below will do the job Mdi-Panel definiton: ``` public class MdiClientPanel : Panel { private Form mdiForm; private MdiClient ctlClient = new MdiClient(); public MdiClientPanel() { base.Controls.Add(this.ctlClient); } public Form MdiForm { get { if (this.mdiForm == null) { this.mdiForm = new Form(); /// set the hidden ctlClient field which is used to determine if the form is an MDI form System.Reflection.FieldInfo field = typeof(Form).GetField("ctlClient", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); field.SetValue(this.mdiForm, this.ctlClient); } return this.mdiForm; } } } ``` Usage: ``` /// mdiChildForm is the form that should be showed in the panel /// mdiClientPanel is an instance of the MdiClientPanel myMdiChildForm.MdiParent = mdiClientPanel1.MdiForm; ```
C# Panel As MDI Container
[ "", "c#", "forms", "panel", "mdi", "" ]
[EDITED - really sorry, the code I quoted was wrong - have changed the message below to reflect this. Apologies! Thank you for your patience.] I'm new to regular expressions and want to match a pattern in Java (following on from this solution - [Java string - get everything between (but not including) two regular expressions?](https://stackoverflow.com/questions/962122/java-string-get-everything-between-but-not-including-two-regular-expressions)). The string is [EDITED]: ``` <row><column name='_id'>1</column></row><row><column name='text'>Header\n\n\ntext</column></row><row><column name='pwd'>password</column></row> ``` And I want to return only what's between the **column name='text'** tags, so: ``` Header\n\n\ntext ``` I've got the code below [EDITED], but it doesn't match. Any ideas on how I need to change the Pattern? Thanks! ``` package test; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Regex { public static void main(String[] args) { Pattern p = Pattern.compile( "<row><column name='text'>(.*)</column></row>", Pattern.DOTALL ); Matcher matcher = p.matcher( "<row><column name='_id'>1</column></row><row><column name='text'>Header\n\n\ntext</column></row><row><column name='pwd'>password</column></row>" ); if(matcher.matches()){ System.out.println(matcher.group(1)); } } } ```
The (unedited) code you posted works fine for me... it matches and prints out the message you expect. The edited code doesn't work, however if you change the regex very slightly to look like this: ``` Pattern p = Pattern.compile( ".*<row><column name='text'>(.*)</column></row>.*", Pattern.DOTALL ); ``` you get a match: ``` Header text</column></row><row><column name='pwd'>password ``` That's probably not what you actually want though, so you'll need to further refine the regex. Using regular expressions to handle xml/html parsing isn't generally a good approach. Yishai's suggestion of using an XML parser is a better way to do it, otherwise you'll most likely end up with a tremendously complicated and inflexible regular expression.
Perhaps what you really want to get to is this: ``` public static void main(String[] args) { Pattern p = Pattern.compile( "<row><column name='(.*?)'>(.*?)</column></row>", Pattern.DOTALL ); Matcher matcher = p.matcher( "<row><column name='text'>Header\n\n\ntext</column></row>" ); if(matcher.matches()){ System.out.println(matcher.group(2)); } } ``` Because your real example could have anything in the name= value (at least that would seem much more real-world). That being said, if this gets much more non-trivial, you might want to look at doing this as a SAX parser (that is built in to the JDK 1.5+ so it isn't necessarily a library dependency issue). Regex is a better way to parse XML if you really don't care much about document structure and just want to suck something trivial out of it. However, if you start getting into attributes and caring what they are on the XML, continuing down the regex route is going to be reinventing the wheel.
Java - how to match regex Pattern containing single quotes?
[ "", "java", "regex", "string", "" ]
I have a require ment to read data from a table(SQL 2005) and send that data to other application for every 5 seconds. I am looking for the best approach to do the same. Right now I am planning to write a console application(.NET and C#) which will read the data from sql server 2005(QUEUE table which will be filled through different applications) and send to other application through TCP/IP(Central server). Run that console application under schedule task for every 5 seconds. I am assuming scheduled task will take care to discard new run event if task is already running(avoid to run concurrent executions). Does any body come accross similar situation? Please share your experience and advice me for best approach. Thanks in advance for your valuable time spending for my request. -Por-hills-
We have done simliar work. If you are going to query a sql database every 5 seconds, be sure to use a stored procedure that is optimized to be very fast. It should not update data unless aboslutely necessary. This approach is typically called 'polling' and I've found that it is acceptable if your sqlserver is not otherwise bogged down with too many other calls. In approaches we've used, a Windows Service that does the polling works well. To communicate results to another app, it all depends on what your other app is doing and what type of interface you can make into it, and how quickly you need the results. The WCF class libraries from Microsoft provide many workable approaches for real time communication. My preference is to write to the applications database, and then have the application read the data (if it works for that app). If you need something real time, WCF is the way to go, and I'd suggest using a stateless protocol like http if < 5 sec response time is required, (using standard HTTP posts), or TCP/IP if subsecond response time is required.
since I assume your central storage is also SQL 2005, have you considered using what SQL Server 2005 offers out of the box to achieve your requirements? Rather than pool every 5 seconds, marshal and unmarshal TCP/IP, implement authentication and authorization for the TCP/IP pipe, scale TCP transmission with boxcaring, manage message acknowledgments and retries, deal with central site availability, fragment large messages, implement fairness in transmission and so on and so forth, why not simply use [Service Broker](http://msdn.microsoft.com/en-us/library/ms166043(SQL.90).aspx)? It does all you need and more, out of the box, already tested, already tuned for performance and scalability. Getting reliable messaging right is not trivial and you should focus your efforts in meeting your business specifics, not reiventing the wheel.
Need advice to query data from sql server on every 5 seconds and send it to other app.(.NET C#)
[ "", "c#", ".net", "sql-server", "" ]
I've created a pretty basic system here at work that does what Google analytics does (extremely simplistic in comparison) and it works quite well, but like Google Analytics it requires each page to reference a JavaScript file. Is there any way to make all of our pages that are served from IIS reference this Javascript file? I would like to capture these stats for every page. Any ideas? Thanks
If you're dealing with static HTML files your best bet seems to be [this previous question](https://stackoverflow.com/questions/638866/can-i-make-iis-add-inject-html-to-every-page-it-serves). If you have an ASP site going, and you already have a header or layout file, I'd recommend putting it in there.
Hmm, it [looks like you are looking for this](http://learn.iis.net/page.aspx/480/sample-web-analytics-tracking-module/).
How to force every page to load a certain javascript file?
[ "", "javascript", "iis", "analytics", "enterprise", "" ]
In python, strings may be unicode ( both utf-16 and utf-8 ) and single-byte with different encodings ( cp1251, cp1252 etc ). Is it possible to check what encoding string is? For example, ``` time.strftime( "%b" ) ``` will return a string with text name of a month. Under MacOS returned string will be utf-16, under Windows with English local it will be single byte with ascii encoding, and under Windows with non-English locale it will be encoded via locale's codepage, for example cp1251. How can i handle such strings?
Strings don't store any encoding information, you just have to specify one when you convert to/from unicode or print to an output device : ``` import locale lang, encoding = locale.getdefaultlocale() mystring = u"blabla" print mystring.encode(encoding) ``` UTF-8 is *not* unicode, it's an encoding of unicode into single byte strings. The best practice is to work with unicode everywhere on the python side, store your strings with an unicode reversible encoding such as UTF-8, and convert to fancy locales only for user output.
charset encoding detection is very complex. however, what's your real purpose for this? if you just want to value to be in unicode, simply write ``` unicode(time.strftime("%b")) ``` and it should work for all the cases you've mentioned above: * mac os: unicode(unicode) -> unicode * win/eng: unicode(ascii) -> unicode * win/noneng: unicode(some\_cp) -> will be converted by local cp -> unicode
string encodings in python
[ "", "python", "unicode", "codepages", "" ]
If we want to get a value from a method, we can use either return value, like this: ``` public int GetValue(); ``` or: ``` public void GetValue(out int x); ``` I don't really understand the differences between them, and so, don't know which is better. Could you explain this to me?
Return values are almost *always* the right choice when the method doesn't have anything else to return. (In fact, I can't think of any cases where I'd *ever* want a void method with an `out` parameter, if I had the choice. C# 7's `Deconstruct` methods for language-supported deconstruction acts as a very, very rare exception to this rule.) Aside from anything else, it stops the caller from having to declare the variable separately: ``` int foo; GetValue(out foo); ``` vs ``` int foo = GetValue(); ``` Out values also prevent method chaining like this: ``` Console.WriteLine(GetValue().ToString("g")); ``` (Indeed, that's one of the problems with property setters as well, and it's why the builder pattern uses methods which return the builder, e.g. `myStringBuilder.Append(xxx).Append(yyy)`.) Additionally, out parameters are slightly harder to use with reflection and usually make testing harder too. (More effort is usually put into making it easy to mock return values than out parameters). Basically there's nothing I can think of that they make *easier*... Return values FTW. EDIT: In terms of what's going on... Basically when you pass in an argument for an "out" parameter, you *have* to pass in a variable. (Array elements are classified as variables too.) The method you call doesn't have a "new" variable on its stack for the parameter - it uses your variable for storage. Any changes in the variable are immediately visible. Here's an example showing the difference: ``` using System; class Test { static int value; static void ShowValue(string description) { Console.WriteLine(description + value); } static void Main() { Console.WriteLine("Return value test..."); value = 5; value = ReturnValue(); ShowValue("Value after ReturnValue(): "); value = 5; Console.WriteLine("Out parameter test..."); OutParameter(out value); ShowValue("Value after OutParameter(): "); } static int ReturnValue() { ShowValue("ReturnValue (pre): "); int tmp = 10; ShowValue("ReturnValue (post): "); return tmp; } static void OutParameter(out int tmp) { ShowValue("OutParameter (pre): "); tmp = 10; ShowValue("OutParameter (post): "); } } ``` Results: ``` Return value test... ReturnValue (pre): 5 ReturnValue (post): 5 Value after ReturnValue(): 10 Out parameter test... OutParameter (pre): 5 OutParameter (post): 10 Value after OutParameter(): 10 ``` The difference is at the "post" step - i.e. after the local variable or parameter has been changed. In the ReturnValue test, this makes no difference to the static `value` variable. In the OutParameter test, the `value` variable is changed by the line `tmp = 10;`
What's better, depends on your particular situation. **One** of the reasons `out` exists is to facilitate returning multiple values from one method call: ``` public int ReturnMultiple(int input, out int output1, out int output2) { output1 = input + 1; output2 = input + 2; return input; } ``` So one is not by definition better than the other. But usually you'd want to use a simple return, unless you have the above situation for example. **EDIT:** This is a sample demonstrating one of the reasons that the keyword exists. The above is in no way to be considered a best practise.
Which is better, return value or out parameter?
[ "", "c#", "reference", "" ]
I have a query which does a number of joins and has a few criteria in the WHERE clause, and I'm ending up with a result which essentially looks like this: ``` | userId | date | otherData | |--------+------------+------------| | 1 | 2008-01-01 | different | | 1 | 2009-01-01 | info | | 1 | 2010-01-01 | for | | 2 | 2008-01-01 | each | | 3 | 2008-01-01 | row | | 3 | 2009-01-01 | here | ``` So, in essence for each user, there will be one or more dates in the past, and 0 or more dates in the future. I need to somehow reduce the dataset to one row per user, **only selecting the row which has the most recently passed date**. That is, with whatever magic `GROUP BY` or `HAVING` clause is added, the result from above would look like this: ``` | userId | date | otherData | |--------+------------+------------| | 1 | 2009-01-01 | info | | 2 | 2008-01-01 | each | | 3 | 2009-01-01 | here | ```
I think you don't want to use GROUP BY / HAVING because you are interested in exactly 1 row per user, and that row already exists in the table as-is. This calls for a WHERE clause and not GROUP BY / HAVING. My suggestion is that in the WHERE clause, you add a condition that the date must be equal to the result of a subquery. That subquery should: 1. Select the max(date) 2. Have a WHERE clause that limits date to be smaller than NOW 3. Have a WHERE clause with UserID equals outer query's user id To prevent cases where a certain user can have two entries with the same date that's also the maximum "passed" date, you should also add DISTINCT. Hope that helps.
Like this: ``` select a.userId, a.date, b.userId, b.otherData from table1 as a left outer join table2 as b on a.userId = b.userId where b.Id in ( select top 1 Id from table2 as c where c.userId = a.userId) ```
SQL group by problem
[ "", "sql", "mysql", "group-by", "" ]
I have a HashSet of Identity values that I need to use as the query values to return a ObjectResult from the Entity Framework Here's the HashSet: ``` HashSet<int> officeIds = new HashSet<int>(); ``` Here's the query that I'm trying to run more or less: ``` ObjectResult<FilingOffice> offices = ctx.FilingOffice.Where(office => office IN officeIds.ToList()); ``` The "office => office IN officeIds.ToList()" part of the above is what I can't get to work and haven't found any samples on the web for returing objects given a list of primary keys. ctx is the System.Data.Objects.ObjectContext
The examples others have given won't work in the Entity Framework today, because you can't mix client and serverside enumerations in LINQ 2 Entities. Instead you need to build an OR expression, manually. I run a series of [EF Tips](http://blogs.msdn.com/alexj/archive/2009/03/26/index-of-tips.aspx) and [this tip](http://blogs.msdn.com/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx) shows you how to build an OR expression up. Hope this helps Alex
I have had similar issues a lot of times, another Stack Overflow question with good information is: [Most efficient way to get multiple entities by primary key?](https://stackoverflow.com/questions/8107439/entity-framework-4-1-most-efficient-way-to-get-multiple-entities-by-primary-key) I prefer to use: ``` var entities = db.Entities.WhereIn(x => x.Id, ids); ```
How to get ObjectResult from Entity Framework using a list of Identities
[ "", "c#", "entity-framework", "" ]
I have the following code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication28 { class Program { static void Main() { List<string> dirs = FileHelper.GetFilesRecursive(@"c:\Documents and Settings\bob.smith\Desktop\Test"); foreach (string p in dirs) { Console.WriteLine(p); } //Write Count Console.WriteLine("Count: {0}", dirs.Count); Console.Read(); } static class FileHelper { public static List<string> GetFilesRecursive(string b) { // 1. // Store results in the file results list. List<string> result = new List<string>(); // 2. // Store a stack of our directories. Stack<string> stack = new Stack<string>(); // 3. // Add initial directory. stack.Push(b); // 4. // Continue while there are directories to process while (stack.Count > 0) { // A. // Get top directory string dir = stack.Pop(); try { // B // Add all files at this directory to the result List. result.AddRange(Directory.GetFiles(dir, "*.*")); // C // Add all directories at this directory. foreach (string dn in Directory.GetDirectories(dir)) { stack.Push(dn); } } catch { // D // Could not open the directory } } return result; } } } } ``` The code above works well for recursively finding what files/directories lie in a folder on my c:. I am trying to serialize the results of what this code does to an XML file but I am not sure how to do this. My project is this: find all files/ directories w/in a drive, serialize into an XML file. Then, the second time i run this app, i will have two XML files to compare. I then want to deserialize the XML file from the first time i ran this app and compare differences to the current XML file and produce a report of changes (i.e. files that have been added, deleted, updated). I was hoping to get some help as I am a beginner in C# and i am very very shaky on serializing and deserializing. I'm having lots of trouble coding. Can someone help me? Thanks
Your result is `List<string>` and that is not directly serializable. You'll have to wrap it, a minimal approach: ``` [Serializable] class Filelist: List<string> { } ``` And then the (De)Serialization goes like: ``` Filelist data = new Filelist(); // replaces List<string> // fill it using (var stream = File.Create(@".\data.xml")) { var formatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter(); formatter.Serialize(stream, data); } data = null; // lose it using (var stream = File.OpenRead(@".\data.xml")) { var formatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter(); data = (Filelist) formatter.Deserialize(stream); } ``` But note that you will not be comparing the XML in any way (not practical). You will compare (deserialzed) List instances. And the XML is SOAP formatted, take a look at it. It may not be very useful in another context. And therefore you could easily use a different Formatter (binary is a bit more efficient and flexible). Or maybe you just want to **persist** the List of files as XML. That is a different question.
For anyone who is having trouble with xml serialization and de-serialization. I have created a sample class to do this below. It works for recursive collections also (like files and directories). ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sample { [Serializable()] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false, ElementName = "rootnode")] public partial class RootNode { [System.Xml.Serialization.XmlElementAttribute("collection1")] public List<OuterCollection> OuterCollections { get; set; } } [Serializable()] public partial class OuterCollection { [XmlAttribute("attribute1")] public string attribute1 { get; set; } [XmlArray(ElementName = "innercollection1")] [XmlArrayItem("text", Type = typeof(InnerCollection1))] public List<InnerCollection1> innerCollection1Stuff { get; set; } [XmlArray("innercollection2")] [XmlArrayItem("text", typeof(InnerCollection2))] public List<InnerCollection2> innerConnection2Stuff { get; set; } } [Serializable()] public partial class InnerCollection2 { [XmlText()] public string text { get; set; } } public partial class InnerCollection1 { [XmlText()] public int number { get; set; } } } ```
Serialization and Deserialization into an XML file, C#
[ "", "c#", "serialization", "xml-serialization", "" ]
Here's my problem: I'm trying to parse a big text file (about 15,000 KB) and write it to a MySQL database. I'm using Python 2.6, and the script parses about half the file and adds it to the database before freezing up. Sometimes it displays the text: > MemoryError. Other times it simply freezes. I figured I could avoid this problem by using generator's wherever possible, but I was apparently wrong. What am I doing wrong? When I press [Ctrl](http://en.wikipedia.org/wiki/Control_key) + `C` to keyboard interrupt, it shows this error message: ``` ... sucessfully added vote # 2281 sucessfully added vote # 2282 sucessfully added vote # 2283 sucessfully added vote # 2284 floorvotes_db.py:35: Warning: Data truncated for column 'vote_value' at row 1 r['bill ID'] , r['last name'], r['vote']) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "floorvotes_db.py", line 67, in addAllFiles addFile(file) File "floorvotes_db.py", line 61, in addFile add(record) File "floorvotes_db.py", line 35, in add r['bill ID'] , r['last name'], r['vote']) File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 166, in execute File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 35, in defaulte rrorhandler KeyboardInterrupt import os, re, datetime, string # Data DIR = '/mydir' tfn = r'C:\Documents and Settings\Owner\Desktop\data.txt' rgxs = { 'bill number': { 'rgx': r'(A|S)[0-9]+-?[A-Za-z]* {50}'} } # Compile rgxs for speediness for rgx in rgxs: rgxs[rgx]['rgx'] = re.compile(rgxs[rgx]['rgx']) splitter = rgxs['bill number']['rgx'] # Guts class floor_vote_file: def __init__(self, fn): self.iterdata = (str for str in splitter.split(open(fn).read()) if str and str <> 'A' and str <> 'S') def iterVotes(self): for record in self.data: if record: yield billvote(record) class billvote(object): def __init__(self, section): self.data = [line.strip() for line in section.splitlines()] self.summary = self.data[1].split() self.vtlines = self.data[2:] self.date = self.date() self.year = self.year() self.votes = self.parse_votes() self.record = self.record() # Parse summary date def date(self): d = [int(str) for str in self.summary[0].split('/')] return datetime.date(d[2],d[0],d[1]).toordinal() def year(self): return datetime.date.fromordinal(self.date).year def session(self): """ arg: 2-digit year int returns: 4-digit session """ def odd(): return divmod(self.year, 2)[1] == 1 if odd(): return str(string.zfill(self.year, 2)) + \ str(string.zfill(self.year + 1, 2)) else: return str(string.zfill(self.year - 1, 2))+ \ str(string.zfill(self.year, 2)) def house(self): if self.summary[2] == 'Assembly': return 1 if self.summary[2] == 'Senate' : return 2 def splt_v_line(self, line): return [string for string in line.split(' ') if string <> ''] def splt_v(self, line): return line.split() def prse_v(self, item): """takes split_vote item""" return { 'vote' : unicode(item[0]), 'last name': unicode(' '.join(item[1:])) } # Parse votes - main def parse_votes(self): nested = [[self.prse_v(self.splt_v(vote)) for vote in self.splt_v_line(line)] for line in self.vtlines] flattened = [] for lst in nested: for dct in lst: flattened.append(dct) return flattened # Useful data objects def record(self): return { 'date' : unicode(self.date), 'year' : unicode(self.year), 'session' : unicode(self.session()), 'house' : unicode(self.house()), 'bill ID' : unicode(self.summary[1]), 'ayes' : unicode(self.summary[5]), 'nays' : unicode(self.summary[7]), } def iterRecords(self): for vote in self.votes: r = self.record.copy() r['vote'] = vote['vote'] r['last name'] = vote['last name'] yield r test = floor_vote_file(tfn) import MySQLdb as dbapi2 import floorvotes_parse as v import os # Initial database crap db = dbapi2.connect(db=r"db", user="user", passwd="XXXXX") cur = db.cursor() if db and cur: print "\nConnected to db.\n" def commit(): db.commit() def ext(): cur.close() db.close() print "\nConnection closed.\n" # DATA DIR = '/mydir' files = [DIR+fn for fn in os.listdir(DIR) if fn.startswith('fvote')] # Add stuff def add(r): """add a record""" cur.execute( u'''INSERT INTO ny_votes (vote_house, vote_date, vote_year, bill_id, member_lastname, vote_value) VALUES (%s , %s , %s , %s , %s , %s )''', (r['house'] , r['date'] , r['year'], r['bill ID'] , r['last name'], r['vote']) ) #print "added", r['year'], r['bill ID'] def crt(): """create table""" SQL = """ CREATE TABLE ny_votes (openleg_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, vote_house int(1), vote_date int(5), vote_year int(2), bill_id varchar(8), member_lastname varchar(50), vote_value varchar(10)); """ cur.execute(SQL) print "\nCreate ny_votes.\n" def rst(): SQL = """DROP TABLE ny_votes""" cur.execute(SQL) print "\nDropped ny_votes.\n" crt() def addFile(fn): """parse and add all records in a file""" n = 0 for votes in v.floor_vote_file(fn).iterVotes(): for record in votes.iterRecords(): add(record) n += 1 print 'sucessfully added vote # ' + str(n) def addAllFiles(): for file in files: addFile(file) if __name__=='__main__': rst() addAllFiles() ```
Generators are a good idea, but you seem to miss the biggest problem: (str for str in splitter.split(**open(fn).read()**) if str and str <> 'A' and str <> 'S') You're reading the whole file in at once even if you only need to work with bits at a time. You're code is too complicated for me to fix, but you should be able to use file's iterator for your task: (line for line in open(fn))
I noticed that you use a lot of slit() calls. This is memory consuming, according to <http://mail.python.org/pipermail/python-bugs-list/2006-January/031571.html> . You can start investigating this.
Error message "MemoryError" in Python
[ "", "python", "memory-management", "" ]
I'm new to jQuery and to some extent JavaScript programming. I've successfully started to use jQuery for my Ajax calls however I'm stumped and I'm sure this is a newbie question but here goes. I'm trying to return in an Ajax call a complete html structure, to the point a table structure. However what keeps happening is that jQuery either strips the html tags away and only inserts the deepest level of "text" or the special characters like `<`,`>`, etc get replaced with the escaped ones I need to know how to turn off this processing of the received characters. Using firebug I see the responses going out of my WebServer correctly but the page received by the user and thus processed by jQuery are incorrect. A quick example will so what I mean. I'm sending something like this ``` <results><table id="test"><tr>test</tr></table></results> ``` what shows up on my page if I do a page source view is this. ``` &lt;results&gt;&lt;table.... ``` so you can see the special characters are getting converted and I don't know how to stop it. The idea is for the `<results></results>` to be the xml tag and the text of that tag to be what gets placed into an existing `<div>` on my page. Here is the JavaScript that I'm using to pull down the response and inserts: ``` $.post(url, params, function(data) { $('#queryresultsblock').text(data) }, "html"); ``` I've tried various options other than "html" like, "xml", "text" etc. They all do various things, the "html" gets me the closest so far.
The simplest way is just to return your raw HTML and use the `html` method of jQuery. Your result: ``` <table id="test"><tr>test</tr></table> ``` Your Javascript call: ``` $.post(url, params, function(data){ $('#queryresultsblock').html(data) }) ``` --- Another solution with less control — you can only do a GET request — but simpler is to use `load`: ``` $("#queryresultsblock").load(url); ``` If you must return your result in a `results` XML tag, you can try adding a jQuery selector to your `load` call: ``` $("#queryresultsblock").load(url + " #test"); ```
You can't put unescaped HTML inside of XML. There are two options I see as good ways to go. One way is to send escaped HTML in the XML, then have some JavaScript on the client side unescape that HTML. So you would send ``` <results>&lt;results&gt;&lt;table.... ``` And the javascript would convert the `&lt;` to < and such. The other option, and what I would do, is to use JSON instead of XML. ``` {'results': "<table id="test"><tr>test</tr></table>" } ``` The JavaScript should be able to extract that HTML structure as a string and insert it directly into your page without any sort of escaping or unescaping.
jQuery, Ajax and getting a complete html structure back
[ "", "javascript", "jquery", "html", "ajax", "" ]
I want to use a circular list. Short of implementing my own ([like this person did](http://cppcorner.3x.ro/circularlist.html)) what are my options? Specifically what I want to do is iterate over a list of objects. When my iterator reaches the end of the list, it should automatically return to the beginning. (Yes, I realize this could be dangerous.) [See Vladimir's definition of a `circular_iterator`](http://cppcorner.3x.ro/circularlist.html): "A circular\_iterator will never be equal with CircularList::end(), thus you can always dereference this iterator."
There's no standard circular list. However, there is a [circular buffer](http://www.boost.org/doc/libs/1_39_0/libs/circular_buffer/doc/circular_buffer.html) in Boost, which might be helpful. If you don't need anything fancy, you might consider just using a `vector` and accessing the elements with an index. You can just `mod` your index with the size of the vector to achieve much the same thing as a circular list.
If you want something looking like an iterator you can roll your own, looking something like ``` template <class baseIter> class circularIterator { private: baseIter cur; baseIter begin; baseIter end; public: circularIterator(baseIter b, baseIter e, baseIter c=b) :cur(i), begin(b), end(e) {} baseIter & operator ++(void) {++cur; if(cur == end) {cur = begin;}} }; ``` (Other iterator operations left as exercise to reader).
Does a standard implementation of a Circular List exist for C++?
[ "", "c++", "data-structures", "circular-list", "" ]
I'm using this function to determine whether my application should be online or offline: ``` function online() { if ($online == "0") { if($_SESSION['exp_user']['userlevel'] != "1") { include("error/offline.php"); exit(); } } } ``` However, with the data value set to 0 in the database, and `$online` does = '0', why is error/offline.php not included for those whoose user level is not 1? Thanks :)
What is `$online`, a global variable? If so you have to do `global $online` to access it inside a function. Right now `$online` is a default `null` value, which is not equal to string "0".
"Chaos" is right about the global variables. But if you're not sure, one way to debug something like this is to add "echo" or "die" statements in various places, to see what's happening in the code. Put one inside the first "if" statement to see if it gets that far, then one in the second "if" statement. Echo the values of the variables you're testing, so you can tell why the conditions aren't working.
What's wrong with this function?
[ "", "php", "function", "if-statement", "" ]
I get the following error in Visual Studio 2008: error C2248: 'Town::Town' : cannot access private member declared in class 'Town'. It looks like the constructor is unable to access the members of its own class. Any idea what's going on? Here's the code: I have this: ``` template<class T> class Tree{...} ``` And this class: ``` class Town{ Town(int number):number(number){}; ... private: int number; }; ``` Which is used in this class: ``` class Country{ public: StatusType AddTown(Shore side, int location, int maxNeighborhoods); private: Tree<Town> towns[2]; ... } ``` And here's the AddTown function: ``` StatusType Country::AddTown(Shore side, int location, int maxNeighborhoods){ if (maxNeighborhoods<0 || location<0){ return INVALID_INPUT; } Town* dummy= new Town(location);//Here be error C2248 if (towns[side].find(*dummy)!=NULL){ delete dummy; return FAILURE; } SouthBorder* dummyBorder; (side==NORTH)?dummyBorder=new SouthBorder(location,0):dummyBorder=new SouthBorder(0,location); if (southBorders.find(*dummyBorder)!=NULL){ delete dummyBorder; return FAILURE; } towns[side].add(*dummy); delete dummyBorder; return SUCCESS; } ```
By default class access level is private. If you do not add a public: before the Town constructor it will be private. ``` class Town{ public: // <- add this Town(int number):number(number){}; ... private: int number; }; ```
This code had both the logic problems listed above. Both the non public declaration and the hiding of the member variables by using the same name passed as internal. Considering we are talking about the 'number' variable as an example. In the past such as in c++ member variables that were private internal variables would be prefixed with 'm\_number'. Or some would do just '\_number'. Just 'num' is a good rename but it may not be clear that it is just the same value. I suppose this is a problem of internal private member variable naming that hasn't really been solved. Python uses 'self.number' which would distinguish from 'number' passed in which is a decent solution. But whatever the platform, it is always good to have a private variable member naming system that helps you to avoid hacks at the points that you have name collisions.
Constructor cannot access private members of its own class
[ "", "c++", "visual-studio-2008", "templates", "" ]
This question is related to C#, but may be applicable to other languages as well. I have a reservation against using code such as the following: ``` using System.Windows.Forms; class MyForm : Form { private Timer myTimer; private Button myButton; public MyForm() { // Initialize the components, etc. myTimer.Tick += new EventHandler( myTimer_Tick ); myButton.Click += new EventHandler( myButton_Click ); myTimer.Start(); } private void myTimer_Tick( object sender, EventArgs eventArgs ) { myTimer.Stop(); // also, I see a lot of usage of // Timer.Enabled = true/false instead of -^ myButton_Click( this, ea /* or event EventArgs.Empty, or null */ ); return; } private void myButton_Click( object sender, EventArgs eventArgs ) { // do a lot of stuff, with lots of logic that doesn't even use the // state of the eventArgs return; } } ``` Am I alone, in that the above style is a pet peeve of mine? Are there others who enjoy the clarity of separating event handling from the workload of functions, or even separating out complex routines into separate functions? Is there even an accepted style? I feel like any expressiveness and flexibility that event handling in C# has can be lost with styles like this. I feel like if you have a method that means "a button has been clicked", then it should only be called when a button is clicked. To those who write like this, I would say: if you insist on having an EventHandler method to handle your timer tick, and your button click, then call it something other than button\_Click -- perhaps "`handleUserEvent( object sender, EventArgs eventArgs )`". Really, though, the question is, are there any style guidelines that are widely used which either support or discourage usage such as the above?
I agree with [Rex M's answer](https://stackoverflow.com/questions/984270/c-is-calling-an-event-handler-explicitly-really-a-good-thing-to-do/984303#984303), but I'd take it one step further. If you are using the MVC pattern (or something similar), the view would delegate the button click to the controller. The controllers methods can of course be called from elsewhere in your class - say, from your timer callback. So, back to your original code: ``` using System.Windows.Forms; class MyForm : Form { private Timer myTimer; private Button myButton; private MyController myController; public MyForm() { // ... // Initialize the components, etc. // ... myTimer.Tick += new EventHandler( myTimer_Tick ); myButton.Click += new EventHandler( myButton_Click ); myTimer.Start(); } private void myTimer_Tick( object sender, EventArgs eventArgs ) { myTimer.Stop(); myController.SomeMethod() } private void myButton_Click( object sender, EventArgs eventArgs ) { // All the stuff done here will likely be moved // into MyController.SomeMethod() myController.SomeMethod(); } } ``` One advantage of using MVC is the decoupling of the controller from the view. The controller can now be used across multiple view types easily and exiting GUIs are easier to maintain as they contain very little application logic. EDIT: Added in response to comments from the OP The fundamental design principals of software engineering talk about coupling and cohesion. Importantly we strive to minimise coupling between components while maximising cohesion as this leads to a more modular and maintainable system. Patterns like MVC and principals like the Open/Closed Principal build on these fundamentals, providing more tangible patterns of implemenation for the developer to follow. So, anyone who writes code as seen in the original post has not understood the fundamentals of software design and needs to develop their skills considerably. The OP should be commended for identifying this "code smell" and trying to understand why it's not quite right. Some relevant references: * <http://en.wikipedia.org/wiki/Coupling_(computer_science)> * <http://en.wikipedia.org/wiki/Cohesion_(computer_science)> * <http://en.wikipedia.org/wiki/Loose_coupling> * <http://en.wikipedia.org/wiki/Model>–view–controller * <http://en.wikipedia.org/wiki/Design_patterns> * <http://en.wikipedia.org/wiki/Open/closed_principle> * <http://en.wikipedia.org/wiki/Design_Patterns_(book)>
This is definitely not a "personal preference". There is a clear, well-understood approach of how to write code that is well-structured, maintainable, reusable, and understandable. Each method in your code should encapsulate a single piece of reusable functionality. The structure of your code should be: ``` void ButtonClickEventHandler(...) { UserData userData = //determine user data from event data DoUserThing(userData); } void DoUserThing(UserData userData) { //do stuff } void SomeOtherMethod() { UserData userData = //get userdata from some other source DoUserThing(userData); } ``` (This is a very loose example. In a proper application everything should be [separated into different classes by concern](http://en.wikipedia.org/wiki/Separation_of_concerns).)
C#: is calling an event handler explicitly really "a good thing to do"?
[ "", "c#", ".net", "formatting", "coding-style", "" ]
What is the best way to put a footer row into a JTable? Does anyone have any sample code to do this? The only approach I've thought of so far is to put a special row into the table model that always get sorted to the bottom. --- Here is what I ended up with: ``` JTable mainTable = new JTable(mainTableModel); JTable footerTable = new JTable(footerModel); footerTable.setColumnModel(mainTable.getColumnModel()); // Disable selection in the footer. Otherwise you can select the footer row // along with a row in the table and that can look quite strange. footerTable.setRowSelectionAllowed(false); footerTable.setColumnSelectionAllowed(false); JPanel tablePanel = new JPanel(); BoxLayout boxLayout = new BoxLayout(tablePanel, BoxLayout.Y_AXIS); tablePanel.setLayout(boxLayout); tablePanel.add(mainTable.getTableHeader()); // This seems like a bit of a WTF tablePanel.add(mainTable); tablePanel.add(footerTable); ``` Sorting works fine but selecting the footer row is a bit strange.
Try using a second JTable that uses the same column model as your data table and add your footer data to that table. Add the second (footer) table under your original table. ``` JTable footer = new JTable(model, table.getColumnModel()); panel.add(BorderLayout.CENTER, table); panel.add(BorderLayout.SOUTH, footer); ```
Looks like this [project](http://www.jidesoft.com/products/oss.htm) has a component called JideScrollPane which advertises support for a row footer. I haven't tried it myself, but it sounds like it does exactly what you want! The website also has a demo app where you can see it in action and it that looks pretty good. Note that it seems a lot of the their stuff you have to pay for, but their JideScrollPane looks to be free and open source.
Footer row in a JTable
[ "", "java", "swing", "jtable", "" ]
I was recently trying to gauge my operator overloading/template abilities and as a small test, created the Container class below. While this code compiles fine and works correctly under MSVC 2008 (displays 11), both MinGW/GCC and Comeau choke on the `operator+` overload. As I trust them more than MSVC, I'm trying to figure out what I'm doing wrong. Here is the code: ``` #include <iostream> using namespace std; template <typename T> class Container { friend Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs); public: void setobj(T ob); T getobj(); private: T obj; }; template <typename T> void Container<T>::setobj(T ob) { obj = ob; } template <typename T> T Container<T>::getobj() { return obj; } template <typename T> Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs) { Container<T> temp; temp.obj = lhs.obj + rhs.obj; return temp; } int main() { Container<int> a, b; a.setobj(5); b.setobj(6); Container<int> c = a + b; cout << c.getobj() << endl; return 0; } ``` This is the error Comeau gives: ``` Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C++ C++0x_extensions "ComeauTest.c", line 27: error: an explicit template argument list is not allowed on this declaration Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs) ^ 1 error detected in the compilation of "ComeauTest.c". ``` I'm having a hard time trying to get Comeau/MingGW to play ball, so that's where I turn to you guys. It's been a long time since my brain has melted this much under the weight of C++ syntax, so I feel a little embarrassed ;). **EDIT**: Eliminated an (irrelevant) lvalue error listed in initial Comeau dump.
I found the solution thanks [to this forum posting](http://www.go4expert.com/forums/showpost.php?s=dac30e8cfd4096ee175ae2e36f406058&p=31759&postcount=10). Essentially, you need to have a function prototype before you can use 'friend' on it within the class, however you also need the class to be declared in order to properly define the function prototype. Therefore, the solution is to have two prototype definitons (of the function and the class) at the top. The following code compiles under all three compilers: ``` #include <iostream> using namespace std; //added lines below template<typename T> class Container; template<typename T> Container<T> operator+ (Container<T>& lhs, Container<T>& rhs); template <typename T> class Container { friend Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs); public: void setobj(T ob); T getobj(); private: T obj; }; template <typename T> void Container<T>::setobj(T ob) { obj = ob; } template <typename T> T Container<T>::getobj() { return obj; } template <typename T> Container<T> operator+ (Container<T>& lhs, Container<T>& rhs) { Container<T> temp; temp.obj = lhs.obj + rhs.obj; return temp; } int main() { Container<int> a, b; a.setobj(5); b.setobj(6); Container<int> c = a + b; cout << c.getobj() << endl; return 0; } ```
``` template <typename T> Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs) ``` Here the "<>" after `operator+` should be removed since you're just declaring a new template, not specializing a general one. Also at least `g++` wants to see the template declaration before the friend declaration, so it needs to be moved before the declaration of `Container`. So the following order of the declarations works: ``` // forward declaration of Container<T> template <typename T> class Container; template <typename T> Container<T> operator+(Container<T>& lhs, Container<T>& rhs) { ... } template <typename T> class Container { friend Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs); ... }; ```
Binary operator overloading on a templated class
[ "", "c++", "templates", "operators", "operator-overloading", "" ]
I'm trying to reload a table which was also generated by PHP. The table has an ID: `#bookmarks` After the user pressed a button, the table should reload the content + the data they have just added. I'm a bit confused because I don't know how to send all of the data from a PHP result.
For specific help using jQuery, check out the [jEditable](http://www.appelsiini.net/projects/jeditable) plugin which is designed to provide the ability to edit data in place. There's also instructions on how to collect the data and save it.
This is assuming your PHP returns a ready-to-inject HTML code for the table: ``` $("#update_button").click(function(){ $("#mytable").load("/tools/getTable.php") }) ``` in your page you need a DIV placeholder like this: ``` <div id="mytable"></div> ``` and your getTable.php needs to echo back html like this: ``` <table> <tr> <td>col1<td> <td>col2<td> <tr> </table> ```
jQuery - Reload table
[ "", "php", "jquery", "dynamic", "reload", "" ]
Using Visual Studio 2008, I setup a client that uses Web Services. It has nothing to do with buffer sizes (as that is a typical response, all appropriate sizes were increased). I was using a List as the parameter of the Method. After much experimentation, I used the System.Net.WebClient to manually create a Soap 1.1 and a Soap 1.2 request to test test the result. ``` using (var webCtx = new System.Net.WebClient()) { webCtx.Headers.Add(System.Net.HttpRequestHeader.ContentType, "text/xml"); webCtx.Headers.Add("SOAPAction", "http://tempuri.org/HelloWorld"); var uri = new Uri("http://localhost:12345/MyProject/WebService.asmx"); MessageBox.Show(webCtx.UploadString(uri, xml)); } ``` Where the xml is a string variable of the xml with actual data. The problem is when one of the fields has a special character. Here is the example of the message body of the xml. ``` <PocoClass> <UnicodeString>&#xE;123</UnicodeString> </PocoClass> ``` If the value of UnicodeString was something simple (i.e. 123), but once the special character appeared, I got 400 Bad Request. Now, I have found a Microsoft Knowledge Base Article describing the bug [kb911276](http://support.microsoft.com/kb/911276/en-us), which basically states, install a hot fix. That really isn't something that can be a solution to the problem, so I was wondering if there are any ideas of how to solve this problem? Are the only solutions to write some sort of custom encoding/decoding or custom bindings to be implemented by the server and client? Are there any easier ideas? Thanks *Edited:* The use of a List is not an issue as it is handled by VS. Here is a more complete (but still partial) contents of the soap message. ``` <HelloWorld xmlns="http://tempuri.org/"> <pocoList> <PocoClass> <UnicodeString>&#xE;123</UnicodeString> </PocoClass> </pocoList> </HelloWorld> ```
I had a similar problem with a webservice we had that users of our app run online account searches. I found a [VS Feedback item about this](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=339060), but it appears MS considers this behaviour by-design. What we ended up doing was writing a method that replaced all characters that are not allowed when serializing to XML with question marks. The allowed list was: 0x09, 0x0a, 0x0d, 0x20-0xd7ff, and 0xe000-0xfffd. Everything else, we turned to "?". I guess if you can't do that, the data should be base64-encoded in transit to avoid this issue. Seems a bit odd to me, as it breaks the ability to losslessly route a call through a web service.
My concern is where you state that you are using a List as the parameter to a method. Web services don't directly support lists. You need to use an array as the parameter. Then internally you can convert it to a list using .ToList(). This may not be your issue directly!
WebServices fail because (400) Bad Request because of special character
[ "", "c#", ".net", "asp.net", "winforms", "" ]
I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. I'm using Django 1.0.2. While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this: ``` number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) ``` It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things. Any other options how I can do it, preferably somehow inside the model abstraction?
Using `order_by('?')` will kill the db server on the second day in production. A better way is something like what is described in [Getting a random row from a relational database](http://web.archive.org/web/20110802060451/http://bolddream.com/2010/01/22/getting-a-random-row-from-a-relational-database/). ``` from django.db.models.aggregates import Count from random import randint class PaintingManager(models.Manager): def random(self): count = self.aggregate(count=Count('id'))['count'] random_index = randint(0, count - 1) return self.all()[random_index] ```
Simply use: ``` MyModel.objects.order_by('?').first() ``` It is documented in [QuerySet API](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.order_by).
How to pull a random record using Django's ORM?
[ "", "python", "django", "django-models", "" ]
Is there some sort of utility available that will check my jQuery plugins and see if they are the latest version? I understand that there is not an easy way to check the version numbers automatically; but I wonder if anyone has taken a look at this.
You could always subscribe to the RSS feed or hit the main page and parse out this bit programmatically, using a DOM parser (or regex if you prefer pain): ``` <p class="jq-version"><strong>Current Release:</strong> v.1.3.2</p> ``` That said, I think the best solution is to manually check the site every couple of weeks or so. If you automatically update your production jQuery libraries, you will almost certainly face at least one catastrophe. Also, you could do it with jQuery like so (provided you get jquery homepage via a proxy on your domain): ``` $('#someDiv').load('proxyOnMyDomain.php?get=www.jquery.com .jq-version'); ```
What real-world problem are you trying to solve? Perhaps [Google AJAX Libraries API](http://code.google.com/apis/ajaxlibs/documentation/) can help you in some way.
Is there an automatic jQuery plugin updater?
[ "", "javascript", "jquery", "jquery-plugins", "utilities", "jquery-1.3", "" ]
Is it possible to get a window popup with always 400px wide, but dynamic height depending on the content in the popup window? I have seen this but not sure how to apply it to popup windows [Adjust width height of iframe to fit with content in it](https://stackoverflow.com/questions/819416/adjust-width-height-of-iframe-to-fit-with-content-in-it)
Solved ``` $(document).ready(function() { // For IE var h = $('#page').outerHeight(); var newH = h + 20; window.resizeBy(0, newH - $(window).height()); // Only works in Firefox/Safari $('img').load(function() { var h = $('#page').outerHeight(); var newH = h + 20; window.resizeBy(0, newH - $(window).height()); }); }); ```
Well, since you're relying on JavaScript to popup, you could do this... You've tagged jQuery, so here is a start... Place this in the popup. ``` $(document).ready(function() { var popupHeight = parseInt($('#elementThatWillGetTaller').css('height')); // parseInt if we get a '200px' // code to set window height - I know it can be done because I've seen osCommerce do it }); ```
Dynamic height for popups depending on content, is it possible?
[ "", "javascript", "jquery", "html", "" ]
I recently wasted a lot of time trying to debug a WPF datagrid (from the WPF Toolkit). I had a column bound to a linq query with a property that was throwing an exception (in a few rows). WPF seems to catch the exception and it just makes the cells blank. I have fixed the bug causing the exception, but I would like to change WPF's behavior. I always want to know if something is wrong. Why is swallowing the exception the default behavior and how can I change it?
Databinding errors are swallowed natively, but they are displayed in the OUTPUT dialog in the visual studio interface. If you wish to be notified (and have as much control over it as possible), then you can use Trace Sources. Bea Stollnitz provides a great writeup about this (and debuginng the bindings in general) here: <http://www.beacosta.com/blog/?p=52> Apparently, this blog has departed, but we do have the WayBack Machine: <http://web.archive.org/web/20091103200557/http://www.beacosta.com/blog/?p=52> I also added it to my Coding notebook for Evernote: <https://www.evernote.com/pub/view/sswrighton/coding/f9786746-94c3-41b5-bcd2-c12992d331a6?locale=en#st=p&n=f9786746-94c3-41b5-bcd2-c12992d331a6>
Here is my [favorite](http://www.jasonbock.net/jb/Default.aspx?blog=entry.0f221e047de740ee90722b248933a28d). It works without changing the app.config
Why does WPF databinding swallow exceptions?
[ "", "c#", ".net", "wpf", "data-binding", "" ]
Any Ideas? I asked the question ["Is it possible to have a default parameter for a mysql stored procedure?"](https://stackoverflow.com/questions/982798/is-it-possible-to-have-a-default-parameter-for-a-mysql-stored-procedure) today and the answer was a very strong "no this is not possible." So my next question then is how do you as a php/mysql developer handle this problem? Do you pass null and in the SP have an IF block that sets the variable if its null? Do you pass a default value in PHP? Thanks.
Here's one solution, using `COALESCE()` to set the value of a local variable in the stored proc: ``` DELIMITER !! CREATE PROCEDURE dflt (IN param1 INT) BEGIN DECLARE param1_dflt INT DEFAULT 456 SET param1_dflt = COALESCE(param1, param1_dflt); SELECT param1_dflt; END!! DELIMITER ; CALL dflt(123); +-------------+ | param1_dflt | +-------------+ | 123 | +-------------+ CALL dflt(NULL); +-------------+ | param1_dflt | +-------------+ | 456 | +-------------+ ```
Optional parameters are scheduled for MySQL 6. Your easiest option is either to write a wrapper that adds the default values, or create procedures for each case. I would consider your reasoning for using stored procedures. In the vast majority of cases they are of little benefit, as abstraction can be performed in the app layer and reduction of network traffic is usually the least of concerns. Of course, this depends on your app.
How do you deal with the fact that default parameters are not possible for Mysql SPs?
[ "", "php", "mysql", "stored-procedures", "default-value", "" ]
I'm writing some kind of automated test suite and I want to make sure the classes contained in the package 'tests' get imported automatically upon runtime in the main namespace, without adding them to the `__init__` file of the package. So here is the script I have so far: ``` import os for dirpath, dirnames, filenames in os.walk('tests'): for filename in filenames: if filename.lower().endswith(('.pyc', '__init__.py')): continue module = ".".join([dirpath, filename.split('.')[0]]) print module ``` If I use `modulename = __import__(module)` the classes get added to the module 'modulename' and not the main namespace. My question is, how do I import them to the current namespace? So I can do things like: ``` testcase = TestCase() testcase.run() results = testcase.results() ``` or whatever in the main script without explicitly importing the classes. Thanks in advance! Thank you all for replying and trying to help me out.
To get classes from some module, there can be better way but here is generic way to get you started ``` mod = __import__("mod") for klass in vars(mod): o = getattr(mod, klass) if type(o) == type: print o ```
I'm not sure I exactly understand your question, but you might try [nose](http://somethingaboutorange.com/mrl/projects/nose/) to [discover](http://www.somethingaboutorange.com/mrl/projects/nose/0.11.1/finding_tests.html) your test suites.
python automatic (or dynamic) import classes in packages
[ "", "python", "" ]
Is there any way, in C#, for a class or method to know who (i.e. what class/ method) invoked it? For example, I might have ``` class a{ public void test(){ b temp = new b(); string output = temp.run(); } } class b{ public string run(){ **CODE HERE** } } ``` Output: "Invoked by the 'test' method of class 'a'."
StackFrame ``` var frame = new StackFrame(1); Console.WriteLine("Called by method '{0}' of class '{1}'", frame.GetMethod(), frame.GetMethod().DeclaringType.Name); ```
You can look at the stack trace to determine who called it. <http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx>
Find out what class invoked a method
[ "", "c#", ".net", "class", "" ]
I am thinking of the following design: ``` static class AppVersion { public static string BuildDate { get; set; } public static string Version { get; set; } public static string GetVersion { get; set; } } ``` A few questions on this: 1. How can I get the build date? 2. How can I print a date in a nice format? 3. How can I obtain and print the Visual Studio version in a nice format? 4. It is probably a bad idea to hard code the version into the binary, so I put the version into assembly information. How can I programmatically get it?
I think your first questions are a matter of taste. You could use [`String.Format`](http://msdn.microsoft.com/en-us/library/fht0f5be.aspx) to get any style you want. Regarding your last question: ``` System.Reflection.Assembly.GetExecutingAssembly().Version ``` returns the version number of the current assembly and: ``` typeof(SomeTypeInSomeAssembly).Assembly.Version ``` will return the version number of the assembly containing the specific type.
For build Date look at <http://dotnetfreak.co.uk/blog/archive/2004/07/08/determining-the-build-date-of-an-assembly.aspx> For the version / Get Version look at the System.Reflection.Assembly name space. As for printing the date in a nice format, you'll want to either use the extension methods built off of DateTime class such as .ToShortDateString() or CultureInfo.
What is the best way to implement versioning of a binary?
[ "", "c#", ".net", "assemblies", "versioning", "" ]
currently setup vs 2008 and been doing "PURE" javascript debugging with eclipse... so i wanted to give vs 2008 a try and debugging "PURE" javascript... I have vs2008 sp1 and i have unchecked the "disable ie client sscripting" in the IE8... I now set my breakpoint (in a .js file) and Attach process. and mark Internet explorer ... but problem is .. it says it will never be hit... anyway i tested it .. i load up my html in the browser WHICH I KNOW calls my js file.. but nothing happens, am i missing something?
Make sure you change Attach To to Script from the default which is Managed Code. This got me a few times.
Write ``` debugger; ``` into your script where you want to start debugging. and run your application. When the script reached it will stop and ask you if you want to debug. Then choose VS.NET 2008 at the list.
debugging with vs 2008?
[ "", "javascript", "visual-studio-2008", "debugging", "" ]
I'm using Visual Studio and COM with C# for the first time and there's something I don't quite understand about the 'references'. How do you know what to reference with a given 'using something.something'? The .Net references seem fairly simple, but COM is less obvious. I'm running Visual Studio 2005 and have the latest VSTO installed, but for the life of me, I can't figure out what I need to reference to satisfy: using Microsoft.VisualStudio.Tools.Applications.Runtime; There are a few Microsoft.VisualStudio things in the .Net tab, but none that continue with .Tools or anything like it. I feel like I'm missing a key concept here.
There are two issues here - First, a reference doesn't necessarily correspond to a namespace. A single reference can contain multiple namespaces, and a single namespace can be shared by multiple assemblies which would need to be referenced. Needing to include a reference allows you to use specific types, not entire namespaces. Second, this is something you'll need to know in advance. If you're using Microsoft's classes, such as the ones in the namespace you listed, MSDN can be a great help. For example, take [Microsoft.VisualStudio.Tools.Applications.Runtime.ServerDocument](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.tools.applications.runtime.serverdocument(VS.80).aspx) If you look at the MSDN page for this class (in that namespace), near the top it includes: > Namespace: Microsoft.VisualStudio.Tools.Applications.Runtime > > Assembly: Microsoft.VisualStudio.Tools.Applications.Runtime (in microsoft.visualstudio.tools.applications.runtime.dll) This specifically tells you which assembly is required.
That reference is part of the Visual Studio SDK. I am currently using VS 2008, but the assemblies should be the same for VS 2005. The link for the SDK is [here](http://www.microsoft.com/downloads/details.aspx?FamilyID=51a5c65b-c020-4e08-8ac0-3eb9c06996f4&DisplayLang=en).
Finding references in Visual Studio
[ "", "c#", "visual-studio", "reference", "" ]
Is there a way to efficiently share or move .NET objects across AppDomains? I realize that the intent of AppDomains is to provide isolation - however I have a case where I need to move a relatively large, cached set of immutable objects that are expensive to compute and create. At the moment, I have a serialization approach that works, but is rather slow.
You cannot move an object across an AppDomain without serializing it. That is the main point of an AppDomain - you can almost think of it as a completely separate process. This is where MarshallByRefObject comes into play. It allows you to **use** the object from the other AppDomain via Remoting, without having to serialize it across the AppDomain boundary. You're still working via remoting, so it will be slower than keeping the object in the same AppDomain, but if the object is large and you are using it infrequently, this can save a huge amount of time when compared with serializing it and unserializing it to make a new copy in the second AppDomain.
One thing you can try is to derive your objects from `MarshalByRefObject`. By default, objects are marshalled by value across AppDomains. For objects that derive from `MarshalByRefObject`, the caller is given a proxy to the object. All calls go through the proxy and are then marshalled to the object's app domain. This can reduce the need to create copies of all your objects in both app domains.
Moving objects across AppDomains in .NET
[ "", "c#", ".net", "serialization", "immutability", "" ]
I'm writing a small read-only FTP-like server. Client says "give me that file" and my server sends it. Is there any standard way (a library function?!?) to make sure that the file requested is not "../../../../../etc/passwd" or any other bad thing? It would be great if I could limit all queries to a directory (and its subdirectories). Thank you!
Get the inode of the root (/) directory, and that of the serving directory (say /ftp/pub). For the files they request, make sure that: 1. The file exists. 2. The parents of the file (accessed using multiple "/.." on the file path) hit the serving directory inode before it hits the root directory inode. You can use `stat` to find the inode of any directory. Put this in one function, and call it before serving the file. Of course using a user/group with appropriate privilege will work as well.
Chroot is probably the best way to go, but you can use `realpath(3)` to determine the canonical path to a given filename. From the man page: ``` char *realpath(const char *file_name, char *resolved_name); ``` > The realpath() function resolves all symbolic links, extra '/' characters, and references to /./ and /../ in filename, and copies the resulting absolute pathname into the memory referenced by resolved name. The resolved\_name argument must refer to a buffer capable of storing at least PATH\_MAX characters. From there you can restrict the request in any additional way you like.
Path sanitization in C++
[ "", "c++", "linux", "unix", "path", "sanitization", "" ]
can anyone recommend portable SIMD library that provides a c/c++ API, works on Intel and AMD extensions and Visual Studio, GCC compatible. I'm looking to speed up things like scaling a 512x512 array of doubles. Vector dot products, matrix multiplication etc. So far the only one I found is: <http://simdx86.sourceforge.net/> but as the very first page says it doesn't compile on visual studio. There's also Intel IPP which doesn't work on AMD from what I gather. And there's Framewave from AMD, but I was having some problems compiling and linking their library and their forums are completely dead. Anyone managed to use Framewave anywhere? Thanks.
Since you mention high-level operations on matrices and vectors, [ATLAS](http://math-atlas.sourceforge.net/), [Intel's MKL](http://software.intel.com/en-us/intel-mkl/), [PLASMA](http://icl.cs.utk.edu/plasma/software/index.html), and [FLAME](http://z.cs.utexas.edu/wiki/flame.wiki/FrontPage) may be of interest. Some C++ matrix math libraries include uBLAS from Boost, Armadillo, Eigen, IT++, and Newmat. The POOMA library probably also includes some of these things. [This question](https://stackoverflow.com/questions/1067821/ublas-vs-matrix-template-library-mtl4) also refers to MTL. If you're looking for lower-level portability primitives, a colleague of mine has developed a wrapper around SSE2, Altivec, VSX, Larrabee, and Cell SPE vector operations. It can be found in our [source repository](http://charm.cs.uiuc.edu/cgi-bin/gitweb2.cgi?p=charm.git;a=blob;f=src/util/simd.h), but its licensing (academic) may not be appropriate if you want to distribute it as part of your work. It is also still under significant development to cover the range of application needs that it's targeted at.
[Eigen](http://eigen.tuxfamily.org/) is an [MPL2](https://www.mozilla.org/MPL/2.0/FAQ.html)-licensed header-only C++ library that has vector / matrix math that is optimized for SSE, Neon, and Altivec. They have more more sophisticated math operations in their add-on modules.
Good portable SIMD library
[ "", "c++", "open-source", "cross-platform", "simd", "" ]
If I choose lots of files tactics, then I become to have directory traversal security problem? I need to write login system, and lots of file tactics means make lots of id files and use scandir. so the directory would have aaa.txt (contents is aaa\_pass) bbb.txt (contents is bbb\_pass) ccc.txt (contents is ccc\_pass) and when someone enter his id, the system scandir the directory, then find the id files. but hey, what if he enters as "../../important.txt" ? then he could access to the ../../important.txt ?
At first glance, it seems like you are going down a somewhat strange path for writing a login system. I'm not sure plain text files in a directory on the filesystem is a wise path to take if for no other other reason than that it's abnormal and you'rer likely to overlook many of the subtleties that are already thought through in more common authentication systems. If you wanted to store the passwords hashed and salted, for instance, you'd need to think through how to implement that in your scheme and you could make a mistake that would lead to a security problem. Using a good PEAR library or even the Zend\_Auth component from Zend Framework, though, would give you a clear and well-documented starting point. Anyway, assuming you have your reasons for the arrangement you describe in your question, the basename() function is likely what you want in this case. It will strip everything but the filename itself so that they can't do a directory traversal attack like you describe in your question. So if the input from the user is: ../../important You can run: ``` $cleanUsername = basename($input); $filename = '/path/to/password/files/' . $cleanUsername . '.txt'; if (file_exists($filename)) { [...] } ``` Make sense?
You could perform some validation of the username before you use it as part of a path - for example to only allow letters and numbers you could do something like this using a regular expression: ``` if (!preg_match('/^[a-zA-Z0-9]+$/', $username)) { //username is not valid } else { //username is ok to use } ``` Another way you could do it is to hash the username before you read or write it, for example: ``` $hash = sha1($username); ``` This way, the user can have anything as their username and there will be no danger of them manipulating the behaviour of your file lookup. A username of `"../../important.txt"` would give you a hash of `"48fc9e70df592ccde3a0dc969ba159415c62658d"`, which is safe despite the source string being nasty.
lots of files tactics have directory traversal security problem?
[ "", "php", "security", "authentication", "directory", "traversal", "" ]