Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
``` "\u4000\f".TrimEnd(new char[0]) ``` is equal to `"\u4000"`. I am passing an empty array, so according to the MSDN documentation nothing should be removed and `"\u4000\f"` should be returned. Is there a reason for this behaviour? EDIT: Clarified expected behaviour EDIT: Apparently, this changed in 3.5, I was looking at the 2.0 documentation page.
the documentation says "If trimChars is null (Nothing in Visual Basic) or an *empty array*, white-space characters are removed instead. " So no, not a bug.
The [documentation](http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx) is clear: > Removes all trailing occurrences of a > set of characters specified in an > array from the current String object. > > Return Value Type: System..::.String > The string that remains after all > occurrences of the characters in the > trimChars parameter are removed from > the end of the current String object. > **If trimChars is null (Nothing in Visual > Basic) or an empty array, white-space > characters are removed instead.** So your example is not bug.
Is this a bug in string.TrimEnd?
[ "", "c#", "string", "" ]
This is an incredibly simple question (I'm new to Python). I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it. As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length. Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings. Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list. I.e., I want to be able to do this: ``` list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] ```
Depending on how you are going to use the list, it may be that you actually want a dictionary. This will work: ``` d = {} for row in rows: c = list_of_categories.index(row["id"]) print c d[c] = row["name"] ``` ... or more compactly: ``` d = dict((list_of_categories.index(row['id']), row['name']) for row in rows) print d ``` PHP arrays are much more like Python dicts than they are like Python lists. For example, they can have strings for keys. And confusingly, Python has an array module, which is described as "efficient arrays of numeric values", which is definitely not what you want.
If the number of items you want is known in advance, and you want to access them using integer, 0-based, consecutive indices, you might try this: ``` n = 3 array = n * [None] print array array[2] = 11 array[1] = 47 array[0] = 42 print array ``` This prints: ``` [None, None, None] [42, 47, 11] ```
How do you create a list like PHP's in Python?
[ "", "python", "list", "" ]
I have a Python function that takes a numeric argument that **must** be an integer in order for it behave correctly. What is the preferred way of verifying this in Python? My first reaction is to do something like this: ``` def isInteger(n): return int(n) == n ``` But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon. Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design? EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.
``` isinstance(n, int) ``` If you need to know whether it's definitely an actual int and not a subclass of int (generally you shouldn't need to do this): ``` type(n) is int ``` this: ``` return int(n) == n ``` isn't such a good idea, as cross-type comparisons can be true - notably `int(3.0)==3.0`
Yeah, as Evan said, don't type check. Just try to use the value: ``` def myintfunction(value): """ Please pass an integer """ return 2 + value ``` That doesn't have a typecheck. It is much better! Let's see what happens when I try it: ``` >>> myintfunction(5) 7 ``` That works, because it is an integer. Hm. Lets try some text. ``` >>> myintfunction('text') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in myintfunction TypeError: unsupported operand type(s) for +: 'int' and 'str' ``` It shows an error, TypeError, which is what it should do anyway. If caller wants to catch that, it is possible. What would you do if you did a typecheck? Show an error right? So you don't have to typecheck because the error is already showing up automatically. Plus since you didn't typecheck, you have your function working with other types: Floats: ``` >>> print myintfunction(2.2) 4.2 ``` Complex numbers: ``` >>> print myintfunction(5j) (2+5j) ``` Decimals: ``` >>> import decimal >>> myintfunction(decimal.Decimal('15')) Decimal("17") ``` Even completely arbitrary objects that can add numbers! ``` >>> class MyAdderClass(object): ... def __radd__(self, value): ... print 'got some value: ', value ... return 25 ... >>> m = MyAdderClass() >>> print myintfunction(m) got some value: 2 25 ``` So you clearly get nothing by typechecking. And lose a lot. --- # UPDATE: Since you've edited the question, it is now clear that your application calls some upstream routine that makes sense only with ints. That being the case, I still think you should pass the parameter **as received** to the upstream function. The upstream function will deal with it correctly e.g. raising an error if it needs to. I highly **doubt that** your function that deals with IPs will behave strangely if you pass it a float. If you can give us the name of the library we can check that for you. But... If the upstream function will behave incorrectly and kill some kids if you pass it a float (I still highly doubt it), then just just call `int()` on it: ``` def myintfunction(value): """ Please pass an integer """ return upstreamfunction(int(value)) ``` You're still not typechecking, so you get most benefits of not typechecking. --- If even after all that, you really want to type check, despite it reducing your application's readability and performance for absolutely no benefit, use an `assert` to do it. ``` assert isinstance(...) assert type() is xxxx ``` That way we can turn off `assert`s and remove this `<sarcasm>`*feature*`</sarcasm>` from the program by calling it as ``` python -OO program.py ```
How can I type-check variables in Python?
[ "", "python", "typing", "dynamic-typing", "" ]
I'm trying to access a large Oracle database through SQL Server using OPENROWSET in client-side Javascript, and not having much luck. Here are the particulars: * A SQL Server view that accesses the Oracle database using OPENROWSET works perfectly, so I know I have valid connection string parameters. However, the new requirement is for extremely dynamic Oracle queries that depend on client-side selections, and I haven't been able to get dynamic (or even parameterized) Oracle queries to work from SQL Server views or stored procedures. * Client-side access to the SQL Server database works perfectly with dynamic and parameterized queries. * I cannot count on clients having any Oracle client software. Therefore, access to the Oracle database has to be through the SQL Server database, using views, stored procedures, or dynamic queries using OPENROWSET. * Because the SQL Server database is on a shared server, I'm not allowed to use globally-linked databases. My idea was to define a function that would take my own version of a parameterized Oracle query, make the parameter substitutions, wrap the query in an OPENROWSET, and execute it in SQL Server, returning the resulting recordset. Here's sample code: ``` // db is a global variable containing an ADODB.Connection opened to the SQL Server DB // rs is a global variable containing an ADODB.Recordset . . . ss = "SELECT myfield FROM mytable WHERE {param0} ORDER BY myfield;"; OracleQuery(ss,["somefield='" + somevalue + "'"]); . . . function OracleQuery(sql,params) { var s = sql; var i; for (i = 0; i < params.length; i++) s = s.replace("{param" + i + "}",params[i]); var e = "SELECT * FROM OPENROWSET('MSDAORA','(connect-string-values)';" + "'user';'pass','" + s.split("'").join("''") + "') q"; try { rs.Open("EXEC ('" + e.split("'").join("''") + "')",db); } catch (eobj) { alert("SQL ERROR: " + eobj.description + "\nSQL: " + e); } } ``` The SQL error that I'm getting is `Ad hoc access to OLE DB provider 'MSDAORA' has been denied. You must access this provider through a linked server.` which makes no sense to me. The Microsoft explanation for this error relates to a registry setting (`DisallowAdhocAccess`). This is set correctly on my PC, but surely this relates to the DB server and not the client PC, and I would expect that the setting there is correct since the view mentioned above works. One alternative that I've tried is to eliminate the enclosing EXEC in the Open statement: ``` rs.Open(e,db); ``` but this generates the same error. I also tried putting the OPENROWSET in a stored procedure. This works perfectly when executed from within SQL Server Management Studio, but fails with the same error message when the stored procedure is called from Javascript. Is what I'm trying to do possible? If so, can you recommend how to fix my code? Or is a completely different approach necessary? Any hints or related information will be welcome. Thanks in advance.
I'm answering this myself. I found the answer, and I'm not happy with the results. The functions that have worked are being run under my personal user id, and I have db-owner privileges. For the *ad hoc* access to work, I need to either set the `DisallowAdhocAccess` registry setting to 0, or give db-owner privileges to the user id used in the web access. Because this is a shared server with tight security, I won't be allowed to change the registry setting, which would affect much more than my database. And I consider the second option to be equally dangerous. As a result, I'm apparently stuck with forcing users to have the Oracle Instant Client installed so I can open an ADO connection to the Oracle database directly in client-side Javascript. I will still welcome any alternative thoughts on this.
Opening client-side ADO connections to a database is a huge security no-no. You’re essentially giving the user the connection credentials to your database and daring them to find a hole in your database security. Even if your audience is internal to your company you can run into problems with them not having the oracle drivers installed (or an older version). Why not just hide the Oracle query behind a JSON call? This way you can sanitize your database input on the server side, and your user never received the database connection credentials in plain text.
Accessing Oracle DB through SQL Server using OPENROWSET
[ "", "javascript", "sql-server", "oracle", "openrowset", "" ]
From a strictly implementation and computer science point of view how would you classify the Php array datastructure? Is it an associative array? a hash? a dictionary? ... ?
From the [PHP manual](https://www.php.net/manual/en/language.types.array.php): > An array in PHP is actually an ordered > map. A map is a type that associates > values to keys. This type is optimized > for several different uses; it can be > treated as an array, list (vector), > hash table (an implementation of a > map), dictionary, collection, stack, > queue, and probably more.
Well, it depends on how you wish to classify it. I'd opt for classification by the performance of operations. For example, a true array in Computer Science terms has an O(1) lookup time, while a linked list has an O(n) lookup time. Insertion and deletion are O(1) in a linked list while they are O(n) in an array. I am not sure what the actual performance of a PHP array is, but if you measure a few of the elementary operations on them and compare them with what's expected from the 'true Computer Science datastructures' you should be able to classify it.
What is the CS definition of a Php Array?
[ "", "php", "data-structures", "computer-science", "" ]
I need to add the "Run when Windows starts" option to my program CintaNotes, but do not want to sacrifice the "cleanness" of it: it is a 100% portable freeware and should not leave traces in the system. I've come up with the idea to autodetect running from the Startup shortcut and automatically minimizing to the system tray. Is there a way to do it? I'm using C++ and raw Winapi. So: - No writing to the registry - No command line parameters Thanks! UPD: The question is NOT how to minimize to the system tray! The question is how can a program differentiate between being run normally and being run from a startup-folder shortcut without using registry and command-line parameters.
Your "cleanness" appears to be an artificial construct at best. If you're telling the user to create a shortcut in the start-up folder, you're already leaving a footprint (and, to be honest, there's little difference between "myprog.exe" and "myprog.exe -m"). In that case, there are some easier approaches than automagically trying to detect where you're running from. I would simply provide a menu option in your program ("Install") which would then install the software to a fixed-disk location (as opposed to the flash drive), including the requisite Programs entry (Start, All Programs, CintaNotes). As part of that process (or even after install), you can let them specify "Start with Windows" and then you create the start-up folder shortcut for the user **with** a command line option so your program can tell if it's running that way. There's no point in allowing "Start with Windows" unless the program's available (i.e., on the fixed disk, not the flash drive). Your user need never have to worry about creating shortcuts at all, let alone ones with parameters. And this gives your program the control over how it's run - two modes, "installed" (and start minimized) or "running without installing first" (and start normal). Something like finding the directory of the executable won't work simply because the start-up folder item that starts your program is likely to be a shortcut to it, so you won't have that path. I think this is a classic case of asking the wrong question. In answer to your specific question, I say: no, there is no way to tell that you've been launched from a start up folder entry without some command-line parameters. But, I've been wrong before, just ask my wife :-). Some-one else may well know a way. Adding this an an edit since comments don't allow enough space: You ask: > What do you think of just disabling the "Start when Windows starts" option when program detects it is being run from the flash drive? I guess there's a way to detect this. That's a good idea since it doesn't make sense to allow automatic running until it's installed (since the flash drive may not be there). One possibility: 1/ Running from flash, you start with "myprog.exe" since you just double-clicked the executable and you run in a normal window. This presents the option to "Install to fixed disk" but not "Start with Windows". As part of the install process, you may allow them to set up the installed copy to "Start with Windows" but not the current running copy. 2/ Your installed program can be set up to run as "myprog.exe -i", since you create the item in Start/AllPrograms. This would disable "Install to fixed disk" but allow you to toggle "Start with Windows". You can choose whether you want explicit running (by the user) to start normal or minimized (see (3)). 3/ The shortcut in StartUp can be "myprog.exe -s" (again, you control this because you created it). This is identical to (2) but starts minimized (if (2) started minimized anyway, there's no distinction between (2) and (3) and no reason for different command-line options). That way, each option can have different behavior as you see fit.
Even though you have already solver the problem I just wanted to say that it's possible to detect if the program was launched from shortcut. Once you have the shortcut path you can compare it to startup folder. See the section "Detect if an executable was started from a Short-Cut " at [Undocumented CreateProcess](http://www.catch22.net/tuts/undoc01)
How to detect launching from a "Startup"-folder shortcut?
[ "", "c++", "windows", "winapi", "startup", "windows-shell", "" ]
When doing thread synchronization in C# should I also lock an object when I read a value or just changing it? for example I have Queue<T> object. Should I just lock it when doing the Enqueue and Dequeue or should I also lock it when checking values like Count?
From MSDN: > A Queue<(Of <(T>)>) can support > multiple readers concurrently, as long > as the collection is not modified. > Even so, enumerating through a > collection is intrinsically not a > thread-safe procedure. To guarantee > thread safety during enumeration, you > can lock the collection during the > entire enumeration. To allow the > collection to be accessed by multiple > threads for reading and writing, you > must implement your own > synchronization. You should ensure no reader is active while an item is queued (a lock is probably a good idea). Looking at the count in reflector reveals a read from a private field. This can be okay depending on what you do with the value. This means you shouldn't do stuff like this (without proper locking): ``` if(queue.Count > 0) queue.Dequeue(); ```
Depends on what you want to do with lock. Usually this kind of locking needs a reader/writer locking mechanism. Readers/writers locking means that readers share a lock, so you can have multiple readers reading the collection simultaneously, but to write, you should acquire an exclusive lock.
Should you lock resources when reading values?
[ "", "c#", ".net", "multithreading", "synchronization", "" ]
Does anyone know of any libraries for .net that allow you to use graphics tablets? specifically i am after the pressure sensitivity of the pen, but the 'eraser' and buttons on the pen would be useful too. thanks
Have a look at the source for [Paint.NET](http://getpaint.net) **EDIT**: There should also be a DLL there...
I have also discovered that WPF also has an `InkCanvas`, which has everything built into it.
Graphics tablet/stylus library
[ "", "c#", ".net", "input", "" ]
I am new to Swing. I am trying to develop an application using Swing. I have managed to create the first page of my application. Now what I want to do is to traverse to a new page, using the next button. But am not able to find a way to do it using Swing. Also, if I click the previous button, would I be able to get the data that I had entered in the text boxes or selected using radio buttons on the previous page. I think this can be done pretty easily in Struts, but how is this to be achieved using Swing. Please do help. Thanks a lot.
This one is old but might just get you started: <http://java.sun.com/developer/technicalArticles/GUI/swing/wizard/>
I assume you're trying to build a wizard-style swing dialog? swing does not offer an out-of-the-box framework for this type of task (but of course it offers all UI elements/controls that you will need to create one). just google for "swing wizard framework" and you will find plenty of inspiration -- unfortunately, i can't recommend a single best one (at my company, we have written our own), but i am confident that you will either find one that will work for you or you will familiarize with some patterns that will help you to write one yourself -- good luck!
How can I travese to a next / previous page in a swing GUI
[ "", "java", "swing", "" ]
My problem is :: From a string like "/usr/folder1/folder2/filename.ext" * I have to extract out file name only for display (filename.ext only). + My question would be how should I do it? Splitting on "/" and taking the last element is one way but doesn't smell nice to me. * I have to create a hyperlink which uses URI of the file as the destination. That will be something similar to file://domain.com/usr/folder1/folder2/filename.ext I looked at URI and URL interfaces in java.net but could not find anything useful there. Also, in some cases, my file path can have COMMA, SPACE etc (Windows folders). So, keep that in mind when giving any ideas.
You could try something like this: ``` File file = new File("/usr/folder1/folder2/filename.ext"); System.out.println(file.getName()); ``` I wasn't sure whether this would work if the file does not exist, but have just tried it and it appears to work OK.
[CommonsIO](http://commons.apache.org/proper/commons-io/) provides solutions for this problem: [`FilenameUtils.getName()`](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FilenameUtils.html#getName%28java.lang.String%29), returns the file name + extension. ``` String filename = FilenameUtils.getName("/usr/folder1/folder2/filename.ext"); System.out.println(filename); // Returns "filename.ext" ```
How to extract the file name from a file URI and create a link for the same?
[ "", "java", "filepath", "" ]
I'm using VB9 (VS2008). I've created a Windows Service that indexes some folders regularly. Is there a way I can put an upper limit on the CPU usage depending upon the current system state, i.e., if the system is idle, the thread can use the CPU as much as it needs, but if there are other programs/processes running then it should use the CPU in way that does not make the system slow.
You can reduce the priority of the thread, in .Net via [Thread.Priority](http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx) Setting it to BelowNormal will mean that other threads will be scheduled in front of it. This can lead to the thread being starved, but it sounds like this is an acceptable design decision for your needs. Note that since you are performing considerable disk IO this actually will be the main impact of the back ground task, and you may find that reducing the priority is not sufficient (since the disk IO will continue in parts even while the thread is throttled. A monitoring thread that checks the usage of the machine (optionally caring only when at least one interactive user is present) could pause the indexing (or throttle the IO considerably). This will be more important on modern machines where there are many available cores (and hyper threading virtual cores) which mean that despite the user actually doing a lot of work spare resources exist to execute your indexing thread but not really to execute the disk IO. You may also want to consider whether you check the [Power Scheme](http://msdn.microsoft.com/en-us/library/aa373182(VS.85).aspx) to determine if you should run at that time (since the battery drain from both heavy disk access is not inconsiderable) If you wish to do even more to reduce the impact of this background IO bound task versions of windows from Vista onwards add two useful APIs: ### [Low Priority I/O](http://www.microsoft.com/whdc/driver/priorityio.mspx) This allows your code to schedule I/O at a lower priority than other I/O. ### [Windows Task Scheduler](http://technet.microsoft.com/en-us/appcompat/aa906020.aspx) You can use this to schedule things to run at "system idle time". This when the system isn't busy, and the user is not present.
On XP, ShuggyCoUk is correct. The first thing to do is simply lower the thread priority to something below 8. This will mean that any other thread or process that is running with priority 8 or greater will always run instead of your thread. Note, I do not recommend simply setting your process priority to <8, just the thread (or threads) you want to run 'nicely'. As Shuggy has pointed out, the issue isn't he CPU time - it is the I/O your service is generating. On XP, all I/O's are treated the same - so your I/O has the potential to interfere with other things. Vista (and soon on Win7) has two things designed to do exactly what you want. The first is the [Windows Task Scheduler](http://technet.microsoft.com/en-us/appcompat/aa906020.aspx). You can use this to schedule things to run at "system idle time". This when the system isn't busy, and the user is not present. The second is [Low Priority I/O](http://www.microsoft.com/whdc/driver/priorityio.mspx). This allows your code to schedule I/O at a lower priority than other I/O. Both of these together can be used to develop code that is a good system citizen. Note, you should also take mobile systems into account by scaling back or disabling your background item when the system is running on batteries. You can be simple about this - simple turning off on battery power; or sophisticated, taking the [Power Scheme](http://msdn.microsoft.com/en-us/library/aa373182(VS.85).aspx) into account, and using that as hint from the user. Since you are working on writing a service that is a good system citizen, you can do a few other things as well. 1) You could monitor the amount of work done over time and slow down or stop if enough progress has been made. 2) Do pay attention to your memory footprint - the smaller the better. This often goes without saying, but it is particular important for services as they run 24/7.
Programmatically limit CPU Usage of a Thread running inside a Service
[ "", "c#", "multithreading", "windows-services", "service", "" ]
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the; ``` <__main__.evolutions instance at 0x01B8EA08> ``` but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?
If you want to just display a particular attribute of each class instance, you can do ``` print([obj.attr for obj in my_list_of_objs]) ``` Which will print out the `attr` attribute of each object in the list `my_list_of_objs`. Alternatively, you can define the `__str__()` method for your class, which specifies how to convert your objects into strings: ``` class evolutions: def __str__(self): # return string representation of self print(my_list_of_objs) # each object is now printed out according to its __str__() method ```
Checkout the \_\_str\_\_() and \_\_repr\_\_() methods. See <http://docs.python.org/reference/datamodel.html#object.__repr__>
python - readable list of objects
[ "", "python", "list", "" ]
Does anyone know if the following expression will be possible in the next version(s) of PHP? ``` (new A())->a(); // Causes a syntax error ``` I find very annoying that currently one must write 2 lines instead of 1: ``` $c = new A(); $c->a(); ```
The first version does not cause a parse error, it is perfectly valid. The second it is, indeed not possible, but you can easily overcome such a problem with some coding standards. If every team member creates, for each defined class, a function with the same name as the class, and a signature similar to the signature of the class constructor, then you won't have the second problem. Example: ``` class Foo { public function __construct($param) {} public function bar() {} } /** * @return Foo */ function Foo($param) { return new Foo($param); } Foo()->bar(); ``` Of course, you'll still have problems with library code.
A new-expression can be used as a function argument. A function call can be used as the left-hand side of the member access operator. Therefore, you just need to define a single function: ``` function with($object) { return $object; } with(new A()) -> a(); ``` No additional efforts required on a per-class basis.
Chaining a constructor with an object function call in PHP
[ "", "php", "" ]
Is it possible to know whether a Java class has been loaded, *without* attempting to load it? `Class.forName` attempts to load the class, but I don't want this side effect. Is there another way? (I don't want to override the class loader. I'm looking for a relatively simple method.)
(Thanks to Aleksi) This code: ``` public class TestLoaded { public static void main(String[] args) throws Exception { java.lang.reflect.Method m = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[] { String.class }); m.setAccessible(true); ClassLoader cl = ClassLoader.getSystemClassLoader(); Object test1 = m.invoke(cl, "TestLoaded$ClassToTest"); System.out.println(test1 != null); ClassToTest.reportLoaded(); Object test2 = m.invoke(cl, "TestLoaded$ClassToTest"); System.out.println(test2 != null); } static class ClassToTest { static { System.out.println("Loading " + ClassToTest.class.getName()); } static void reportLoaded() { System.out.println("Loaded"); } } } ``` Produces: > ``` > false > Loading TestLoaded$ClassToTest > Loaded > true > ``` Note that the example classes are not in a package. The full [binary name](http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#name) is required. An example of a binary name is `"java.security.KeyStore$Builder$FileBuilder$1"`
You can use the [findLoadedClass(String)](http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#findLoadedClass(java.lang.String)) method in ClassLoader. It returns null if the class is not loaded.
In Java, is it possible to know whether a class has already been loaded?
[ "", "java", "classloader", "" ]
When I write C++ code for a class using templates and split the code between a source (CPP) file and a header (H) file, I get a whole lot of "unresolved external symbol" errors when it comes to linking the final executible, despite the object file being correctly built and included in the linking. What's happening here, and how can I fix it?
Templated classes and functions are not instantiated until they are used, typically in a separate .cpp file (e.g. the program source). When the template is used, the compiler needs the full code for that function to be able to build the correct function with the appropriate type. However, in this case the code for that function is detailed in the template's source file and hence unavailable. As a result of all this the compiler just assumes that it's defined elsewhere and only inserts the call to the templated function. When it comes to compile the template's source file, the specific template type that is being used in the program source isn't used there so it still won't generate the code required for the function. This results in the unresolved external symbol. The solutions available for this are to: 1. include the full definition of the member function in the template's header file and not have a source file for the template, 2. define all the member functions in the template's source file as "inline" (Update: [this does not work on Visual Studio 2017+]), or 3. define the member functions in the template's source with the "export" keyword. Unfortunately this isn't supported by a lot of compilers. (Update: [this has been removed from the standard as of C++11](http://www.parashift.com/c++-faq/separate-template-fn-defn-from-decl-export-keyword.html).) Both 1 and 2 basically address the problem by giving the compiler access to the full code for the templated function when it is attempting to build the typed function in the program source.
Another option is to put the code in the cpp file and in the same cpp file add explicit instantiations of the template with the types you expect to be using. This is useful if you know you're only going to be using it for a couple of types you know in advance.
Why do I get "unresolved external symbol" errors when using templates?
[ "", "c++", "templates", "linker", "" ]
How can I call a method asynchronously ?
How to call a Visual C# method asynchronously: <http://support.microsoft.com/kb/315582>
You should probably use `ThreadPool.QueueUserWorkItem` ([ThreadPool.QueueUserWorkItem Method](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx))
Async Method Call
[ "", "c#", ".net", "" ]
I have an array of Foo objects. How do I remove the second element of the array? I need something similar to `RemoveAt()` but for a regular array.
If you don't want to use List: ``` var foos = new List<Foo>(array); foos.RemoveAt(index); return foos.ToArray(); ``` You could try this extension method that I haven't actually tested: ``` public static T[] RemoveAt<T>(this T[] source, int index) { T[] dest = new T[source.Length - 1]; if( index > 0 ) Array.Copy(source, 0, dest, 0, index); if( index < source.Length - 1 ) Array.Copy(source, index + 1, dest, index, source.Length - index - 1); return dest; } ``` And use it like: ``` Foo[] bar = GetFoos(); bar = bar.RemoveAt(2); ```
The nature of arrays is that their length is immutable. You can't add or delete any of the array items. You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete. So it is probably better to use a List instead of an array.
Remove element of a regular array
[ "", "c#", ".net", "arrays", "" ]
I have a SWF Video player on my webpage. I want to draw a div tag over it with a high z-index to act as a popup on it . Its a very generic popup. Hence I cannot make it as a part of swf. but, SWF seems to have very high zIndex and would not allow any HTMLO entity to sit over it. How do I achieve this or is there an alternate solution. Thanks.
There are some arguments that have to be passed to the SWF file in order to be able to achieve that. In the HTML representation, inside the object tag you should put: ``` <param name="wmode" value="transparent"> ``` and... ``` <embed wmode="transparent" ... ``` A similar value should apply if you're using a JS library to render the SWF object.
You need to add a param to the flash object `<param NAME="wmode" VALUE="transparent">` this puts it back in the "flow" and allows other html elements to go on top oh and add the wmode="transparent" to th embed tag
HTML Object over a SWF
[ "", "javascript", "html", "flash", "" ]
I want to write a service (probably in c#) that monitors a database table. When a record is inserted into the table I want the service to grab the newly inserted data, and perform some complex business logic with it (too complex for TSQL). One option is to have the service periodically check the table to see if new records have been inserted. The problem with doing it that way is that I want the service to know about the inserts as soon as they happen, and I don't want to kill the database performance. Doing a little research, it seems like maybe writing a CLR trigger could do the job. I could write trigger in c# that fires when an insert occurs, and then send the newly inserted data to a Windows or WCF service. What do you think, is that a good (or even possible) use of SQL CLR triggers? Any other ideas on how to accomplish this?
Probably you should de-couple postprocessing from inserting: In the Insert trigger, add the record's PK into a queue table. In a separate service, read from the queue table and do your complex operation. When finished, mark the record as processed (together with error/status info), or delete the record from the queue.
What you are describing is sometimes called a Job Queue or a Message Queue. There are several threads about using a DBMS table (as well as other techniques) for doing this that you can find by searching. I would consider doing anything iike this with a Trigger as being an inappropriate use of a database feature that's easy to get into trouble with anyway. Triggers are best used for low-overhead dbms structural functionality (e.g. fine-grained referential integrity checking) and need to be lightweight and synchronous. It could be done, but probably wouldn't be a good idea.
Can SQL CLR triggers do this? Or is there a better way?
[ "", "sql", "sql-server", "t-sql", "triggers", "sqlclr", "" ]
Are there any built-in functions in .Net that allow to capitalize strings, or handling proper casing? I know there are some somewhere in the Microsoft.VB namespace, but I want to avoid those if possible. I'm aware of functions like string.ToUpper and string.ToLower() functions however it affects the entire string. I am looking to something like this: ``` var myString = "micah"; myString = myString.Format(FormattingOptions.Capitalize) //Micah ```
Just to throw another option into the mix. This will capitalize every word in the given string: ``` public static string ToTitleCase(string inputString) { System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo textInfo = cultureInfo.TextInfo; return textInfo.ToTitleCase(inputString.ToLower()); } ```
There's ``` System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(string str) ``` to capitalize every word in a string. [ToTitleCase](http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx)
Built-In Character Casing functions in .Net
[ "", "c#", ".net", "string", "" ]
Most references I've seen, and my IDE's code completion all have my specifying a Generic type on both a variables type and its implementation eg. ``` List<String> string = new ArrayList<String>(); ``` Recently I've started skipping the generic type on the implementation eg. ``` List<String> strings = new ArrayList(); ``` assuming that the compiler is only checking against the type for it's spiffy generics voodoo, and that the implementation shouldn't care, as its generic types are erased when it's compiled and should not affect run-time at all. Am I being naive? Is there a reason to include the generic type on the implementation?
> Is there a reason to include the generic type on the implementation? It's required as it won't necessarily be the same: ``` List<? extends Number> numbers = new ArrayList<Integer>(); ``` One way of avoiding it for common cases is to have static utility methods, and let the compiler's type inference do the rest: ``` class CollectionUtilities { static <T> ArrayList<T> arrayList () { return new ArrayList<T>(); } } ... import static CollectionUtilities.*; List<Integer> numbers = arrayList(); ``` This is type safe, and doesn't require the generic type on the implementation. (The reason itay's example is not safe the lack of the generic type on the type of the list variable, not anything to do whether you need to specify generic type on both the variable's type and the implementation.)
The compiler may allow you to write code with such assignments (depending on your warnings/errors settings) but it is unsafe. Here's an example: ``` List<Date> dates = new ArrayList<Date>(); List list = dates; List<String> strings = list; strings.add("a"); Date d = dates.get(0); // Boom!! ```
Java: Specifying generics on Type AND Implementation
[ "", "java", "generics", "" ]
I'm soon going to check in the very first commit of a new Java project. I work with Eclipse Ganymede and a bunch of plug ins are making things a little bit easier. Previously I've been part of projects where the entire Eclipse project was checked in. It's quite convenient to get the project settings after a check out. However this approach still was not problem free: * I strongly suspect that some Eclipse configuration files would change without user interaction (from when I used Eclipse Europa), making them appear as changed (as they were changed, but not interactively) when it's time to do a commit. * There are settings unique to each development machine as well as settings global for all developers on a project. Keeping these apart was hard. * Sometime if the Eclipse version was different from others Eclipse would get angry and mess up the project configuration. Another case is that it change the format so it gets updated, and if commited messes up the configuration for others. For this specific project I have another reason not to commit the project files: * There might be developers who prefer NetBeans which will join the project later. However they won't join within the coming months. How do you organize this? What do you check into versioning control and what do you keep outside? What do you consider best practice in this kind of situation?
At a minimum you should be check-in the `.project` and `.classpath` files. If anybody on your team is hard-coding an external JAR location in the `.classpath` you should put them up against the wall and shoot them. I use Maven to manage my dependencies but if you are not using maven you should create user libraries for your external JARs with with a consistent naming convention. After that you need to consider things on a plug-in by plug-in basis. For example I work with Spring so I always check-in the `.springBeans` and likewise for CheckStyle I always check-in the `.checkstyle` project. It gets a bit trickier when it comes to the configuration in the `.settings` folder but I generally check-in the following if I change the default settings for my project and want them shared with the rest of the team: * **.settings/org.eclipse.jdt.ui.prefs** - it contains the settings for the import ordering * **.settings/org.eclipse.jdt.core.prefs** - it contains the settings for the compiler version In general I haven't noticed Ganymede modifying files without me modifying the project preferences.
I recommend to use [maven](http://maven.apache.org) so that the entire life cycle is outside of any IDE. You can easily create an eclipse project with it on the command line and you can use whatever you want, if it's not eclipse. It has it's quirks but takes out a lot of bitterness when it comes to dependencies and build management.
To check in, or not check in, the entire Eclipse project?
[ "", "java", "eclipse", "version-control", "netbeans", "" ]
According to this <http://www.cplusplus.com/reference/clibrary/csignal/signal.html> `SIGINT` is generally used/cause by the user. How do i cause a `SIGINT` in c++? i seen an example using `kill(pid, SIGINT);` but i rather cause it another way. Also i am using windows.
C89 and C99 define raise() in signal.h: ``` #include <signal.h> int raise(int sig); ``` This function sends a signal to the calling process, and is equivalent to ``` kill(getpid(), sig); ``` If the platform supports threads, then the call is equivalent to ``` pthread_kill(pthread_self(), sig); ``` The return value is 0 on success, nonzero otherwise.
You cause a `SIGINT` by pressing `Ctrl+C`. Example code: ``` #include <stdio.h> #include <stdlib.h> #include <signal.h> void siginthandler(int param) { printf("User pressed Ctrl+C\n"); exit(1); } int main() { signal(SIGINT, siginthandler); while(1); return 0; } ``` When run: ``` $ ./a.out ^CUser pressed Ctrl+C $ ``` (Note that this is pure C code, should work in C++ though) Edit: The only way I know of to send `SIGINT` apart from interactively pressing `Ctrl+C` is using `kill(pid, SIGINT)` as you said...
Using SIGINT
[ "", "c++", "windows", "signals", "" ]
I've got a game engine where I'm splitting off the physics simulation from the game object functionality. So I've got a pure virtual class for a physical body ``` class Body ``` from which I'll be deriving various implementations of a physics simulation. My game object class then looks like ``` class GameObject { public: // ... private: Body *m_pBody; }; ``` and I can plug in whatever implementation I need for that particular game. But I may need access to all of the `Body` functions when I've only got a `GameObject`. So I've found myself writing tons of things like ``` Vector GameObject::GetPosition() const { return m_pBody->GetPosition(); } ``` I'm tempted to scratch all of them and just do stuff like ``` pObject->GetBody()->GetPosition(); ``` but this seems wrong (i.e. violates the Law of Demeter). Plus, it simply pushes the verbosity from the implementation to the usage. So I'm looking for a different way of doing this.
The idea of the law of Demeter is that your `GameObject` isn't supposed to have functions like `GetPosition()`. Instead it's supposed to have `MoveForward(int)` or `TurnLeft()` functions that may call `GetPosition()` (along with other functions) internally. Essentially they translate one interface into another. If your logic requires a `GetPosition()` function, then it makes sense turn that into an interface a la Ates Goral. Otherwise you'll need to rethink why you're grabbing so deeply into an object to call methods on its subobjects.
One approach you could take is to split the `Body` interface into multiple interfaces, each with a different purpose and give `GameObject` ownership of only the interfaces that it would have to expose. ``` class Positionable; class Movable; class Collidable; //etc. ``` The concrete `Body` implementations would probably implement all interfaces but a `GameObject` that only needs to expose its position would only reference (through dependency injection) a `Positionable` interface: ``` class BodyA : public Positionable, Movable, Collidable { // ... }; class GameObjectA { private: Positionable *m_p; public: GameObjectA(Positionable *p) { m_p = p; } Positionable *getPosition() { return m_p; } }; BodyA bodyA; GameObjectA objA(&bodyA); objA->getPosition()->getX(); ```
How to restructure this code hierarchy (relating to the Law of Demeter)
[ "", "c++", "oop", "refactoring", "law-of-demeter", "" ]
I want to put individual JComboBoxes into each cells of a JTable. ie. The JComboBox content is not identical for each cell. I basically would like to be able to just call the following code to add a row of JComboBox into the JTable. Anyone has any idea? Thanks ``` JComboBox cb1 = new JComboBox(...); JComboBox cb2 = new JComboBox(...); model.addRow(new Object[] {"Row name", cb1, cb2} ); JComboBox cb3 = new JComboBox(...); JComboBox cb4 = new JComboBox(...); model.addRow(new Object[] {"Row name 2", cb3, cb4} ); ``` The closest example code I can find is as follows. But it is for where JComboBox content is identical for the individual column. Not the solution I need. ``` TableColumn col = table.getColumnModel().getColumn(vColIndex); col.setCellEditor(new MyComboBoxEditor(values)); ``` where ``` public class MyComboBoxEditor extends DefaultCellEditor { public MyComboBoxEditor(String[] items) { super(new JComboBox(items)); } } ```
The easiest way is to implement your own [TableModel](http://java.sun.com/javase/6/docs/api/javax/swing/table/TableModel.html) ``` public class MyModel extends AbstractTableModel { List rows; public int getRowCount() { return rows.size(); } public int getColumnCount() { return 4; } public Object getValueAt(int row, int column) { return rows.get(row).getCol(col); //assuming your row "Object" has a getCol() } public Class<?> getColumnClass(int col) { return Boolean.class; } public void setValueAt(Object aValue, int rowIndex, int columnIndex) { rows.get(rowIndex).getCol(columnIndex).setValue(aValue); } } ``` Load this into you JTable. If you haven't replaced the default cell renderer for Boolean's, all you cells will be rendered as check boxes thanks to you implementation of getColumnClass(). All user input to these check boxes is collected with our setValueAt().
Extend JTable with this code: ``` @Override public TableCellEditor getCellEditor(int row, int column) { Object value = super.getValueAt(row, column); if(value != null) { if(value instanceof JComboBox) { return new DefaultCellEditor((JComboBox)value); } return getDefaultEditor(value.getClass()); } return super.getCellEditor(row, column); } ``` This will create a unique JComboBox cell editor for each combo box you get the a value for.
Putting JComboBox into JTable
[ "", "java", "jtable", "jcombobox", "" ]
Is there a good C++ framework to implement XA distributed transactions? With the term "good" I mean usable, simple (doesn't imply "easy"), well-structured. Due to study reasons, at the moment I'm proceeding with a personal implementation, following X/Open XA specification. Thank you in advance.
I am not aware of an open-source or free transaction monitor that has any degree of maturity, although [This link](http://linuxfinances.info/info/tpmonitor.html) does have some fan-out. The incumbent commercial ones are [BEA's Tuxedo,](http://www.bea.com/framework.jsp?CNT=index.htm&FP=/content/products/tux/) Tibco's [Enterprise Message Service](http://www.tibco.com/software/messaging/enterprise_messaging_service/default.jsp) (really a transactional message queue manager like IBM's MQ) and Transarc's [Encina](http://publib.boulder.ibm.com/infocenter/txformp/v5r1/index.jsp?topic=/com.ibm.txseries510.doc/aetgpk0012.htm) (now owned by IBM). These systems are all *very* expensive. If you want to make your own (and incidentally make a bit of a name for yourself by filling a void in the open-source software space) get a copy of [Grey and Reuter](https://rads.stackoverflow.com/amzn/click/com/1558601902). This is the definitive work on transaction processing systems architecture, written by two of the foremost experts in the field. Interestingly, they claim that one can implement a working TP monitor in around 10,000 lines of C. This actually sounds quite reasonable, as what it does is not all that complex. On occasion I have been tempted to try. Essentially you need to make a distributed transaction coordinator that runs as a daemon process. You will need to get the resource manager protocol working from it, so starting with this as a prototype is probably a good start. If you can get it to independently roll back or commit a transaction you have the basis of the TM-RM interface. The XA API as defined in the spec is the API to control the transaction manager. Strictly speaking, you don't need to make a 3-tier architecture to use distributed transactions of this sort, but they are more or less pointless without a TP monitor. How you communicate from the front-end to the middle-tier can be left as an exercise for the reader. You are probably best off using an existing ORB, of which there are several good open-source implementations available. Depending on whether you want to make the DTC and the app server separate processes (which is possibly desirable for stability but not strictly necessary) you could also use ACE as a basis for the DTC server. If you want to make a high-performance middle-tier server, check out Douglas Schmidt's [ACE framework](http://www.cs.wustl.edu/~schmidt/ACE-overview.html). This comes with an ORB called TAO, and is flexible enough to allow you to use more or less any threading model that takes your fancy. Using this is a trade-off between learning it and the effort of writing your own and debugging all the synchronisation and concurrancy issues.
Maybe quite late for your task, but it can be useful for other users: [LIXA](https://sourceforge.net/projects/lixa/) is not a "framework", but it provides an implementation for the TX Transaction Demarcation specification and supports most of the XA features. The TX specification is for C and COBOL languages, but the integration of the C version inside a C++ project should be effortless.
XA distributed transactions in C++
[ "", "c++", "xa", "" ]
Why I can use `Object Initializers` in Visual Studio 2008 Windows projects, etc targeted to .NET 2.0 but cannot - in ASP.NET projects targeted to .NET 2.0 ? I understand that this is C# 3.0 features, but don't - why this possible to use in .NET 2.0 projects.
Probably because the ASP.Net stuff targeting the 2.0 framework assumes it will run in a mode where it may have to compile some code on the fly. Since it is running in 2.0 mode it will get the 2.0 compiler at that stage (thus anything relying on the 3.0 compiler will fail) When targeting the 2.0 codebase from a 'normal' project the compilation is done then and there so relying on 3.0 compiler functionality is fine.
When you target the .NET 2.0 runtime, you are also targeting the C# 2.0 compiler. That version of the compiler does not understand the 3.0 features.
Why I cannot use Object Initializers in ASP.NET 2.0?
[ "", "c#", "asp.net", "object-initializers", "" ]
I am storing the response to various rpc calls in a mysql table with the following fields: ``` Table: rpc_responses timestamp (date) method (varchar) id (varchar) response (mediumtext) PRIMARY KEY(timestamp,method,id) ``` What is the best method of selecting the most recent responses for all existing combinations of `method` and `id`? * For each date there can only be one response for a given method/id. * Not all call combinations are necessarily present for a given date. * There are dozens of methods, thousands of ids and at least 365 different dates Sample data: ``` timestamp method id response 2009-01-10 getThud 16 "....." 2009-01-10 getFoo 12 "....." 2009-01-10 getBar 12 "....." 2009-01-11 getFoo 12 "....." 2009-01-11 getBar 16 "....." ``` Desired result: ``` 2009-01-10 getThud 16 "....." 2009-01-10 getBar 12 "....." 2009-01-11 getFoo 12 "....." 2009-01-11 getBar 16 "....." ``` (I don't think [this](https://stackoverflow.com/questions/189213/sql-selecting-rows-by-most-recent-date) is the same question - it won't give me the most recent `response`)
Self answered, but I'm not sure that it will be an efficient enough solution as the table grows: ``` SELECT timestamp,method,id,response FROM rpc_responses INNER JOIN (SELECT max(timestamp) as timestamp,method,id FROM rpc_responses GROUP BY method,id) latest USING (timestamp,method,id); ```
> This solution was updated recently. > Comments below may be outdated This can query may perform well, because there are no joins. ``` SELECT * FROM ( SELECT *,if(@last_method=method,0,1) as new_method_group,@last_method:=method FROM rpc_responses ORDER BY method,timestamp DESC ) as t1 WHERE new_method_group=1; ``` Given that you want one resulting row per `method` this solution should work, using mysql variables to avoid a JOIN. FYI, PostgreSQL has a way of doing this built into the language: ``` SELECT DISTINCT ON (method) timestamp, method, id, response FROM rpc_responses WHERE 1 # some where clause here ORDER BY method, timestamp DESC ```
How to select the most recent set of dated records from a mysql table
[ "", "mysql", "sql", "date", "greatest-n-per-group", "" ]
I'm a newbie when it comes to LINQ... I have an IEnumerable generic list that contains answers with different versions (each with an FK to the question). From this list I need to get a dictionary of latest version answers only. A very simplified class diagram: Question -ID -question - ...other properties Answer -ID -Version -QuestionID -Value - ...other properties Currently I've got the following : ``` IEnumerable<Answer> answers = GetAnswers(); IDictionary<long, AnswerDTO> latestVersionAnswers = new Dictionary<long, AnswerDTO>(); if (answers != null) { latestVersionAnswers = answers .OrderBy(e => e.ID) .GroupBy(e => e.Question.ID) .Select(g => new AnswerDTO { Version = g.Last().Version, // g.Select(e => e.Version).Max(), QuestionID = g.Key, ID = g.Last().ID, Value = g.Last().Value }).ToDictionary(c => c.QuestionID); } ``` While this works for the most part, you can quickly see that it needs some serious optimization (and is a little fragile in that it depends on the Answer record rows order instead of "Max" logic). What would be the best way to do this with LINQ, or is it best to just do multiple for each loops? 1. If I only needed the version (and not the ID, Value, etc.) I wouldn't need the OrderBy as I could just go g.Select(e => e.Version).Max() (or I've now seen the post at [C# List<> GroupBy 2 Values](https://stackoverflow.com/questions/363655/c-list-groupby-2-values), but this again would only return the key/s and one property: Version). 2. Ultimately, in this particularly situation I would much prefer to just "filter" the original list and return the original answer items instead of involving the AnswerDTO. Any pointers or help would be much appreciated!
How about something like.... ``` private void button1_Click(object sender, EventArgs e) { List<Answer> list = GetAnswers(); var dict = (from a in list group a by a.QuestionID into grp from g in grp where g.Version == grp.Max(m => m.Version) select new { id = g.QuestionID, q = g }).ToDictionary( o => o.id, o => o.q); StringBuilder sb = new StringBuilder(); foreach (var elem in dict) { sb.AppendLine(elem.Key.ToString() + "-" + elem.Value.Version.ToString()); } MessageBox.Show(sb.ToString()); } private List<Answer> GetAnswers() { List<Answer> result = new List<Answer>(); result.Add(new Answer() { ID = 1, QuestionID = 1, Version = 1 }); result.Add(new Answer() { ID = 2, QuestionID = 1, Version = 2 }); result.Add(new Answer() { ID = 3, QuestionID = 1, Version = 3 }); result.Add(new Answer() { ID = 4, QuestionID = 2, Version = 1 }); result.Add(new Answer() { ID = 5, QuestionID = 2, Version = 2 }); result.Add(new Answer() { ID = 6, QuestionID = 2, Version = 3 }); result.Add(new Answer() { ID = 7, QuestionID = 3, Version = 1 }); result.Add(new Answer() { ID = 8, QuestionID = 3, Version = 2 }); result.Add(new Answer() { ID = 9, QuestionID = 3, Version = 3 }); result.Add(new Answer() { ID = 10, QuestionID = 3, Version = 4 }); return result; } ```
``` latestVersionAnswers = answers .GroupBy(e => e.Question.ID) .Select(g => g.OrderByDescending(e => e.Version).First()) .ToDictionary(e => e.Question.ID); ``` Or, if you prefer the selecting overload of ToDictionary: ``` latestVersionAnswers = answers .GroupBy(e => e.Question.ID) .ToDictionary( g => g.Key, g => g.OrderByDescending(e => e.Version).First() ); ```
LINQ with subselect and groupby to get only the latest version of each item in a list
[ "", "c#", "linq", "lambda", "" ]
I was using [xampp](http://www.apachefriends.org/en/xampp.html) to develop locally and then I installed the PHP from the direct installer. Now in some of my PHP code, only PHP code that starts with `"<?php`" is correctly parsed. Anything that starts with "`<?`" or "`<?=`" is completely ignored and just left as is. How can I adjust the configuration to parse either tokens?
This is a php.ini setting named ``` short_open_tag = 1 # (enabled) ```
I recommend you to disable [`short_open_tag`](http://www.php.net/manual/en/ini.core.php#ini.short-open-tag) and only work with `<?php`. When `short_open_tag` is enabled, it can collide with the [XML processing instruction](http://www.w3.org/TR/REC-xml/#sec-pi) `<?xml` as both the PHP open tag and XML PI start with a `<?`.
Why is "<?" no longer working and instead only "<?php" works?
[ "", "php", "xampp", "" ]
In PHP you can just use `$_POST` for POST and `$_GET` for GET (Query string) variables. What's the equivalent in Python?
suppose you're posting a html form with this: ``` <input type="text" name="username"> ``` If using [raw cgi](http://docs.python.org/library/cgi.html): ``` import cgi form = cgi.FieldStorage() print form["username"] ``` If using [Django](http://docs.djangoproject.com/), [Pylons](http://pylonshq.com/), [Flask](http://flask.pocoo.org/) or [Pyramid](http://www.pylonsproject.org/projects/pyramid/about): ``` print request.GET['username'] # for GET form method print request.POST['username'] # for POST form method ``` Using [Turbogears](http://turbogears.org/), [Cherrypy](http://www.cherrypy.org/): ``` from cherrypy import request print request.params['username'] ``` [Web.py](http://webpy.org): ``` form = web.input() print form.username ``` [Werkzeug](http://werkzeug.pocoo.org/): ``` print request.form['username'] ``` If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly: ``` def index(self, username): print username ``` [Google App Engine](https://developers.google.com/appengine/docs/python/gettingstartedpython27/introduction): ``` class SomeHandler(webapp2.RequestHandler): def post(self): name = self.request.get('username') # this will get the value from the field named username self.response.write(name) # this will write on the document ``` So you really will have to choose one of those frameworks.
I know this is an old question. Yet it's surprising that no good answer was given. First of all the question is completely valid without mentioning the framework. The CONTEXT is a PHP language equivalence. Although there are many ways to get the query string parameters in Python, the framework variables are just conveniently populated. In PHP, `$_GET` and `$_POST` are also convenience variables. They are parsed from QUERY\_URI and php://input respectively. In Python, these functions would be `os.getenv('QUERY_STRING')` and `sys.stdin.read()`. Remember to import os and sys modules. We have to be careful with the word "CGI" here, especially when talking about two languages and their commonalities when interfacing with a web server. 1. CGI, as a protocol, defines the data transport mechanism in the HTTP protocol. 2. Python can be configured to run as a CGI-script in Apache. 3. The CGI module in Python offers some convenience functions. Since the HTTP protocol is language-independent, and that Apache's CGI extension is also language-independent, getting the GET and POST parameters should bear only syntax differences across languages. Here's the Python routine to populate a GET dictionary: ``` GET={} args=os.getenv("QUERY_STRING").split('&') for arg in args: t=arg.split('=') if len(t)>1: k,v=arg.split('='); GET[k]=v ``` and for POST: ``` POST={} args=sys.stdin.read().split('&') for arg in args: t=arg.split('=') if len(t)>1: k, v=arg.split('='); POST[k]=v ``` You can now access the fields as following: ``` print GET.get('user_id') print POST.get('user_name') ``` I must also point out that the CGI module doesn't work well. Consider this HTTP request: ``` POST / test.py?user_id=6 user_name=Bob&age=30 ``` Using `CGI.FieldStorage().getvalue('user_id')` will cause a null pointer exception because the module blindly checks the POST data, ignoring the fact that a POST request can carry GET parameters too.
How are POST and GET variables handled in Python?
[ "", "python", "post", "get", "" ]
I need to add line breaks in the positions that the browser naturally adds a newline in a paragraph of text. For example: <p>This is some very long text **\n** that spans a number of lines in the paragraph.</p> This is a paragraph that the browser chose to break at the position of the **\n** I need to find this position and insert a <br /> Does anyone know of any JS libraries or functions that are able to do this? The only solutuion that I have found so far is to remove tokens from the paragraph and observe the clientHeight property to detect a change in element height. I don't have time to finish this and would like to find something that's already tested. **Edit:** The reason I need to do this is that I need to accurately convert HTML to PDF. Acrobat renders text narrower than the browser does. This results in text that breaks in different positions. I need an identical ragged edge and the same number of lines in the converted PDF. **Edit:** @dtsazza: Thanks for your considered answer. It's not impossible to produce a layout editor that almost exactly replciates HTML I've written 99% of one ;) The app I'm working on allows a user to create a product catalogue by dragging on 'tiles' The tiles are fixed width, absolutely positioned divs that contain images and text. All elemets are styled so font size is fixed. My solution for finding \n in paragraph is ok 80% of the time and when it works with a given paragrah the resulting PDF is so close to the on-screen version that the differences do not matter. Paragraphs are the same height (to the pixel), images are replaced with high res versions and all bitmap artwork is replaced with SVGs generated server side. The only *slight* difference between my HTML and PDF is that Acrobat renderes text slightly more narrowly which results in line slightly shorter line length. Diodeus's solution of adding span's and finding their coords is a very good one and should give me the location of the BRs. Please remember that the user will never see the HTML with the inserted BRs - these are added so that the PDF conversion produces a paragraph that is exactly the same size. There are lots of people that seem to think this is impossible. I already have a working app that created *extremely* accurate HTML->PDF conversion of our docs - I just need a better solution of adding BRs because my solution sometimes misses a BR. BTW when it does work my paragraphs are the same height as the HTML equivalents which is the result we are after. If anyone is interested in the type of doc i'm converting then you can check ou this screen cast: <http://www.localsa.com.au/brochure/brochure.html> **Edit:** Many thanks to Diodeus - your suggestion was spot on. Solution: for my situation it made more sense to wrap the words in spans instead of the spaces. var text = paragraphElement.innerHTML.replace(/ /g, '</span> <span>'); text = "<span>"+text+"</span>"; //wrap first and last words. This wraps each word in a span. I can now query the document to get all the words, iterate and compare y position. When y pos changes add a br. This works flawlessly and gives me the results I need - Thank you!
I would suggest wrapping all spaces in a span tag and finding the coordinates of each tag. When the Y-value changes, you're on a new line.
I don't think there's going to be a very clean solution to this one, if any at all. The browser will flow a paragraph to fit the available space, linebreaking where needed. Consider that if a user resizes the browser window, all the paragraphs will be rerendered and almost certainly will change their break positions. If the user changes the size of the text on the page, the paragraphs will be rerendered with different line break points. If you (or some script on your page) changes the size of another element on the page, this will change the amount of space available to a floating paragraph and again - different line break points. Besides, changing the actual markup of your page to mimic something that the browser does for you (and does very well) seems like the wrong approach to whatever you're doing. What's the *actual* problem you're trying to solve here? There's probably a better way to achieve it. **Edit**: OK, so you want to render to PDF the same as "the screen version". Do you have a specific definitive screen version nominated - in terms of browser window dimensions, user stylesheets, font preferences and adjusted font size? **The critical thing about HTML is that it deliberately does not specify a specific layout**. It simply describes what is on the page, what they are and where they are in relation to one another. I've seen several misguided attempts before to produce some HTML that will exactly replicate a printed creative, designed in something like a DTP application where a definitive absolute layout is essential. Those efforts were doomed to failure because of the nature of HTML, and doing it the other way round (as you're trying to) will be even *worse* because you don't even have a definitive starting point to work from. On the assumption that this is all out of your hands and you'll have to do it *anyway*, my suggestion would be to give up on the idea of mangling the HTML. Look at the PDF conversion software - if it's any good it should give you some options for font kerning and similar settings. Playing around with the details here should get you something that approximates the font rendering in the browser and thus breaks lines at the same places. Failing that, all I can suggest is taking screenshots of the browser and parsing these with OCR to work out where the lines break (it shouldn't require a very accurate OCR since you know what the raw text is anyway, it essentially just has to count spaces). Or perhaps just embed the screenshot in the PDF if text search/selection isn't a big deal. Finally doing it by hand is likely the only way to make this work definitively and reliably. But really, this is still just *wrong* and any attempts to revise the requirements would be better. Keep going up one step in the chain - *why* does the PDF have to have the exact same ragged edge as some arbitrary browser rendering? Can you achieve *that* purpose in another (better) way?
How to find where browser breaks a paragraph of text
[ "", "javascript", "html", "" ]
I'm trying to use this code to replace spaces with \_, it works for the first space in the string but all the other instances of spaces remain unchanged. Anybody know why? ``` function updateKey() { var key=$("#title").val(); key=key.replace(" ","_"); $("#url_key").val(key); } ```
Try `.replace(/ /g,"_");` *Edit*: or `.split(' ').join('_')` if you have an aversion to REs *Edit*: [John Resig said](http://ejohn.org/blog/javascript-micro-templating/): > If you're searching and replacing > through a string with a static search > and a static replace it's faster to > perform the action with > .split("match").join("replace") - > which seems counter-intuitive but it > manages to work that way in most > modern browsers. (There are changes > going in place to grossly improve the > performance of .replace(/match/g, > "replace") in the next version of > Firefox - so the previous statement > won't be the case for long.)
try this: ``` key=key.replace(/ /g,"_"); ``` that'll do a global find/replace [javascript replace](http://www.w3schools.com/jsref/jsref_replace.asp)
Replacing spaces with underscores in JavaScript?
[ "", "javascript", "string", "" ]
What do you recommend for setting the MAMP development stack? I've seen the quickstart thing at <http://www.mamp.info>, but I don't really like that approach. I'd rather have a full-fledged Apache that I can install any number of modules into. I remember seeing in the OS X v10.5 (Leopard) Server demo a really slick GUI that allows you to set up all this stuff, add virtual hosts, etc., and I was wondering if anything similar is available for the non-server Leopard.
OS X already comes with Apache, PHP, Perl and Python. Just install MySQL and edit the Apache config file as needed and you should be golden.
You could use [Darwin Ports](http://darwinports.com/) or [Fink](http://www.finkproject.org/) to install everything from scratch.
How can I get started with Apache, MySQL, and (PHP, Perl, Python) on a Mac?
[ "", "php", "mysql", "perl", "apache", "macos", "" ]
I overloaded the 6 signals listed on this site <http://www.cplusplus.com/reference/clibrary/csignal/signal.html> Then i ran my app (double click not ran through IDE) and tried 1) end task 2) X on topright and 3) kill process. I expected the first two to cause some kind of signal (i am on XP) but alas i got nothing. Am i not allowed to open files to write into when a signal occurs? i am guessing i am (SIGSEGV allowed me). When firefox crashes or when i kill it, it remembers what pages i was. Does it log the address everytime i click a page or does it do that on a signal/crash? my main question is what signal can i use to catch kill process
Win32 does not provide an option to intercept your program being killed with `TerminateProcess` (which is what will happen when you "End Task" from Task Manager or click on the [X]). You can catch the SIGSEGV signal because the C runtime library provides an emulation of this signal when running on Windows. When your program causes a Windows access violation (exception 0xC0000005), the runtime library has the option to catch that and simulate a Unix style SIGSEGV for you. This is, however, not the best way to handle such an exception. If you are writing a Win32 program, you shouldn't generally try to use Unix style services.
You can catch runtime error like an access violation if you override the default exception handler calling SetUnhandledExceptionFilter (this is a win32 function and as such doesn't rely on C library emulation). This is the method can used to provide "minidumps" when a program crashes. But this exception handler will not be called when you normally close your application, or when your application is closed from Task manager. In the last case windows is calling TerminateProcess, is not a clean shutdown but it is forcing your program to terminate. I'm not aware of which is the implementation used by Firefox, but to save the current tabs open is likely to have a timer running, and each time it is run it save the history to a file and some kind of dirty mark. Other more complex solutions to detect when a program is closed (implemented by antivirus and similar programs) is to have two unrelated programs running, each checking that the other is still running, and if one detect the other was closed the run it again.
signal when user kills process?
[ "", "c++", "windows-xp", "crash", "signals", "kill-process", "" ]
I have the following code: ``` // Obtain the string names of all the elements within myEnum String[] names = Enum.GetNames( typeof( myEnum ) ); // Obtain the values of all the elements within myEnum Array values = Enum.GetValues( typeof( myEnum ) ); // Print the names and values to file for ( int i = 0; i < names.Length; i++ ) { print( names[i], values[i] ); } ``` However, I cannot index values. Is there an easier way to do this? Or have I missed something entirely!
``` Array values = Enum.GetValues(typeof(myEnum)); foreach( MyEnum val in values ) { Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val)); } ``` Or, you can cast the System.Array that is returned: ``` string[] names = Enum.GetNames(typeof(MyEnum)); MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum)); for( int i = 0; i < names.Length; i++ ) { print(names[i], values[i]); } ``` But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?
You need to cast the array - the returned array is actually of the requested type, i.e. `myEnum[]` if you ask for `typeof(myEnum)`: ``` myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum)); ``` Then `values[0]` etc
C# Iterating through an enum? (Indexing a System.Array)
[ "", "c#", "enums", "iteration", "system.array", "" ]
Given a dictionary like so: ``` my_map = {'a': 1, 'b': 2} ``` How can one invert this map to get: ``` inv_map = {1: 'a', 2: 'b'} ```
Python 3+: ``` inv_map = {v: k for k, v in my_map.items()} ``` Python 2: ``` inv_map = {v: k for k, v in my_map.iteritems()} ```
Assuming that the values in the dict are unique: Python 3: ``` dict((v, k) for k, v in my_map.items()) ``` Python 2: ``` dict((v, k) for k, v in my_map.iteritems()) ```
Reverse / invert a dictionary mapping
[ "", "python", "dictionary", "mapping", "reverse", "" ]
I want to use a string that I have been using in one aspx.cs file over to another. I know this is easy, but how do I go about doing that?
You can do it in a query string. On your first page: ``` Response.Redirect("Second.aspx?book=codecomplete"); ``` and on the second page ``` string book = Request["book"]; ``` This method will allow your users to see what you are passing to a second page. Alternatively you can place it in session object. To place it use: ``` Session["book"] = "codecomplete"; ``` and to get it back use: ``` string book = Session["book"] as string; ``` As a third alternative, you can use Server.Transfer. Use this method if you want to go to the second page on the server side. But notice that your user will continue to see the url of the first page on address bar. On page 1: ``` this.SomeProperty = "codecomplete"; Server.Transfer("SecondPage.aspx"); ``` On page 2: ``` string book = (PreviousPage as Page1).SomeProperty; ```
You can either send it using a querystring or you can define a session variable to store it. The best option depends on what you want to use that string for.
How do I bring a string from one aspx.cs page to another?
[ "", "c#", ".net", "asp.net", "" ]
Often, one needs several enumerated types together. Sometimes, one has a name clash. Two solutions to this come to mind: use a namespace, or use 'larger' enum element names. Still, the namespace solution has two possible implementations: a dummy class with nested enum, or a full blown namespace. I'm looking for pros and cons of all three approaches. Example: ``` // oft seen hand-crafted name clash solution enum eColors { cRed, cColorBlue, cGreen, cYellow, cColorsEnd }; enum eFeelings { cAngry, cFeelingBlue, cHappy, cFeelingsEnd }; void setPenColor( const eColors c ) { switch (c) { default: assert(false); break; case cRed: //... break; case cColorBlue: //... //... } } // (ab)using a class as a namespace class Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; }; class Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; }; void setPenColor( const Colors::e c ) { switch (c) { default: assert(false); break; case Colors::cRed: //... break; case Colors::cBlue: //... //... } } // a real namespace? namespace Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; }; namespace Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; }; void setPenColor( const Colors::e c ) { switch (c) { default: assert(false); break; case Colors::cRed: //... break; case Colors::cBlue: //... //... } } ```
**Original C++03 answer:** The *benefit* from a `namespace` (over a `class`) is that you can use `using` declarations when you want. The *problem* with using a `namespace` is that namespaces can be expanded elsewhere in the code. In a large project, you would not be guaranteed that two distinct enums don't both think they are called `eFeelings` For simpler-looking code, I use a `struct`, as you presumably want the contents to be public. If you're doing any of these practices, you are ahead of the curve and probably don't need to scrutinize this further. **Newer, C++11 advice:** If you are using C++11 or later, `enum class` will implicitly scope the enum values within the enum's name. With `enum class` you will lose implicit conversions and comparisons to integer types, but in practice that may help you discover ambiguous or buggy code.
FYI In C++0x there is a new syntax for cases like what you mentioned (see [C++0x wiki page](http://en.wikipedia.org/wiki/C%2B%2B0x#Strongly_typed_enumerations)) ``` enum class eColors { ... }; enum class eFeelings { ... }; ```
namespaces for enum types - best practices
[ "", "c++", "enums", "scope", "nested", "" ]
For those of you with experience with both, what are the major differences? For a newcomer to either, which would be better to learn? Are there situations where you might choose C but then other situations where you would choose C++? Is it a case of use the best tool for the job or one is significantly better than the other. I know C++ is an "enhancement" of C, but it was created in '83 and hasn't completely replaced C so there must be something more to it. I know this question is subjective and I am not trying to start any religious war, so please try to be as objective as possible. Clear strengths and weaknesses and comparisons.
While C is a pure procedural language, C++ is a *multi-paradigm* language. It supports * Generic programming: Allowing to write code once, and use it with different data-structures. * Meta programming: Allowing to utilize templates to generate efficient code at compile time. * Inspection: Allows to inspect certain properties at compile time: What type does an expression have? How many parameters does a function have? What type does each one have? * Object oriented programming: Allowing the programmer to program object oriented, with sophisticated features such as multiple inheritance and private inheritance. * Procedural programming: Allows the programmer to put functions free of any classes. Combined with advanced features such as ADL allows writing clean code decoupled from specifics of certain classes. Apart from those, C++ has largely kept compatibility with C code, but there are some differences. Those can be read about in Annex D of the C++ Standard, together with reasons and possible fixed to make C code valid C++ code.
C++ is 99% a superset of C. It's a little more strict in syntax, with a few very minute differences in terms of things changing. The biggest difference is that C++ makes an attempt at being object oriented. There's native support for classes. There's a few other perks in C++: templates, stream operators, pass-by-reference (a bit less confusing than pass-by-pointer) What do you lose out for going C++? It's missing some of the lowest-level hacks that a lot of people use C for. I don't remember any of them offhand, but I've never heard any good argument for tricking the compiler into doing what you want except as a way to push efficiency that extra 10%.
What are the major differences between C and C++ and when would you choose one over the other?
[ "", "c++", "c", "programming-languages", "" ]
I have good knowledge on the working of a "traditional" `.dll`. Also the differences between `dynamic loading` and `static loading`, etc. But I have the following doubts about the working of COM objects, * Is it mandatory to register COM objects with `regsvr32`? * can I have two versions of a registered `COM object` lying in the same/different directory? * besides being packaged inside a .dll file is there anything in common between a "traditional" `.dll` and a `COM object`?
1) No - it is NOT necessary to register COM *objects*. Registration is needed to create *new* COM objects. There are many interfaces (COM or native functions) that want a COM object. Their API tells you which interface your COM object should support. Since you pass in an existing COM object, they don't need registration information to create your COM object. A variation of this scenario is the RUnning Object Table, in which you can register created COM objects. Those objects are also created by you, and you don't need the registration info. Example interface: IQueryCancelAutoplay. 2) A COM *object* exists in memory. You're probably thinking about a COM *class*, implemented in a DLL together with its COM factory. COM classes are registered by their GUID. You can have multipe classes=GUIDs per DLL, but only one DLL per class. Remember, the caller asks COM for an instance of your class. Which DLL would COM load if there would be two DLLs implementing the same class?! Of course, there can be two DLLs each implementing one class, where the two classes share some interfaces. They will always share IUnknown, for instance, often IDispatch, but rarely IAcmeCorpFooBarv2 3) A COM DLL *is* a normal DLL which (a) exposes some COM-specific functions and (b) is registered so the COM framewrok can call LoadLibrary on it. The DLL may also expose other non-COM functions. As a result, you can call LoadLibrary on a COM DLL yourself. This can occasionally be useful to reduce the latency involved in creating your first COM object.
Yes, COM assemblies are registered so that the COM infrastructure knows they exist. The DLLs are found by registration of a CLSID, not by path. Two versions could co-exist if they have different names (you can't have the same named file in a folder, obviously). All COM objects implement specific interfaces (IUnknown, many have IDispatch). How COM works really is a subject way beyond what we could post here. You might get a book like ATL Internals or run through some online COM tutorials.
Questions about COM/ActiveX objects
[ "", "c++", "c", "com", "dll", "activex", "" ]
Is it bad practice to have a string like "name=Gina;postion= HouseMatriarch;id=1234" to hold state data in an application.I know that I could just as well have a struct , class or hashtable to hold this info. Is it acceptable practice to hold delimited key/value pairs in a database field– just for use in where the data type is not known at design time. Thanks...I am just trying to insure that I maintain good design practices
Yes, holding your data in a string like "name=Gina;postion= HouseMatriarch;id=1234" is very bad practice. This data structure should be stored in structs or objects, because it is hard to access, validate and process the data in a string. It will take you much more time to write the code to parse your string to get at your data than just using the language structures of C#. I would also advise against storing key/value pairs in database fields if the other option is just adding columns for those fields. If you don't know the type of your data at design time, you are probably not doing the design right. How will you be able to build an application when you don't know what data types your fields will have to hold? Or perhaps you should elaborate on the context of the application to make the intent clearer. It is not all black and white :-)
Well, if your application only passes this data between other systems, I don't see any problems in treating it as a string. However, if you need to use the data, I would definitely introduce the necessary types to handle that.
C# Is holding data in a delimited string bad practice
[ "", "c#", "" ]
In my application I am running the same winform in different contexts to control visibility of buttons, enabeling of text fields and the winform header text. The way I decided to do this is simply by passing a string to the form constructor and check it with a couple of if statements that in turn contain the desired winform tweaks. ``` if (formContext == "add") { Text = "Add member"; } if (formContext == "edit") { Text = "Change role"; userTextBox.Enabled = false; searchButton.Visible = false; } ``` This works fine, however the "Text" keywords get a blue squigly line added by ReSharper with the following message: Viritual member call in constructor. Is this a potential problem or just some sort of overly enthusiastic ReSharper message. Any clarification or suggestions for improvement of my implementation would be much appreciated.
A virtual member call in the base class ctor *could* cause some logic to run in the subclass before the subclass' ctor is called (and thus before the object gets a chance to initialize itself to a consistent state). It's just a nice reminder so you know you are doing something that could potentially cause some nasty unexpected behavior.
In addition to the existing answers, for forms you could add a Load event handler: ``` Load += delegate { if (formContext == "add") { Text = "Add member"; } if (formContext == "edit") { Text = "Change role"; userTextBox.Enabled = false; searchkButton.Visible = false; } }; ```
Virtual member call in constructor
[ "", "c#", "visual-studio-2008", "resharper", "" ]
I created a new email box for general support questions. When I try to send an email through SMTP I receive the following error: > Mailbox unavailable. The server response was: No such recipient I am able to email the box through Outlook and SMTP works when I send to other email address in the same domain.
The great thing about SMTP is that it's easy to spoof the conversation. The terrible thing about SMTP is also that it's easy to spoof the conversation. What makes this great is that if you want to figure out what's going wrong in a SMTP connection you can just "telnet mailhost 25" and start issuing SMTP commands like: ``` HELO example.com MAIL FROM: <me@me.com> RCPT TO: <him@him.com> DATA Subject: test message From: Me <me@me.com> To: Him <him@him.com> test message . QUIT ```
Is your DNS configured properly? You need an MX record specifying which host handles incoming messages for that domain. Btw, your post is missing some details, like which server you are using etc. That makes it hard to find where the problem is.
SMTP Email: Mailbox unavailable. The server response was: No such recipient
[ "", "c#", "email", "smtp", "" ]
**How does one performance tune a SQL Query?** * What tricks/tools/concepts can be used to change the performance of a SQL Query? * How can the benefits be Quantified? * What does one need to be careful of? **What tricks/tools/concepts can be used to change the performance of a SQL Query?** * Using Indexes? How do they work in practice? * Normalised vs Denormalised Data? What are the performance vs design/maintenance trade offs? * Pre-processed intermediate tables? Created with triggers or batch jobs? * Restructure the query to use Temp Tables, Sub Queries, etc? * Separate complex queries into multiples and UNION the results? * Anything else? **How can performance be Quantified?** * Reads? * CPU Time? * "% Query Cost" when different versions run together? * Anything else? **What does one need to be careful of?** * Time to generate Execution Plans? (Stored Procs vs Inline Queries) * Stored Procs being forced to recompile * Testing on small data sets (Do the queries scale linearly, or square law, etc?) * Results of previous runs being cached * Optimising "normal case", but harming "worst case" * What is "Parameter Sniffing"? * Anything else? *Note to moderators:* This is a huge question, should I have split it up in to multiple questions? *Note To Responders:* Because this is a huge question please reference other questions/answers/articles rather than writing lengthy explanations.
I really like the book "Professional SQL Server 2005 Performance Tuning" to answer this. It's Wiley/Wrox, and no, I'm not an author, heh. But it explains a lot of the things you ask for here, plus hardware issues. But yes, this question is way, way beyond the scope of something that can be answered in a comment box like this one.
Writing sargable queries is one of the things needed, if you don't write sargable queries then the optimizer can't take advantage of the indexes. Here is one example [Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/only-in-a-database-can-you-get-1000-impr) this query went from over 24 hours to 36 seconds
Performance Tuning SQL - How?
[ "", "sql", "performance", "" ]
How can I convert seconds into (Hour:Minutes:Seconds:Milliseconds) time? Let's say I have 80 seconds; are there any specialized classes/techniques in .NET that would allow me to convert those 80 seconds into (00h:00m:00s:00ms) format like `Convert.ToDateTime` or something?
For **.Net <= 4.0** Use the TimeSpan class. ``` TimeSpan t = TimeSpan.FromSeconds( secs ); string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", t.Hours, t.Minutes, t.Seconds, t.Milliseconds); ``` (As noted by Inder Kumar Rathore) For **.NET > 4.0** you can use ``` TimeSpan time = TimeSpan.FromSeconds(seconds); //here backslash is must to tell that colon is //not the part of format, it just a character that we want in output string str = time .ToString(@"hh\:mm\:ss\:fff"); ``` (From Nick Molyneux) Ensure that seconds is less than `TimeSpan.MaxValue.TotalSeconds` to avoid an exception.
For **.NET > 4.0** you can use ``` TimeSpan time = TimeSpan.FromSeconds(seconds); //here backslash is must to tell that colon is //not the part of format, it just a character that we want in output string str = time .ToString(@"hh\:mm\:ss\:fff"); ``` or if you want date time format then you can also do this ``` TimeSpan time = TimeSpan.FromSeconds(seconds); DateTime dateTime = DateTime.Today.Add(time); string displayTime = dateTime.ToString("hh:mm:tt"); ``` For more you can check [Custom TimeSpan Format Strings](http://msdn.microsoft.com/en-us/library/ee372287.aspx)
How can I convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?
[ "", "c#", "datetime", "" ]
I'm looking for some clarity on the SQL Server log file. I have a largish database (2GB) which lately wasn't backed up for whatever reason. The log file for the database grew to around 11GB which from my understanding is all the transactions and statements that occurred in the database. My questions: What causes the database log file to be flushed? What does "flush" actually mean? What are the consequences of doing a file shrink or database shrink on a large log file?
Once you backup the transaction log, those transactions are truncated from the log but the space used by the operation is not automatically recovered. If you are doing regular transaction log backups, this can be a good thing. The assumption being that the space being used for transactions and will be needed again in the future. Continuously shrinking the transaction log can be bad for performance since when needed again the database will need to expand the log. So to fix your issue, first do a full backup and a transaction log backup. You don't need to go to Simple mode or single-user. Then shrink the database and set up a transaction log backup every few hours. On my servers I do it every 10 minutes, but it entirely depends how often one needs for their environment. Monitor how the log size changes, be sure to leave enough room such that it does not have to expand regularly, plus a little extra for fun. When you do shrink the database use [DBCC SHRINKFILE](http://msdn.microsoft.com/en-us/library/ms189493.aspx) rather than [DBCC SHRINKDATABASE](http://msdn.microsoft.com/en-us/library/ms190488.aspx) since the latter will shrink the entire database, not just the log file. Also you don't have as much control over how much space is being recovered.
A backup usually clears the transaction log. The transaction log keeps all changes since the last backup. Depending on how you backup the database you may not need to keep a full transaction log at all. If you are using MS SQL2000/MS SQL2005 setting the recovery mode to **Simple** does away with the transaction log. Once you are sure you have a clean copy of the database (with no risk of loss) it is safe to remove the transaction log. There are some SQL commands to do it but I usually change the recovery mode to **Simple** then shrink the database then set the recovery mode back to **Full** if necessary. If you need more info then include the version of SQL you are using and how you perform backups and I'll see if I can elaborate bit more on your specific set-up.
SQL Server Log File Confusion
[ "", "sql", "sql-server", "flush", "" ]
I am using C# to write a method that returns the following information about a table: column names, column types, column sizes, foreign keys. Can someone point me in the right direction on how to accomplish this ?
To get the FK and Schema you should be able to use: ``` DA.FillSchema() DS.Table("Name").PrimaryKey ``` OR calling **sp\_fkey** using the method demonstrated below Code Snippet [from](http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/fad53def-d4d3-4a46-9fe2-f7d2f1251b42/) AND [Another Link](http://www.java2s.com/Code/CSharp/Database-ADO.net/GettableSchema.htm) ``` private void LoanSchema() { private List<String> tablesList = new List<String>(); private Dictionary<String, String> columnsDictionary = new Dictionary<String, String>(); string connectionString = "Integrated Security=SSPI;" + "Persist Security Info = False;Initial Catalog=Northwind;" + "Data Source = localhost"; SqlConnection connection = new SqlConnection(); connection.ConnectionString = connectionString; connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "exec sp_tables"; command.CommandType = CommandType.Text; SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) tablesList.Add(reader["TABLE_NAME"].ToString()); } reader.Close(); command.CommandText = "exec sp_columns @table_name = '" + tablesList[0] + "'"; command.CommandType = CommandType.Text; reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) columnsDictionary.Add(reader["COLUMN_NAME"].ToString(), reader["TYPE_NAME"].ToString()); } } ```
This really depends on how you communicate with your database. If you are using LinqToSQL or another similar ORM this would be pretty easy but if you want to get these values via a query I'd suggest you use the INFORMATION\_SCHEMA views as these are fast and easy to query. e.g. ``` select * from information_schema.columns where table_name = 'mytable' ```
ADO.Net : Get table definition from SQL server tables
[ "", "c#", "sql-server", "ado.net", "" ]
**Here is my situation:** I have an application that use a configuration file. The configuration file applies to all users of the system and all users can make change to the configuration. I decided to put the configuration file in "All Users\Application Data" folder. The problem is that the file is writable only by the user who created it. **Here is my temporary solution:** When creating the file, the application set its security options so that it can be written by all users of the system. However, [I think this is a hack](http://blogs.msdn.com/oldnewthing/archive/2004/11/22/267890.aspx) and I think I have to create a service that will manage access to the file. My application is written in C++ (MFC) and I'm not an expert with all the .Net stuff. So my first idea is to write a Windows C++ service with COM interfaces that will be called by the application. **My questions:** * Is my idea a good idea or someone knows a better way to do? * Is there any new more up to date way to do a service in Windows than plain C++ and COM? **EDIT:** I know it's easy to set write permission to all users. Back with Windows XP it was also easy to write files under "Program Files" and registry keys under "HKLM" with a limited user. But now, if you want an application to have the Vista logo certification, you must not write to these location (event if Virtual Stores can 'save' you). Maybe my final solution will be the "make it writable to all users" one, but my question really is : "Is my solution good or do you have another easier solution that does not rely hacking a behavior fixed by Microsoft". I'm really sorry to not have made it clear from the beginning. Thanks a lot, Nic
I wouldn't even bother with COM. Named pipes to your service work fine, too, and it's a lot easier to secure those with ACLs. The service will be so simple I wouldn't even bother with MFC or .NET, pure C++ should be fine. All the heavy lifting is done by your real app; the service just checks if the request piped in are reasonable. (ie. not too big etc.)
This is not the right approach. If you're putting the file in All Users\Application Data, then it should be writable by all users. When you create it, create it with write permissions for all users. Setting the creation permissions isn't that hard.
Windows service to control access to a file in "All Users\Application Data"
[ "", "c++", "windows", "mfc", "" ]
Basically I'm asking the same question as this guy: [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does not work (as the OP pointed out in his comments to their answers). I know that you can do this by using sys.path, but I would prefer a cleaner method. Example: ``` App __init__.py Package_A --__init__.py --Module_A.py Package_B --__init__.py --Module_B.py ``` How would I import Module\_A into Module\_B?
``` main.py setup.py app/ -> __init__.py package_a/ -> __init__.py module_a.py package_b/ -> __init__.py module_b.py ``` 1. You run `python main.py`. 2. `main.py` does: `import app.package_a.module_a` 3. `module_a.py` does `import app.package_b.module_b` Alternatively 2 or 3 could use: `from app.package_a import module_a` That will work as long as you have `app` in your PYTHONPATH. `main.py` could be anywhere then. So you write a `setup.py` to copy (install) the whole app package and subpackages to the target system's python folders, and `main.py` to target system's script folders.
If I'm [reading](http://www.python.org/dev/peps/pep-0328/) [correctly](http://docs.python.org/whatsnew/2.5.html), in Python 2.5 or higher: ``` from ..Module_B import Module_B ``` I thought I was well-versed in Python but I had no idea that was possible in version 2.5.
Python - Doing absolute imports from a subfolder
[ "", "python", "python-import", "" ]
I would like to dynamically add fields to an ASP.NET MVC form with JQuery. Example: ``` <script language="javascript" type="text/javascript"> var widgets; $(document).ready(function() { widgets = 0; AddWidget(); }); function AddWidget() { $('#widgets').append("<li><input type='text' name='widget" + widgets + "'/></li>"); widgets++; } </script> <ul id="widgets"> </ul> ``` This works, but I was going to manually iterate the form values in the controller: ``` [AcceptVerbs("Post")] public ActionResult AddWidget(FormCollection form) { foreach (string s in form) { string t = form[s]; } return RedirectToAction("ActionName"); } ``` But it occurred to me when I send the user back to the Get Action in the Controller I will have to set the FormData with the values entered and then iteratively add the widgets with <% scripting. What is the est way to do this in the current release (5 I believe)?
My solution could be something like this (pseudo-code): ``` <script language="javascript" type="text/javascript"> var widgets; $(document).ready(function() { widgets = 0; <% for each value in ViewData("WidgetValues") %> AddWidget(<%= value %>); <% next %> }); function AddWidget( value ) { $('#widgets').append("<li><input type='text' name='widget" + widgets + "'>" + value + "</input></li>"); widgets++; } </script> <ul id="widgets"> </ul> ``` And in the controller: ``` [AcceptVerbs("Post")] public ActionResult AddWidget(FormCollection form) { dim collValues as new Collection; foreach (string s in form) { string t = form[s]; collValues.add( t ) } ViewData("WidgetValues") = collValues; return RedirectToAction("ActionName"); } ``` You can work out the details later (sorry for mixing VB with C#, I'm a VB guy)
i might be missing the point here, but, do you need to actually post the data back to the controller via a form action? why not make an ajax call using jquery to post the data to the controller...or better yet a web service? send the data async and no need to rebuild the view with the data values sent in. This works fine if the values are being consumed and never used again, however, if you plan on persisting the data and surfacing it through a the view, your model should really support the data structure. maybe a `Dictionary<string, string>` on the model.
ASP.NET MVC & JQuery Dynamic Form Content
[ "", "c#", "jquery", "asp.net-mvc", "" ]
Not entirely sure how to phrase the question, because it's a "why doesn't this work?" type of query. I've reduced my particular issue down to this code: ``` public interface IFoo { } public class Foo : IFoo { } public class Bar<T> where T : IFoo { public Bar(T t) { } public Bar() : this(new Foo()) // cannot convert from 'Foo' to 'T' { } } ``` Now, the generic type `T` in the `Bar<T>` class *must* implement IFoo. So why does the compiler give me the error in the comment? Surely an instance of Foo is an IFoo, and can therefore be passed around as a representative of the generic type `T`? Is this a compiler limitation or am I missing something?
You could also have a Fiz that implements IFoo that is not related to Foo in any other way: ``` public interface IFoo { } public class Foo : IFoo { } public class Fiz : IFoo { } Foo foo = new Foo(); Fiz fiz = foo; // Not gonna compile. ``` What you want is probably more like: ``` public class Bar<T> where T : IFoo, new() { public Bar(T t) { } public Bar() : this(new T()) { } } ``` So you can have ``` Bar<Foo> barFoo = new Bar<Foo>(); Bar<Fiz> barFiz = new Bar<Fiz>(); ```
If you create a class Baz and then the generic type Bar baz = new Bar(), new Foo() as defined by your constructor overload, would not be of type T, in this case Baz.
Generic constraints and interface implementation/inheritance
[ "", "c#", "generics", "" ]
After reading this on the question [How do I uniquely identify computers visiting my web site?](https://stackoverflow.com/questions/216542/how-do-i-uniquely-identify-computers-visiting-my-web-site#216599) : > A possibility is using flash cookies: > > ``` > Ubiquitous availability (95 percent of visitors will probably have > ``` > > flash) > > ``` > You can store more data per cookie (up to 100 KB) > > Shared across browsers, so more likely to uniquely identify a machine > > Clearing the browser cookies does not remove the flash cookies. > ``` > > You'll need to build a small (hidden) > flash movie to read and write them. I tried to find if someone has already done something like this, so I wouldn´t have to reinvent the wheel. So far, no luck(maybe I don´t know the right term to search), except for the [code in the flash side](http://blog.circlecube.com/2008/04/tutorial/shared-object-utilizing-the-flash-cookie/) The use I have for this is to prevent a user to answer a quiz multiple times, but future uses maybe banning trolls. Does anyone knows a open source library that does this and allows me to access via javascript? Caveats: I don't know flash and I don't own a license. **Edit: You can do that using [evercookie](http://samy.pl/evercookie/). It's kind of evil, but works.**
To build on what *rmeador* said, and to help get you started, you are going to need to know how to use two classes in the FLEX3 API, [SharedObject](http://livedocs.adobe.com/flex/3/langref/) and [ExternalInterface](http://livedocs.adobe.com/flex/3/langref/). **SharedObject** will allow you to store and retrive data from a client computer and **ExternalInterface** will allow your actionscript to communicate with your javascript. Using shared object is simple. To put data onto a users machine just create a SharedObject and add properities to the sharedObject's data properity. ``` private var sharedObject : SharedObject = SharedObject.getLocal("myCookie"); sharedObject.data.DATA_FOR_THE_COOKIE = DATA; ``` Retriving data from the SharedObject is just as simple. Make sure the size of the SharedObject is greater than 0 (Make sure the SharedObject exists) and the just look up the properity names through the SharedObject's data properity. ``` if(sharedObject.size > 0) // access data from cookie with -> sharedObject.data.DATA_FROM_THE_COOKIE; ``` To pass the data stored in the SharedObject to your javascript you are going to need to use ExternalInterface. Lets say you have a javascript function to retrieve the variables ``` function retrieveVars( vars ){ // Do something with vars. } ``` To call this function from actionscript you will use ``` ExternalInterface.call("retrieveVars", DATA_ITEM_1, DATA_ITEM_2, ...); ``` Its that simple. *Please note that this technique will not work if the client's flash player has its storage settings set at 0, or if the client's browser does not have ActiveX or NPRuntime.*
I'm hesitant to answer your question, because it sounds like this is straying dangerously close to Evil... Also, it's doomed to failure. If you really want to prevent a user from answering a quiz multiple times, the best thing you can do is have them register a user account. If you want to prevent them from registering multiple user accounts, you can have them verify something through a credit card or snail mail, both of which are generally untenable solutions. In short, the internet is anonymous. Anyways, if you really want to go forward with this plan, you can build your application in Flex (a variant of Flash) fairly trivially. There's tons of documentation on the Adobe site. Some of it is rather sparse and annoying, particularly the collections API, but it'll be sufficient for your purposes. ActionScript (the programming language underlying both Flash and Flex) is very much like JavaScript and easy to learn. Flex has a free SDK (usually available in a small link from the page that tells you to get the expensive Flex Builder; Flex Builder is a primarily GUI tool, whereas you'll be writing straight code without an IDE with just the SDK), so a license shouldn't be a problem. The JavaScript to Flash bridge is also well documented.
Javascript bridge to Flash to store SO "cookies" within flash
[ "", "javascript", "flash", "cookies", "" ]
I've tried my best to be a purist with my usage of Javascript/Ajax techniques, ensuring that all Ajax-y behavior is an enhancement of base functionality, while the site is also fully functional when Javascript is disabled. However, this causes some problems. In some cases, a DOM node should only be visible when Javascript is enabled in the browser. In other cases, it should only be visible when disabled. Take for instance a submit button on a form that has a drop down with an onchange handler that auto-submits (using JQuery's form plugin): ``` <form method="post" action="."> <label for="id_state">State:</label> <select name="state" id="id_state" onchange="$(this.form).ajaxSubmit(ajax_submit_handler);"> <option value="AL">Alabama</option> <option value="AK">Alaska</option> </select> <input class="with_js_disabled" type="submit" value="OK" /> </form> ``` and the Javascript: ``` <script type="text/javascript"> $(document).ready(function() { $(".with_js_disabled").hide(); }); </script> ``` When Javascript is enabled, the submit button is not required (due to the onchange handler). However, JQuery's $(document).ready function (and the more direct document.onload) is only called after the page has been fully loaded and rendered - hence, the submit button is initially displayed and a "flash" occurs when the Javascript is executed and the node's display is set to "none". I've accepted this as the cost of doing business, and haven't found a way around it. But is there a technique I'm not aware of that will minimize the effect, or even outright eliminate it? **EDIT:** The `<noscript>` solution mentioned by many people below seems promising, but isn't working for me on Safari. However Prestaul's 2nd suggestion works beautifully: ``` <body> <script type="text/javascript"> document.body.className += ' has_js'; </script> <!-- the rest of your page --> </body> ``` This can then be styled using straight CSS: ``` body .js_enabled_only { display: none; } body .js_disabled_only { display: block; } body.has_js .js_enabled_only { display: block; } body.has_js .js_disabled_only { display: none; } ``` This second line is just for reference and can (and should) be removed to avoid circumstances where your element shouldn't be display:block. Likewise, you may need different variations on the third line for other display styles. But this solution is nice and clean, IMO, and in my tests entirely eliminates the flicker effect.
How about combining some of these solutions: ``` <style type="text/javascript"> .only-without-script { display: none; } </style> <noscript> <style type="text/javascript"> .only-with-script { display: none; } .only-without-script { display: block; } </style> </noscript> ``` or I prefer adding a class to the body (place your `<script>` tag at the top of the body and don't use the .ready event): ``` <head> <style type="text/javascript"> body.has-script .something-not-ajaxy { display: none; } input.ajaxy-submit { display: none; } body.has-script input.ajaxy-submit { display: inline; } </style> </head> <body> <script type="text/javascript"> document.body.className += ' has-script'; </script> <!-- the rest of your page --> </body> ```
For situations identical to yours, I usually put the submit button around a [`<noscript>`](http://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.3.1) tag. No one has suggested it, so I am not sure if it is considered bad practice around these parts, but it is what I use and it works for me. If you only want a node visible when Javascript is enabled, you could do in the head: ``` <noscript> <style type="text/css"> .js-enabled { display: none; } </style> </noscript> ``` And then give any Javascript-only elements a class of `js-enabled`.
How to eliminate post-render "flicker"?
[ "", "javascript", "jquery", "html", "ajax", "dom", "" ]
In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out? If you're unfamiliar with the rules, there's a description of semicolon insertion on the [Mozilla site](http://www.mozilla.org/js/language/js20-2000-07/rationale/syntax.html). Here's the key point: > If the first through the nth tokens of a JavaScript program form are grammatically valid but the first through the n+1st tokens are not and there is a line break between the nth tokens and the n+1st tokens, then the parser tries to parse the program again after inserting a virtual semicolon token between the nth and the n+1st tokens. That description may be incomplete, because it doesn't explain @Dreas's example. Anybody have a link to the complete rules, or see why the example gets a semicolon? (I tried it in JScript.NET.) [This stackoverflow question](https://stackoverflow.com/questions/42247/are-semicolons-needed-after-an-object-literal-assignment-in-javascript) is related, but only talks about a specific scenario.
Yes, you should use semicolons after every statement in JavaScript.
An ambiguous case that breaks in the absence of a semicolon: ``` // define a function var fn = function () { //... } // semicolon missing at this line // then execute some code inside a closure (function () { //... })(); ``` This will be interpreted as: ``` var fn = function () { //... }(function () { //... })(); ``` We end up passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. The second function will fail with a "... is not a function" error at runtime.
Do you recommend using semicolons after every statement in JavaScript?
[ "", "javascript", "" ]
When doing an ALTER TABLE statement in MySQL, the whole table is read-locked (allowing concurrent reads, but prohibiting concurrent writes) for the duration of the statement. If it's a big table, INSERT or UPDATE statements could be blocked for a looooong time. Is there a way to do a "hot alter", like adding a column in such a way that the table is still updatable throughout the process? Mostly I'm interested in a solution for MySQL but I'd be interested in other RDBMS if MySQL can't do it. To clarify, my purpose is simply to avoid downtime when a new feature that requires an extra table column is pushed to production. Any database schema *will* change over time, that's just a fact of life. I don't see why we should accept that these changes must inevitably result in downtime; that's just weak.
The only other option is to do manually what many RDBMS systems do anyway... - Create a new table You can then copy the contents of the old table over a chunk at a time. Whilst always being cautious of any INSERT/UPDATE/DELETE on the source table. (Could be managed by a trigger. Although this would cause a slow down, it's not a lock...) Once finished, change the name of the source table, then change the name of the new table. Preferably in a transaction. Once finished, recompile any stored procedures, etc that use that table. The execution plans will likely no longer be valid. **EDIT:** Some comments have been made about this limitation being a bit poor. So I thought I'd put a new perspective on it to show why it's how it is... * Adding a new field is like changing one field on every row. * Field Locks would be much harder than Row locks, never mind table locks. * You're actually changing the physical structure on the disk, every record moves. * This really is like an UPDATE on the Whole table, but with more impact...
Percona makes a tool called [pt-online-schema-change](https://www.percona.com/doc/percona-toolkit/2.1/pt-online-schema-change.html) that allows this to be done. It essentially makes a copy of the table and modifies the new table. To keep the new table in sync with the original it uses triggers to update. This allows the original table to be accessed while the new table is prepared in the background. This is similar to Dems suggested method above, but this does so in an automated fashion. Some of their tools have a learning curve, namely connecting to the database, but once you have that down, they are great tools to have. Ex: ``` pt-online-schema-change --alter "ADD COLUMN c1 INT" D=db,t=numbers_are_friends ```
ALTER TABLE without locking the table?
[ "", "sql", "mysql", "ddl", "alter-table", "" ]
I'm working on an application that allows users to add their own RSS feeds to a simple reader of sorts. Currently, I'm using `xml_domit_rss` as the parser but I'm unsure if it's actually validating the URL before parsing. From what I can gather online, it looks as if validating is separate from the parse, either by using a service <https://www.feedvalidator.org> or some other method such as `parse_url()`. Anyone have some insight into either how `xml_domit_rss` validates, or a method by which I can validate before sending the URL to the parser?
It's simple, You can do that using **[SyndicationFeed](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx)**. It supports [Atom 1.0](http://www.ietf.org/rfc/rfc4287.txt) and [RSS 2.0](http://validator.w3.org/feed/docs/rss2.html) versions. ``` try { SyndicationFeed fetchedItems = SyndicationFeed.Load(XmlReader.Create(feedUrl)); // Validation successful. } catch { // Validation failed. }; ```
You could validate the RSS with a RelaxNG schema. Schemas for all the different feed formats should be available online...
Validating an RSS feed
[ "", "php", "xml", "rss", "feed", "validation", "" ]
In [this blog article](http://abstracthack.wordpress.com/2007/09/05/multi-threaded-map-for-python/) they use the construct: ``` @measured def some_func(): #... # Presumably outputs something like "some_func() is finished in 121.333 s" somewhere ``` This `@measured` directive doesn't seem to work with raw python. What is it? UPDATE: I see from Triptych that `@something` is valid, but is where can I find `@measured`, is it in a library somewhere, or is the author of this blog using something from his own private code base?
`@measured` decorates the some\_func() function, using a function or class named `measured`. The `@` is the decorator syntax, `measured` is the decorator function name. Decorators can be a bit hard to understand, but they are basically used to either wrap code around a function, or inject code into one. For example the measured function (used as a decorator) is probably implemented like this... ``` import time def measured(orig_function): # When you decorate a function, the decorator func is called # with the original function as the first argument. # You return a new, modified function. This returned function # is what the to-be-decorated function becomes. print "INFO: This from the decorator function" print "INFO: I am about to decorate %s" % (orig_function) # This is what some_func will become: def newfunc(*args, **kwargs): print "INFO: This is the decorated function being called" start = time.time() # Execute the old function, passing arguments orig_func_return = orig_function(*args, **kwargs) end = time.time() print "Function took %s seconds to execute" % (end - start) return orig_func_return # return the output of the original function # Return the modified function, which.. return newfunc @measured def some_func(arg1): print "This is my original function! Argument was %s" % arg1 # We call the now decorated function.. some_func(123) #.. and we should get (minus the INFO messages): This is my original function! Argument was 123 # Function took 7.86781311035e-06 to execute ``` The decorator syntax is just a shorter and neater way of doing the following: ``` def some_func(): print "This is my original function!" some_func = measured(some_func) ``` There are some decorators included with Python, for example [`staticmethod`](http://docs.python.org/library/functions.html#staticmethod) - but `measured` is not one of them: ``` >>> type(measured) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'measured' is not defined ``` Check the projects `import` statements to see where the function or class is coming from. If it uses `from blah import *` you'll need to check all of those files (which is why `import *` is discouraged), or you could just do something like `grep -R def measured *`
Yes it's real. It's a function decorator. Function decorators in Python are functions that take a function as it's single argument, and return a new function in it's place. `@classmethod` and `@staticmethod` are two built in function decorators. [Read more »](http://www.python.org/dev/peps/pep-0318/)
Is @measured a standard decorator? What library is it in?
[ "", "python", "decorator", "" ]
What's wrong with this query: ``` INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1; ``` It works without the `WHERE` clause. I've seemed to have forgot my SQL.
MySQL [INSERT Syntax](http://dev.mysql.com/doc/refman/5.5/en/insert.html) does not support the WHERE clause so your query as it stands will fail. Assuming your `id` column is unique or primary key: If you're trying to insert a new row with ID 1 you should be using: ``` INSERT INTO Users(id, weight, desiredWeight) VALUES(1, 160, 145); ``` If you're trying to change the weight/desiredWeight values for an existing row with ID 1 you should be using: ``` UPDATE Users SET weight = 160, desiredWeight = 145 WHERE id = 1; ``` If you want you can also use INSERT .. ON DUPLICATE KEY syntax like so: ``` INSERT INTO Users (id, weight, desiredWeight) VALUES(1, 160, 145) ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145 ``` OR even like so: ``` INSERT INTO Users SET id=1, weight=160, desiredWeight=145 ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145 ``` It's also important to note that if your `id` column is an autoincrement column then you might as well omit it from your INSERT all together and let mysql increment it as normal.
You can't combine a WHERE clause with a VALUES clause. You have two options as far as I am aware- 1. INSERT specifying values ``` INSERT INTO Users(weight, desiredWeight) VALUES (160,145) ``` 2. INSERT using a SELECT statement ``` INSERT INTO Users(weight, desiredWeight) SELECT weight, desiredWeight FROM AnotherTable WHERE id = 1 ```
MySQL Insert query doesn't work with WHERE clause
[ "", "sql", "mysql", "" ]
Say I have an array of values: ``` string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" }; ``` Then I have a basic loop: ``` for (int i = 0; i <= 30; i++) { Console.WriteLine(i + " = " + text[i]) } ``` Obviously, this will cause an out of bounds exception, so what I want to do is when the counter reaches the upper bound of the array then go back to the start. So ``` 0 = val1 1 = val2 2 = val3 3 = val4 4 = val5 5 = val1 6 = val2 7 = val3 etc.. ```
You could use the modulus operator: ``` Console.WriteLine(i + " = " + text[i % 5]) ```
Take the modulus of the array length: ``` for (int i = 0; i < 30; ++i) { Console.WriteLine(i + " = " + text[i % text.Length]); } ```
Looping through an array without throwing exception
[ "", "c#", "arrays", "loops", "" ]
I have a Linq to SQL query that was working just fine with SQL Server 2005 but, I have to deploy the web app with a SQL Server 2000 and, when executing that query, I get his error: "System.Data.SqlClient.SqlException: The column prefix 't0' does not match with a table name or alias name used in the query." I have more queries but it doesn't seems to have problems with those. Now, this is the query: ``` from warningNotices in DBContext_Analyze.FARs where warningNotices.FAR_Area_ID == filter.WarningAreaID && warningNotices.FAR_Seq == filter.WarningSeq && warningNotices.FAR_Year == filter.WarningYear orderby warningNotices.FAR_Seq ascending select new Search_Result { FAR_Area_ID = warningNotices.FAR_Area_ID, FAR_Seq = warningNotices.FAR_Seq, FAR_Year = warningNotices.FAR_Year, DateTime_Entered = (DateTime)warningNotices.DateTime_Entered == null ? DateTime.MaxValue : (DateTime)warningNotices.DateTime_Entered, Time_Entered = warningNotices.Time_Entered, OrigDept = warningNotices.OrigDept, Part_No = warningNotices.Part_No, DateTime_Analyzed = (DateTime)warningNotices.DateTime_Analyzed == null ? DateTime.MaxValue : (DateTime)warningNotices.DateTime_Analyzed, Analyzed_By = warningNotices.Analyzed_By, MDR_Required = (Char)warningNotices.MDR_Required == null ? Char.MinValue : (Char)warningNotices.MDR_Required, Resp_Dept = (from FARSympt in DBContext_Analyze.FAR_Symptoms where FARSympt.FAR_Area_ID == warningNotices.FAR_Area_ID && FARSympt.FAR_Year == warningNotices.FAR_Year && FARSympt.FAR_Seq == warningNotices.FAR_Seq select new { FARSympt.Resp_Dept}).FirstOrDefault().Resp_Dept, Sympt_Desc = (from SymptomsCatalog in DBContext_Analyze.Symptoms where SymptomsCatalog.symptom_ID == filter.Status_ID select new { SymptomsCatalog.Sympt_Desc }).FirstOrDefault().Sympt_Desc, Status_ID = warningNotices.Status.HasValue ? warningNotices.Status.Value : 0 }; ``` Previously I had a "Distinc" in the subquery for the Resp\_Dept field, but I removed it. Any ideas? Thanks in advance for your comments =) --- This is query I get from the SQL Server profiler: ``` exec sp_executesql N'SELECT [t0].[FAR_Seq], [t0].[FAR_Year], (CASE WHEN ([t0].[DateTime_Entered]) IS NULL THEN @p3 ELSE [t0].[DateTime_Entered] END) AS [DateTime_Entered], [t0].[Time_Entered], [t0].[OrigDept], [t0].[Part_No], (CASE WHEN ([t0].[DateTime_Analyzed]) IS NULL THEN @p4 ELSE [t0].[DateTime_Analyzed] END) AS [DateTime_Analyzed], [t0].[Analyzed_By], (CASE WHEN (UNICODE([t0].[MDR_Required])) IS NULL THEN @p5 ELSE CONVERT(NChar(1),[t0].[MDR_Required]) END) AS [MDR_Required], ( SELECT [t2].[Resp_Dept] FROM ( **SELECT TOP (1)** [t1].[Resp_Dept] FROM [dbo].[FAR_Symptoms] AS [t1] WHERE (UNICODE([t1].[FAR_Area_ID]) = UNICODE([t0].[FAR_Area_ID])) AND ([t1].[FAR_Year] = [t0].[FAR_Year]) AND ([t1].[FAR_Seq] = [t0].[FAR_Seq]) ) AS [t2] ) AS [Resp_Dept], ( SELECT [t4].[Sympt_Desc] FROM ( **SELECT TOP (1)** [t3].[Sympt_Desc] FROM [dbo].[Symptoms] AS [t3] WHERE [t3].[symptom_ID] = @p6 ) AS [t4] ) AS [Sympt_Desc], [t0].[FAR_Area_ID], (CASE WHEN [t0].[Status] IS NOT NULL THEN [t0].[Status] ELSE @p7 END) AS [Status_ID] FROM [dbo].[FARs] AS [t0] WHERE (UNICODE([t0].[FAR_Area_ID]) = @p0) AND ([t0].[FAR_Seq] = @p1) AND ([t0].[FAR_Year] = @p2) ORDER BY [t0].[FAR_Seq]',N'@p0 int,@p1 int,@p2 varchar(2),@p3 datetime,@p4 datetime,@p5 nchar(1),@p6 int,@p7 int',@p0=76,@p1=7204,@p2='08',@p3=''9999-12-31 23:59:59:997'',@p4=''9999-12-31 23:59:59:997'',@p5=N' ',@p6=0,@p7=0 ``` The only think that I see there that may not in SQL Server 2000 is the '()' in the "Select top..." but I'm not sure if that is what is causing the problem and, also, I don't know how that could be fixed =S Thanks again =)
after several testing and review the DB, I found that the problem was a **legacy table** I was working on: that table has **"text" type fields**. Also, I had to **remove** some "**Distinct**" instructions in a nested query I had. I found [this](http://msdn.microsoft.com/en-us/library/bb399342.aspx) and, after review that, I found that I have to change my queries and that the "Distinct" instruction does not work correctly. As a side note, let me say that the nested queries can also generate unexpected behavior. So, the real lesson here is that if you **need to deploy** this against a **SQL Server 2000**, set an instance of the server and test against it!!! XD Thanks a lot of your help =)
My Linq statement worked on SQL2008 but broke with the exact same error message on SQL2000. Had a very similar Linq query that worked on both, the only real difference was that before calling .ToList() I called the .OrderBy() clause. Ex: var query = from t1 in table1 ... ...; list = query.OrderBy(o => o.Field).ToList() Tried the same OrderBy clause on the broken Linq query and it worked! Has to be a bug?
LINQ Incompatibility Issue with SQL Server 2000
[ "", "sql", "linq", "sql-server-2000", "" ]
I would like to call `FindLast` on a collection which implements `IEnumerable`, but `FindLast` is only available for `List`. What is the best solution?
The equivalent to: ``` var last = list.FindLast(predicate); ``` is ``` var last = sequence.Where(predicate).LastOrDefault(); ``` (The latter will have to check *all* items in the sequence, however...) Effectively the "Where()" is the Find part, and the "Last()" is the Last part of "FindLast" respectively. Similarly, `FindFirst(predicate)` would be map to `sequence.Where(predicate).FirstOrDefault()` and `FindAll(predicate)` would be `sequence.Where(predicate)`.
How about with LINQ-to-Objects: ``` var item = data.LastOrDefault(x=>x.Whatever == "abc"); // etc ``` If you only have C# 2, you can use a utility method instead: ``` using System; using System.Collections.Generic; static class Program { static void Main() { int[] data = { 1, 2, 3, 4, 5, 6 }; int lastOdd = SequenceUtil.Last<int>( data, delegate(int i) { return (i % 2) == 1; }); } } static class SequenceUtil { public static T Last<T>(IEnumerable<T> data, Predicate<T> predicate) { T last = default(T); foreach (T item in data) { if (predicate(item)) last = item; } return last; } } ```
FindLast on IEnumerable
[ "", "c#", "ienumerable", "ilist", "" ]
With valid HTML the following finds the object as expected in all browsers but gets NULL in IE (6 & 7). ``` $(document).ready(function() { alert( '$(.rollover):\n' + $('.rollover')); }); ``` I've tried by switching it to something simpler like $('a') but I always get NULL in IE. **Update:** After running the page through the W3C validator (and ignoring what my Firefox validator plugin was telling me) it appears there are actually quite a lot of validation errors (even with HTML 4 Transitional defined), which I can't easily fix, so my guess is that is the cause of my issues. As trying on a very simple document works as expected in IE.
If you're having $ conflicts there are many way to avoid this as documented [here](http://docs.jquery.com/Using_jQuery_with_Other_Libraries).
It seems that it is AjaxCFC's JavaScript includes that are causing a problem, more specifically the ajaxCFC util.js which seems to define it's own $. Moving those includes before that of the JQuery lib fixed the above issues I was having.
Why isn't jQuery $('.classname') working in IE?
[ "", "javascript", "jquery", "" ]
I've written the following routine to manually traverse through a directory and calculate its size in C#/.NET: ``` protected static float CalculateFolderSize(string folder) { float folderSize = 0.0f; try { //Checks if the path is valid or not if (!Directory.Exists(folder)) return folderSize; else { try { foreach (string file in Directory.GetFiles(folder)) { if (File.Exists(file)) { FileInfo finfo = new FileInfo(file); folderSize += finfo.Length; } } foreach (string dir in Directory.GetDirectories(folder)) folderSize += CalculateFolderSize(dir); } catch (NotSupportedException e) { Console.WriteLine("Unable to calculate folder size: {0}", e.Message); } } } catch (UnauthorizedAccessException e) { Console.WriteLine("Unable to calculate folder size: {0}", e.Message); } return folderSize; } ``` I have an application which is running this routine repeatedly for a large number of folders. I'm wondering if there's a more efficient way to calculate the size of a folder with .NET? I didn't see anything specific in the framework. Should I be using P/Invoke and a Win32 API? What's the most efficient way of calculating the size of a folder in .NET?
I do not believe there is a Win32 API to calculate the space consumed by a directory, although I stand to be corrected on this. If there were then I would assume Explorer would use it. If you get the Properties of a large directory in Explorer, the time it takes to give you the folder size is proportional to the number of files/sub-directories it contains. Your routine seems fairly neat & simple. Bear in mind that you are calculating the sum of the file lengths, not the actual space consumed on the disk. Space consumed by wasted space at the end of clusters, file streams etc, are being ignored.
No, this looks like the [recommended way](https://msdn.microsoft.com/en-us/library/system.io.directory(v=vs.100).aspx) to calculate directory size, the relevent method included below: ``` public static long DirSize(DirectoryInfo d) { long size = 0; // Add file sizes. FileInfo[] fis = d.GetFiles(); foreach (FileInfo fi in fis) { size += fi.Length; } // Add subdirectory sizes. DirectoryInfo[] dis = d.GetDirectories(); foreach (DirectoryInfo di in dis) { size += DirSize(di); } return size; } ``` You would call with the root as: ``` Console.WriteLine("The size is {0} bytes.", DirSize(new DirectoryInfo(targetFolder)); ``` ...where `targetFolder` is the folder-size to calculate.
What's the best way to calculate the size of a directory in .NET?
[ "", "c#", ".net", "windows", "" ]
How can I create a Java/Swing text component that is both styled and has a custom font? I want to highlight a small portion of the text in red, but at the same time use a custom (embedded via `Font.createFont`) font. JLabel accepts HTML text, which allows me to highlight a portion of the text, but it ignores font settings when rendering HTML. Other text components such as JTextArea will use the custom font, but they won't render HTML. What's the easiest way to do both? Here's an example of using JTextPane unsuccessfully: ``` JTextPane textPane = new JTextPane(); textPane.setFont(myCustomFont); textPane.setText(text); MutableAttributeSet attributes = new SimpleAttributeSet(); StyleConstants.setForeground(attributes, Color.RED); textPane.getStyledDocument().setCharacterAttributes( text.indexOf(toHighlight), toHighlight.length(), attributes, true ); ``` This successfully displays the text with the "toHighlight" portion highlighted in red, but it doesn't use myCustomFont. Note that I could set a String font with `StyleConstants.setFontFamily()`, but not a custom font.
OK, I see the problem better now. After checking some Swing source code, it is clear you cannot use the `DefaultStyledDocument` and have it use a physical font (one you created yourself with `createFont`) out of the box. However, what I think you could do is implement your own `StyleContext` this way: ``` public class MyStyleContext extends javax.swing.text.StyleContext { @Override public Font getFont(AttributeSet attr) { Font font = attr.getAttribute("MyFont"); if (font != null) return font; else return super.getFont(attr); } } ``` Then you have to: 1. create a `DefaultStyledDocument` with a `new MyStyleContext()` 2. "attach" it to the `JTextPane` 3. call `attributes.addAttribute("MyFont", myCustomFont);` in your snippet above I did not try it but I think it should work or it might be a good path to investigate.
jfpoilpret's solution worked perfectly! For posterity's sake, here's a working code snippet: ``` JTextPane textPane = new JTextPane(); textPane.setStyledDocument(new DefaultStyledDocument(new StyleContext() { @Override public Font getFont(AttributeSet attr) { return myCustomFont; } })); textPane.setText(text); MutableAttributeSet attributes = new SimpleAttributeSet(); StyleConstants.setForeground(attributes, Color.RED); textPane.getStyledDocument().setCharacterAttributes( text.indexOf(toHighlight), toHighlight.length(), attributes, true ); ``` Thanks, jfpoilpret!
How can I create a Java/Swing text component that is both styled and has a custom font?
[ "", "java", "swing", "fonts", "" ]
I am not sure what the problem is but I keep receiving this error when I try to use a while statement in my code. > Invalid token 'while' in class, > struct, or interface member > declaration I want to use a while loop to have something continuously update while a statement is true. The rest of my code is rather long but whenever I type in the syntax: ``` while(a<b) { //do whatever i want it to do here } ``` It gives me that compiler error right off the bat. Not quite sure what the problem is. I am doing this in a C# windows application under the Form1.cs file with all the other event handlers (for buttons and such). Thanks! --- I was unaware that loops had to be placed within a method (fairly new to c#), but I tried it and no errors were returned. Thanks for your help everybody! Previously, I just had the loop within the main class of the program.
Based on the error, it sounds like the compiler thinks this code is typed directly in the body of a class/struct/interface declaration. Statements while/if/for/etc ... must appear with in a method. Try moving this code into a method to fix the problem. If it's in a method, you likely have a mismatched brace problem.
There's nothing wrong with the while, it's something above it that's the problem. Check for mismatched braces and semicolons in a comment or something like that.
Invalid token 'while' in class, struct, or interface member declaration in very simple code
[ "", "c#", "loops", "while-loop", "" ]
I need to write a simple command-line application in Java. It would be nice to use a library that takes care of parsing commands and takes care of things like flags and optional/mandatory parameters... **UPDATE** Something that has built-in TAB completion would be particularly great.
I've used the [Apache Commons CLI library](http://commons.apache.org/cli/) for command-line argument parsing. It's fairly easy to use and has [reasonably good documentation](http://commons.apache.org/cli/introduction.html). Which library you choose probably comes down to which style of options you prefer ("--gnu-style" or "-javac-style").
[JLine](https://github.com/jline/jline3/) looks helpful. > JLine is a Java library for handling console input. It is similar in functionality to BSD editline and GNU readline. People familiar with the readline/editline capabilities for modern shells (such as bash and tcsh) will find most of the command editing features of JLine to be familiar. And it does list tab completion in its [features](https://github.com/jline/jline3/wiki).
Are there good Java libraries that facilitate building command-line applications?
[ "", "java", "shell", "command-line", "interactive", "" ]
Alright, so I'm trying out C++ for the first time, as it looks like I'll have to use it for an upcoming course in college. I have a couple years of programming under my belt, but not much in the non-garbage-collected world. I have a class, a Node for use in a doubly linked list. So basically it has a value and two pointers to other Nodes. The main constructor looks like `Node(const std::string & val, Node * prev, Node * next)`. The exercise includes a copy constructor that does a shallow copy of another Node, with a comment above it that says to change it to make a deep copy. Here is what I thought that meant: ``` Node(const Node & other) : value(other.value) { prev = new Node(other.prev->value, other.prev->prev, other.prev->next); next = new Node(other.next->value, other.next->prev, other.next->next); } ``` This seems to accomplish the goal of making it so that changing the copied Node doesn't affect the new Node. However, when I do it this way, I am allocating new stuff on the heap. This worries me, because I think it means that I should also be deleting it in the Node's destructor. But this is now inconsistent with the other constructor, where pointers to the Nodes are just passed in, already pointing to something. I can't rightly go `delete`ing `next` and `prev` in the destructor with that going on, right? I'm really confused, guidance appreciated! EDIT: Here is the code (before my above change to it), as requested: ``` #include <string> //! Node implements a doubly-linked list node class Node { friend class LinkedList; //!< LinkedList can access private members of Node public: //! Constructor Node(const std::string & v, Node * p, Node * n) : value(v), prev(p), next(n) { } //! Change to deep copy Node(const Node & other) : value(other.value), prev(other.prev), next(other.next) { } //! Read-only public methods for use by clients of the LinkedList class const std::string & GetValue() const { return value; } Node * GetPrevious()const { return prev; } Node * GetNext()const { return next; } //! Change to deep copy Node & operator=(const Node & other) { if(this!=&other) { value=other.value; prev=other.prev; next=other.next; } return *this; } private: std::string value; //!< value stored in the node Node * prev; //!< pointer to previous node in the list Node * next; //!< pointer to next node in the list }; ```
First of all, I'm not really sure how the objective of the exercise should be understood. How deep should the copy be? In a solution like yours, `this->next->next` and `other.next->next` would be still the same thing. Should this object also be duplicated? And the rest of the list? Where does it end? One could of course deep-copy the whole list, but this would be a quite unexpected behavior of a copy constructor of a single node, I think. Is maybe the `value` member variable a pointer, that is supposed to be deep copied? That would make much more sense for me. But back to your interpretation: ``` Node a(...); // ... more code that adds a whole list to a Node b(a); ``` There are two problems with your implementation. For one `b->next->prev` points to `a`, while I suspect it should point back to `b`. Secondly you need to think about the corner cases, where `a` might be the first or last node in the list. And to your main question: you are of course right, somewhere the newly created objects need to be `delete`d again. No matter if you just copy the `prev` and `next` nodes or the whole list, I would say the user of that copy is responsible to delete all the copied nodes again. I assume with a normal, not-copied list, the user of that list would walk through all the nodes and delete them manually one after another, once he's done with the list. He wouldn't not assume the destructor of one node to delete the whole list. And the same goes for copies, they should behave the same. The user of the copied stuff should delete all the copies. (In practice you would probably have a `list` class, that does all that node management for you). But again, if the copy constructor of the node copies the whole list, or even just several of it's nodes, this would be very unexpected and all the time people would forget to clean up all these copies. But that's not your node class' fault, but the exercise requirements'.
Usually "deep copy" involves traversing the data structure and copying the entire thing. In your case, given a Node, make a complete copy of the list.
Newbie question about manual memory management and deep copying
[ "", "c++", "memory-management", "deep-copy", "" ]
Im runing mySQL in a server where i need to drop tons of databases (after some testing with the server). All databases that i need to drop have the same prefix "Whatever\_". After the prefix, the names are random. So you have your Whatever\_something, Whatever\_232, Whatever\_blabla, .... , Whatever\_imthelast. I will be doing this job quite some times so i was wondering what would be the best way to do this? **EDIT:** I can use any kind of language or plug in for mysql... so we CAN do this in some ways. Right now, i asked the guy that is generating the databases to give me a .txt with each name in a line... so im coding a quick php that will take a file and delete all the databases in it, later i will try the % answer(if it works, it takes the correct answer for sure its the easier way). Anyway i would like to do this the easier way coz i wont be able to support this code(other guys will and you know... ) **edit 2:** The use of a wildcard didnt work: #1008 - Can't drop database 'whatever\_%'; database doesn't exist
The basic idea is to run "show tables" in your database, and use the results from that to select the tables you want. I don't think MySQL lets you do anything with the resultset from "show tables", but I'm probably wrong. Here's a quick-and-dirty solution using the shell: ``` mysql -u your_user -D your_database_name -e "show tables" -s | egrep "^Whatever_" | xargs -I "@@" echo mysql -u your_user -D your_database_name -e "DROP TABLE @@" ``` That will print out all the shell commands to drop the tables beginning with "Whatever\_". If you want it to actually execute those commands, remove the word "echo". **EDIT**: I forgot to explain the above! I don't know how familiar you are with shell scripting, but here goes: ``` mysql -u your_user -D your_database_name -e "show tables" -s ``` prints out a list of all your tables, with the header "Tables\_in\_your\_database\_name". The output from that is piped (the | symbol means "piped", as in passed-on) through the next command: ``` egrep "^Whatever_" ``` searches for any lines that begin (that ^ symbols means "beings with") the word "Whatever\_" and only prints those. Finally, we pipe that list of "Whatever\_\*" tables through the command: ``` xargs -I "@@" echo mysql -u your_user -D your_database_name -e "DROP TABLE @@" ``` which takes each line in the list of table names, and inserts it instead of the "@@" in the command ``` echo mysql -u your_user -D your_database_name -e "DROP TABLE @@" ``` So if you had a bunch of tables named "Whatever\_1", "Whatever\_2", "Whatever\_3", the generated commands would be: ``` echo mysql -u your_user -D your_database_name -e "DROP TABLE Whatever_1" echo mysql -u your_user -D your_database_name -e "DROP TABLE Whatever_2" echo mysql -u your_user -D your_database_name -e "DROP TABLE Whatever_3" ``` Which would output the following: ``` mysql -u your_user -D your_database_name -e "DROP TABLE Whatever_1" mysql -u your_user -D your_database_name -e "DROP TABLE Whatever_2" mysql -u your_user -D your_database_name -e "DROP TABLE Whatever_3" ``` I hope that was enough detail, and that I'm not just beating anyone over the head with too much information. Good luck, and be careful when using the "DROP TABLE" command!
The principle of the answer by **scraimer** is correct, but since the question was about dropping a database not a table in a database, the correct command should be: ``` mysql -u your_username -p'your password' -e 'show databases' | grep Whatever_* | xargs -I "@@" mysql -u your_username -p'your password' -e "DROP database \`@@\`" ``` For explanations of the command, look at **scraimer**'s explanation. The last bit... \`@@\` we have our resulting database name quoted in bacticks(`) in case our database name has special characters like `-` Cheers
Drop MySQL databases matching some wildcard?
[ "", "mysql", "sql", "" ]
Using a DB with C++ is a real mess and it was refreshing when I moved to Java to be able to use a unified system to abstract the whole layer away (aka Hibernate). There are a couple of C++ abstract layers for DB's out there but they are usually vendor specific and only a thin layer that wraps the real C API. Has anybody come across something more like hibernate for C++ or know of a group or open source project that is looking at this problem domain.
I don't know of any C++ library like Hibernate, but certainly there are non-vendor specific libs: [SOCI](http://sourceforge.net/projects/soci/) and [DTL](http://dtemplatelib.sourceforge.net/)
I feel your pain. You'll quickly be using separate libraries for database access, XML processing, threading, and everything else applications commonly need. For this reason I often use Qt, which provides most common functionality often need in programs (database access, XML processing, threading, GUI widgets, etc.). Their SQL classes are pretty decent and work with many databases. But it does not abstract SQL away like many object-relation mappers.
Hibernate like layer for C++
[ "", "c++", "hibernate", "persistence", "freeze-thaw", "" ]
I feel like I am always reinventing the wheel for each application when it needs to load/save general settings to an xml file. What is the best way to manage basic application settings that the user can adjust and need to be saved/restored?
I like the use of [custom configuration sections](http://www.renevo.com/blogs/dotnet/archive/2009/01/08/custom-configuration-sections-in-application-config-files.aspx) in .config files coupled with [loading external .config](http://www.renevo.com/blogs/dotnet/archive/2008/01/31/loading-config-files-from-non-default-locations.aspx) files instead of the standard app.config.
Are you using Visual Studio? There's a built-in settings manager and I find it works well for most situations. Just don't forget to call `Settings.Save()` before the application quits.
C# Settings Management
[ "", "c#", "xml", "settings", "" ]
I am writing an application in Java using Swing. I am trying to implement functionality to save and load simulation states for at simulation i am running. The entire simulation is kept as an object, disconnected from Swing. I am trying to serialize my Simulation class with this code: ``` public void saveSimulationState(String simulationFile) { try { Serializable object = this.sm; ObjectOutputStream objstream = new ObjectOutputStream(new FileOutputStream(simulationFile)); objstream.writeObject(object); objstream.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } ``` But i get the following error (it is huge). ``` Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at java.io.ObjectStreamClass.processQueue(ObjectStreamClass.java:2234) at java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:266) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1106) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.ArrayList.writeObject(ArrayList.java:570) at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.ArrayList.writeObject(ArrayList.java:570) at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.ArrayList.writeObject(ArrayList.java:570) at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.ArrayList.writeObject(ArrayList.java:570) at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.ArrayList.writeObject(ArrayList.java:570) at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.ArrayList.writeObject(ArrayList.java:570) at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.ArrayList.writeObject(ArrayList.java:570) at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.ArrayList.writeObject(ArrayList.java:570) at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) ``` Can anybody tell me what is causing this exception?
Interesting post from Chen: [When debugging a stack overflow, you want to focus on the repeating recursive part](https://web.archive.org/web/20140424233104/http://blogs.msdn.com/b/oldnewthing/archive/2009/01/07/9286576.aspx) In your case: ``` at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.ArrayList.writeObject(ArrayList.java:570) at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) ``` > If you go hunting through your defect tracking database trying to see whether this is a known issue or not, a search for the top functions on the stack is unlikely to find anything interesting. > > That's because stack overflows tend to happen at a random point in the recursion; each stack overflow looks superficially different from every other one even if they are the same stack overflow. > > Once you get past the initial turmoil, the stack trace settles down into a nice repeating pattern consisting of the same x functions over and over again. > > Identifying the start of the repeating pattern isn't important, because the starting point will be different for each crash, in the same way that the precise note which exceeds your singing range varies from crash to crash. > > Once you've identified the repeating part, pick a function from it that is somewhat unusual and search for it in [your defect database](https://www.google.com/search?q=java.lang.StackOverflowError%20%20ObjectOutputStream%20defaultWriteFields&gws_rd=ssl). [For example](https://coderanch.com/t/277328/java/java-lang-StackOverflowError-Serialization), a default `ArrayList` serialization. Here your [`GrahPanel`](https://web.archive.org/web/20140827034420/http://code.google.com:80/p/sensor-protocol-simulation/source/browse/trunk/src/protokolsimulering/view/GraphPanel.java?r=20) refers a [`Simulation`](https://web.archive.org/web/20170105135156/https://code.google.com/archive/p/sensor-protocol-simulation/source) which refers to [`Graph`](https://web.archive.org/web/20170105135156/https://code.google.com/archive/p/sensor-protocol-simulation/source), with potentially long `ArrayList` of Sensor and Edge... > Java serialization keeps a record of every object written to a stream. > If the same object is encountered a second time, only a reference to it is written to the stream, and not a second copy of the object; so circular references aren't the problem here. > > But serialization is vulnerable to stack overflow for certain kinds of structures; for example, **a long linked list with no special `writeObject()` methods will be serialized by recursively writing each link. > If you've got a 100,000 links, you're going to try to use 100,000 stack frames, and quite likely fail with a `StackOverflowError`**. > > It's possible to define a `writeObject()` method for such a list class that, when the first link is serialized, simply walks the list and serializes each link iteratively; this will prevent the default recursive mechanism from being used.
You should consider reimplementing the `writeObject` / `readObject` methods of your Simulation class in order to serialize only the relevant data (and not the entire contained object structure by default) or tagging transient your not to be serialized objects. You can also use the `Externalizable` interface if needed. BTW, you may want to read this [interesting article](http://java.sun.com/developer/technicalArticles/Programming/serialization/) to begin with.
StackOverflowError when serializing an object in Java
[ "", "java", "swing", "serialization", "stack-overflow", "" ]
I have a series of interlinked web pages, and I want to restrict access to these pages by asking the user to provide a login and password. However, my hosting account currently does not provide any facility for server side scripting - is there any way I can accomplish this objective using only client side scripts? I was wondering how the following program works - <http://www.myzips.com/software/HTML-Password.phtml> Clarification: Thanks for your inputs. However, if I am configuring the web server, then is there a possibility of the user entering an username and password?
There is no way to create a secure clientside script. If the user has access to it, it's insecure. If your host is running apache you can secure folders using .htaccess, on IIS you can do the same through directory security.
Below is a **working solution to this problem** that uses encryption, which I implemented myself. A few users here have suggested using an encryption-based approach to client-side password protection. I needed this functionality too, so I implemented it myself. The password is hashed using PBKDF2 and then used to encrypt the page with AES256. The tool is hosted here: <https://www.maxlaumeister.com/pagecrypt/> with source code available here: <https://github.com/MaxLaumeister/pagecrypt> --- Description of the project, from the project page: > **PageCrypt - Password Protect HTML** > > This tool lets you securely password-protect an HTML file. Unlike other password-protection tools, this tool: > > 1. Has no server-side components (this tool and its password-protected pages run entirely in javascript). > 2. Uses strong encryption, so the password-protection cannot be bypassed. > > All you need to do is choose an HTML file and a password, and your page will be password-protected.
Is there a way to password protect HTML pages without using a server side language?
[ "", "javascript", "html", "client", "passwords", "" ]
I am writing my form validation class using CodeIgniter. Is there any way so that I can get error messages in name value pair? For example, in a sample form there are four fields: `user_name`, `password`, `password_conf`, and `timezone`. Among them `user_name` and `password` validation has failed after executing the following: ``` $result = $this->form_validation->run(); ``` If the above function returns false, I want to get the errors in name value pairs like the following: ``` Array { 'user_name' => 'user name is required', 'password' => 'passord is required' } ``` I truly want to form a JSON, which I can pass back to the AJAX call. I have a (dirty) solution: I can call validation methods one by one like the following: ``` $this->form_validation->required($user_name); $this->form_validation->required($password); ``` Is there any other way, to get all the error messages **at once** in name value pair? **EDIT**: I was suggested to do validation with jQuery from one of the answers: **jQuery will help in client side validation, but what about server side, there I am using CodeIgniter validation.** I have designed it so that: 1. I post all the values using AJAX. 2. Validate in server side (PHP). 3. Perform the desired operation if the inputs are valid; else return error to the user.
I have found one way myself by looking into the CodeIgniter code: I have extended the library CI\_Form\_validation like: - ``` class MY_Form_validation extends CI_Form_validation { public function getErrorsArray() { return $this->_error_array; } } ``` I know, this is a hack, but will serve my need for the time. I hope CodeIginter team soon come up with an interface to access that array.
You can simply use, `$this->form_validation->error_array();` This is from the [class reference documentation](https://www.codeigniter.com/userguide3/libraries/form_validation.html#class-reference) of CodeIgniter.
CodeIgniter Form Validation - Get the Result as "array" Instead of "string"
[ "", "php", "codeigniter", "" ]
Does anyone know what advantages (memory/speed) there are by using a class generated by the XSD tool to explore a deserialized XML file as opposed to XPATH?
I'd say the advantage is that you get a strongly typed class which is more convenient to use, and also the constructor for the class will throw an exception if the XML data in the file is invalid for creating the object, so you get a minimal data validation for free.
If you don't want to write boilerplate code, and you need to check ANY values of your XML on the way through, you can't go wrong with the XSD.exe generated classes.
DeSerializing an XML file to a C# class
[ "", "c#", "xml", "xsd.exe", "" ]
I am having trouble with [FxCop warning CA1006](http://msdn.microsoft.com/en-us/library/ms182144.aspx "FxCop warning CA1006"), Microsoft.Design "DoNotNestGenericTypesInMemberSignatures". Specifically, I am designing a `ReportCollection<T>` class that inherits from `ReadOnlyCollection<Report<T>>`, and its `public` constructor takes an `IList<Report<T>>` as a parameter. The suggestion for fixing this warning is not very useful: > "To fix a violation of this rule, change the design to remove the nested type argument." There are two ways I can see so far to change the design as suggested: 1. Make the constructor `internal`. This doesn't work in my case. The constructor must be `public` because this collection class needs to be instantiable by code outside the assembly. 2. Make the constructor take a `Report<T>[]` instead of an `IList<Report<T>>`. This is sub-optimal because external code should have the flexibility of using dynamically-sized data structures like `List<T>` instead of fixed-size arrays. At this point, I have given up and suppressed this warning. Is there a better solution?
I agree, another good time to ignore this rule is when you need to say: ``` Func<IEnumerable<T>> ``` of course you could use the non-generic IEnumerable, but then any type can be used as long as it implements IEnumerable (non-generic). The purpose of generics (in part) is to restrict the types that are permisable to a given set of types. I think this rule is very stupid. only need it if you have multiple generic types nested. one layer of nesting is more than safe. BTW, I think a lot of the LINQ Functions nest generic types as well, so if MS does it, we can too :)
I would take FxCop's warnings as if they were suggestions from an extremely anal-retentive coworker. It's perfectly ok to ignore (suppress) some of the things it suggests.
Are there any good workarounds for FxCop warning CA1006?
[ "", "c#", ".net", "fxcop", "" ]
This is what I understand about IDisposable and finalizers from "CLR via C#", "Effective C#" and other resources: * IDisposable is for cleaning up managed and unmanaged resources deterministically. * Classes that are responsible for unmanaged resources (e.g. file handles) should implement IDisposable and provide a finalizer to guarantee that they are cleaned up even if the client code does not call Dispose() on the instance. * Classes that are responsible for managed resources only should never implement a finalizer. * If you have a finalizer then you must implement IDisposable (this allows client code to do the right thing and call Dispose(), while the finalizer prevents leaking resources if they forget). While I understand the reasoning for and agree with all of the above, there is one scenario where I think it makes sense to break these rules: a singleton class that is responsible for unmanaged resources (such as providing a single point of access to particular files). I believe it is always wrong to have a Dispose() method on a singleton because the singleton instance should live for the life of the application and if any client code calls Dispose() then you are stuffed. However, you want a finalizer so that when the application is unloaded the finalizer can clean up the unmanaged resources. So having a singleton class with a finalizer that does not implement IDisposable seems to me to be a reasonable thing to do, yet this type of design is counter to what I understand are best practices. Is this a reasonable approach? If not, why not and what are the superior alternatives?
If the unmanaged resource is released only on application exit you don't even need to worry with a finalizer since the process unload should deal with this for you anyway. If you have multiple app domains and you want to deal with an app domain unload that's one possible issue but possibly one you don't need to care about. I second those saying that this design is possibly not the right thing to do (and will make it harder to fix is subsequently you find that you do actually need two instances) Create the object (or a lazy loading wrapper object) in your entry point and pass it through the code to where it is needed making it clear who is responsible for providing it to whom, then you are free to change the decision to use only one with little effect to the rest of the code (which uses what it gets given)
I'd first mention that Object Oriented design patterns and their consequences do not always influence every language decision, even in Object Oriented languages. You can certainly find classic design patterns that are easier to implement in one language (Smalltalk) as opposed to another (C++). That being said, I'm not sure I agree with the premise that a singleton instance should only be disposed at the end of an application. Nothing in the design pattern descriptions that I've read for [Singleton](http://www.dofactory.com/Patterns/PatternSingleton.aspx) (or [Design Patterns: Elements of reusable Object-Oriented Software](https://rads.stackoverflow.com/amzn/click/com/0201633612)) mention this as a property of this pattern. A singleton should ensure that only one instance of the class exists at any one moment in time; that does not imply that it must exist for as long as the application exists. I have a feeling that in practice, many singletons do exist for most of the life of an application. However, consider an application that uses a TCP connection to communicate with a server, but can also exist in a disconnected mode. When connected, you would want a singleton to maintain the connection information and state of the connection. Once disconnected, you may want to keep that same singleton - or you may dispose of the singleton. While some may argue that it makes more sense to keep the singleton (and I may even be among them), there is nothing in the design pattern itself that precludes you from disposing of it - if a connection is remade, the singleton can be instantiated again, as no instance of it exists at that moment in time. In other words, you can create scenarios where it is logical for singletons to have IDisposable.
Singleton with finalizer but not IDisposable
[ "", "c#", ".net", "singleton", "idisposable", "" ]
I have 3 variables like this: $first = 2; $second = 5; $operation = '\*'; how can I programaticly assign the solution to this math problem to the $answer variable? I have tried eval(), but that does not work.
eval() should work perfectly fine for something like this. Remember that eval() returns NULL though, unless you tell it to return something. ``` <?php $first = 3; $second = 4; $operation = "*"; $answer = eval('return '.$first.$operation.$second.';'); echo $answer; ?> ```
``` function add($a, $b) { return $a + $b; } function multiply($a, $b) { return $a * $b; } function divide($a, $b) { return $a / $b; } $operations = array( '+' => 'add', '*' => 'multiply', '/' => 'divide', ); $a = 2; $b = 5; $operation = '*'; echo $operations[$operation]($a, $b); ```
Preforming math stored in variables
[ "", "php", "" ]
I need a CSVParser class file A Class File which parses csv and returns a dataSet as a result ASP.Net
I'm pretty sure that [CSVReader](http://www.codeproject.com/KB/database/CsvReader.aspx) (CodeProject) can read to `DataTable`. ``` DataTable table = new DataTable(); // set up schema... (Columns.Add) using(TextReader text = File.OpenText(path)) using(CsvReader csv = new CsvReader(text, hasHeaders)) { table.Load(csv); } ``` Note that manually setting up the schema is optional; if you don't, I believe it assumes that everything is `string`.
Simple google gives plenty of [results](http://windowsclient.net/blogs/faqs/archive/2006/05/30/how-do-i-load-a-csv-file-into-a-datatable.aspx).
Howto parse csv and returns a dataSet as a result
[ "", "c#", "asp.net", "csv", "parsing", "" ]
Currentaly I am using a gridView and on RowCommand event of gridview the details of selected row are displayed below the Gridview. But now I have to display the details just below the row clicked. Means it will be displayed in between the selected row and next row of it. The gridview code is as ``` <asp:GridView ID ="gvUserDataReadOnly" AutoGenerateColumns ="false" runat ="server" OnRowCommand ="gvUserDataReadOnly_RowCommand" DataKeyNames ="Guid"> <Columns > <asp:ButtonField ItemStyle-Width ="100px" DataTextField ="FirstName" HeaderText ="<%$ Resources:StringsRes,pge_ContactManager_FirstName %>" SortExpression ="FiratName" CommandName ="show_Details" ButtonType ="link" /> <asp:ButtonField ItemStyle-Width ="100px" DataTextField ="LastName" HeaderText ="<%$ Resources:StringsRes,pge_ContactManager_LastName %>" SortExpression ="LastName" CommandName ="show_Details" ButtonType ="link" /> <asp:BoundField ItemStyle-Width ="100px" DataField ="TypeName" HeaderText ="<%$ Resources:StringsRes,pge_ContactManager_TypeName %>" SortExpression ="TypeId" /> </Columns> <RowStyle Height="25px" /> <HeaderStyle Height="30px"/> </asp:GridView> ``` and div tag which i want to display in betwwen rows is ``` <div id ="dvUserDatails" runat ="server" visible ="false" class ="eventcontent"> <h2><asp:Literal ID ="ltUserName" runat ="server" ></asp:Literal></h2> <asp:Label Text ="Type : " runat ="server" ID ="Type"></asp:Label><asp:Literal ID ="ltType" runat ="server" ></asp:Literal><br /> <asp:Label Text ="Address : " runat ="server" ID ="Address"></asp:Label><asp:Literal ID ="ltAddress" runat ="server" ></asp:Literal><br /> <asp:Label Text ="Phone No : " runat ="server" ID ="PhoneNo"></asp:Label><asp:Literal ID ="ltPhoneNo" runat ="server" ></asp:Literal><br /> <asp:Label Text ="Mobile No : " runat ="server" ID ="MobNo"></asp:Label><asp:Literal ID ="ltMobNo" runat ="server" ></asp:Literal><br /> <asp:Label Text ="Email Id : " runat ="server" ID ="emailId"></asp:Label><asp:Literal ID ="ltemail" runat ="server" ></asp:Literal><br /> </div> ``` I can't use EditItem Template as I am not using Edit button of gridview. Can anyone tell me how to do this task? Any other way to do this? Thanks in advance.
Please refer to the following artice, that describes exactly what you want: [DataGrid and Details Using ASP.NET, C#, and JavaScript (Expand / Collapse Rows)](http://www.progtalk.com/ViewArticle.aspx?ArticleID=1)
You probably want to use a Repeater and build the table yourself. I don't think that you'll be able to get a GridView to work as you can only control what goes in each row and what you want to do is alternate rows between general and detailed information. More information on how to connect it to your data source and handle the button clicks can be found at [MSDN](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx). ``` <asp:Repeater ID="gvUserDataReadOnly" runat="server" DataKeyNames="Guid"> <HeaderTemplate> <table> <tr> <th>Header 1</th> ... </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> ... first name button ... </td> ... </tr> </ItemTemplate> <AlternatingItemTemplate> <tr runat="server" visible="false"> <td colspan="3"> ... details (minus div) here ... </td> </tr> </AlternatingItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> ```
Is it possible to display a panel or div in between gridview rows on RowCommand event
[ "", "c#", "asp.net", "gridview", "" ]
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this? ``` if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo() ```
You can reload a module when it has already been imported by using [`importlib.reload()`](https://docs.python.org/3/library/importlib.html#importlib.reload): ``` from importlib import reload # Python 3.4+ import foo while True: # Do some things. if is_changed(foo): foo = reload(foo) ``` In Python 2, [`reload`](https://docs.python.org/2.7/library/functions.html#reload) was a builtin. In Python 3, it was [moved](https://docs.python.org/3/whatsnew/3.0.html#builtins) to the [`imp`](https://docs.python.org/3/library/imp.html) module. In 3.4, `imp` was [deprecated](https://docs.python.org/3/whatsnew/3.4.html#importlib) in favor of [`importlib`](https://docs.python.org/3/library/importlib.html). When targeting 3 or later, either reference the appropriate module when calling `reload` or import it. I think that this is what you want. Web servers like Django's development server use this so that you can see the effects of your code changes without restarting the server process itself. To quote from the docs: > * Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the [loader](https://docs.python.org/3/glossary.html#term-loader) which originally loaded the module. The `init` function of extension modules is not called a second time. > * As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero. > * The names in the module namespace are updated to point to any new or changed objects. > * Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired. As you noted in your question, you'll have to reconstruct `Foo` objects if the `Foo` class resides in the `foo` module.
In Python 3.0–3.3 you would use: [`imp.reload(module)`](http://docs.python.org/3.3/library/imp.html?highlight=imp#imp.reload) The [BDFL](http://docs.python.org/3.3/glossary.html#term-bdfl) has [answered](http://mail.python.org/pipermail/edu-sig/2008-February/008421.html) this question. However, [`imp` was deprecated in 3.4, in favour of `importlib`](https://docs.python.org/dev/library/imp.html) (thanks [@Stefan!](https://stackoverflow.com/users/2068635/stefan)). I *think*, therefore, you’d now use [`importlib.reload(module)`](https://docs.python.org/dev/library/importlib.html#importlib.reload), although I’m not sure.
How do I unload (reload) a Python module?
[ "", "python", "module", "reload", "python-import", "" ]
I can drop a table if it exists using the following code but do not know how to do the same with a constraint: ``` IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'TableName') AND type = (N'U')) DROP TABLE TableName go ``` I also add the constraint using this code: ``` ALTER TABLE [dbo].[TableName] WITH CHECK ADD CONSTRAINT [FK_TableName_TableName2] FOREIGN KEY([FK_Name]) REFERENCES [dbo].[TableName2] ([ID]) go ```
The more simple solution is provided in [Eric Isaacs's](https://stackoverflow.com/a/13186918) answer. However, it will find constraints on any table. If you want to target a foreign key constraint on a specific table, use this: ``` IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'FK_TableName_TableName2') AND parent_object_id = OBJECT_ID(N'dbo.TableName') ) ALTER TABLE [dbo].[TableName] DROP CONSTRAINT [FK_TableName_TableName2] ```
This is a lot simpler than the current proposed solution: ``` IF (OBJECT_ID('dbo.FK_ConstraintName', 'F') IS NOT NULL) BEGIN ALTER TABLE dbo.TableName DROP CONSTRAINT FK_ConstraintName END ``` If you need to drop another type of constraint, these are the applicable codes to pass into the OBJECT\_ID() function in the second parameter position: ``` C = CHECK constraint D = DEFAULT (constraint or stand-alone) F = FOREIGN KEY constraint PK = PRIMARY KEY constraint UQ = UNIQUE constraint ``` You can also use OBJECT\_ID without the second parameter. Full List of types [here](http://technet.microsoft.com/en-us/library/ms190324.aspx): Object type: > ``` > AF = Aggregate function (CLR) > C = CHECK constraint > D = DEFAULT (constraint or stand-alone) > F = FOREIGN KEY constraint > FN = SQL scalar function > FS = Assembly (CLR) scalar-function > FT = Assembly (CLR) table-valued function > IF = SQL inline table-valued function > IT = Internal table > P = SQL Stored Procedure > PC = Assembly (CLR) stored-procedure > PG = Plan guide > PK = PRIMARY KEY constraint > R = Rule (old-style, stand-alone) > RF = Replication-filter-procedure > S = System base table > SN = Synonym > SO = Sequence object > ``` **Applies to: SQL Server 2012 through SQL Server 2014.** > ``` > SQ = Service queue > TA = Assembly (CLR) DML trigger > TF = SQL table-valued-function > TR = SQL DML trigger > TT = Table type > U = Table (user-defined) > UQ = UNIQUE constraint > V = View > X = Extended stored procedure > ```
How do I drop a foreign key constraint only if it exists in sql server?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
Is it possible to use a C# assembly from Clarion? If not. Is it possible to run a simple console application written in C# and read the output from it back into Clarion? In both cases, how would you do it? In the case of the assembly, would you have to do something special with it for Clarion to get access to it? In both cases, how would you do it in Clarion? The reason is we have two methods written in C#, which is used by an application written in C#. But we also need to use that same method in a Clarion application. And we really don't want to write the methods again for Clarion, since they are a bit complex...
Clarion is a programming language. Don't know it myself. Parts of the old system where I work is made with it, and we are working on porting it to C# .NET. So for a while they have to live side by side. We found a work around so it is no longer needed though. But thanks for info :) Maybe we will need it further down the road instead. Although I hope not... hehe. For those curious: [en.wikipedia.org/wiki/Clarion\_(programming\_language)](http://en.wikipedia.org/wiki/Clarion_%28programming_language%29)
Unless you need to display a .Net UserControl in your clarion program I would recommend using the technique described here: Robert Giesecke - [C# Project Template for Unmanaged Exports](http://sites.google.com/site/robertgiesecke/Home/uploads/csharpprojecttemplateforunmanagedexports) On the Clarion side you then just link and use the .Net assembly as you would any other unmanaged DLL. I have found it convenient to load the DLL at runtime with the LoadLibrary API too.
Clarion: Possible to use a C# Assembly?
[ "", "c#", "dll", "clarion", "" ]
I need to write a query that will group a large number of records by periods of time from Year to Hour. My initial approach has been to decide the periods procedurally in C#, iterate through each and run the SQL to get the data for that period, building up the dataset as I go. ``` SELECT Sum(someValues) FROM table1 WHERE deliveryDate BETWEEN @fromDate AND @ toDate ``` I've subsequently discovered I can group the records using Year(), Month() Day(), and datepart(week, date) and datepart(hh, date). ``` SELECT Sum(someValues) FROM table1 GROUP BY Year(deliveryDate), Month(deliveryDate), Day(deliveryDate) ``` My concern is that using datepart in a group by will lead to worse performance than running the query multiple times for a set period of time due to not being able to use the index on the datetime field as efficiently; any thoughts as to whether this is true? Thanks.
As with anything performance related **Measure** Checking the query plan up for the second approach will tell you any obvious problems in advance (a full table scan when you know one is not needed) but there is no substitute for measuring. In SQL performance testing that measurement should be done with appropriate sizes of test data. Since this is a complex case, you are not simply comparing two different ways to do a single query but comparing a single query approach against a iterative one, aspects of your environment may play a major role in the actual performance. Specifically 1. the 'distance' between your application and the database as the latency of each call will be wasted time compared to the one big query approach 2. Whether you are using prepared statements or not (causing additional parsing effort for the database engine on each query) 3. whether the construction of the ranges queries itself is costly (heavily influenced by 2)
If you put a formula into the field part of a comparison, **you get a table scan**. The index is on field, not on datepart(field), **so ALL fields must be calculated** - so I think your hunch is right.
SQL Group By Year, Month, Week, Day, Hour SQL vs Procedural Performance
[ "", "sql", "sql-server", "performance", "" ]
I wanted to experiment a little with python 3.0 at home. I got python 3.0 working, I've played around with some scripts, and I thought it would be fun to try to make a small web-project with it. As I was googling, it turned out, that mod\_python, for some reasons, will not be able to support python 3.0. The only other alternative I've found is [mod\_wsgi](http://code.google.com/p/modwsgi/). On the main page of the [mod\_wsgi](http://code.google.com/p/modwsgi/) project, it says, that if you want to play with python 3.0, you have to get the latest version from subversion repository. I was wondering, if there is somewhere a pre-built windows binaries available? If there are no such binaries, then I'd be thankful for any resources about building it with VC++ 2008. Or maybe even general resources about building apache and it's modules with VC++ 2008. Thanks. Oh and, I'm using the latest Apache 2.2 release. EDIT: Will it be a problem, if I'll be using the official apache build with my own build of a mod\_wsgi (I used depends.exe on apache, and seems that it's not built with VC++ 2008)?
Binaries for Windows are now being supplied from the mod\_wsgi site for Apache 2.2 and Python 2.6 and 3.0. Python 3.0 is only supported for mod\_wsgi 3.0 onwards. See: <http://code.google.com/p/modwsgi/downloads/list> --- UPDATE July 2015 The above link is no longer valid. Instead see: * <https://github.com/GrahamDumpleton/mod_wsgi/blob/develop/win32/README.rst>
I would like to find either 2.6 (preferable) or 3.0 (okay) Windows binaries myself, and have looked into this a bit. There are Windows build steps for mod\_wsgi buried deep in the Google Group for it. I think they're out of date; only one person appears to have ever done it and told the world how well it worked out. There may well be problems compiling that require a patch. I do not think you will need to build your own Apache, or if it matters that the VC++ version is different (though I don't have a ton of evidence for this belief). VC++ version is very important for Python module builds since they rely heavily on the internals of the compiler data structures. I think the Apache module interface is more structured. You'll probably want to post to the mod\_wsgi group if you try this and hit problems, or if you successfully build the modules, please post them as some of us would very much like them but are too busy to get to doing it ourselves :(
Where to get/How to build Windows binary of mod_wsgi with python 3.0 support?
[ "", "python", "apache", "visual-c++", "mod-wsgi", "" ]
Is there any way to convert a string to Title case, using JSTL tags? Thanks in Advance.
An alternative to transforming the string on the server is to [let CSS do the work](http://www.w3.org/TR/CSS2/text.html#caps-prop): ``` text-transform: capitalize ```
An idea: In a class, create a simple method that uses the WordUtils from Apache Commons Lang that will manipulate your String: ``` import org.apache.commons.lang.WordUtils; ... public static String titleCase(String input){ return WordUtils.capitalize(input);; } ``` And now, create your own tag (in a function.tld) : ``` <?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>functions library</description> <display-name>functions</display-name> <tlib-version>1.1</tlib-version> <short-name>xfn</short-name> <uri>http://yourdomain/functions.tld</uri> <function> <description> Title case a String </description> <name>titleCase</name> <function-class>Functions</function-class> <function-signature>java.lang.String titleCase(java.lang.String)</function-signature> <example> ${xfn:titleCase(string)} </example> </function> </taglib> ``` ps: I was quite inspired from [this post](https://stackoverflow.com/questions/74248/in-jstl-jsp-given-a-java-util-date-how-do-i-find-the-next-day) to give my answer.
converting strings to Title case in JSTL
[ "", "java", "string", "jstl", "" ]
Digital commercial products that customers pay for download link. I have put all the zipped files (products) outside of web document root and buyers download them via a php script which is integrated with paypal IPN to make sure the downloader is a paying buyer. Sort of like: <http://www.mysite.com/download.php?buyer_id=xxx> Thus far it all works with only one problem. The zip files I download via the URL above is corrupted and can't be opened correctly with WinRAR. However, directly downloaded zip is fine. My code: ``` $path = WAREHOUSE_PATH.'/products/'.$identifier.'.zip'; $mm_type="application/octet-stream"; header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Type: " . $mm_type); header("Content-Length: " .(string)(filesize($path)) ); header('Content-Disposition: attachment; filename="'.basename($path).'"'); header("Content-Transfer-Encoding: binary\n"); $fp = @fopen($path,"rb"); if ($fp) { while(!feof($fp)) { print(fread($fp, 1024*8)); flush(); if (connection_status()!=0) { @fclose($fp); die(); } } @fclose($fp); } ``` What could be wrong? Thanks! Problem solved: Thank you all for the tips. It turns out that the downloaded packages contains a few extra white spaces which shouldn't be there. Silly.
You'd be better off just using [`readfile()`](http://www.php.net/readfile). Unless you have ignore\_user\_abort on, then the script will terminate automatically if the user cancels anyway. If you're still having problems, load the file up in a hex editor and compare the first few characters and the last few characters.
I would suggest changing this: ``` $fp = @fopen($path,"rb"); if ($fp) { while(!feof($fp)) { print(fread($fp, 1024*8)); flush(); if (connection_status()!=0) { @fclose($fp); die(); } } @fclose($fp); } ``` to this ``` readfile($path); ``` You can find more info on readfile [here](http://php.net/readfile), but basically it will do everything your loop does.
What's the best way to supply download of a digital product in PHP?
[ "", "php", "download", "" ]
Ok I'm at my work this friday setting up a table that will have data in it that will come from a separate file called values.php. When I write it like this, the divs turn up blank. I think I have the "include" written wrong, does an absolute path not work? ``` <?php include('http://www.nextadvisor.com/credit_report_services/values.php'); ?> <div class="box_text"> <div class="box_image"> <a href="<?php echo $offer1link ?>" target="blank"><img src="<?php echo $offer1logo ?>" alt="<?php echo $offer1name ?>"></a></div> <div class="box_rating"> Rating:<span class="star_rating"><img src="<?php echo $offer1star1 ?>" alt=""></span><br> <div class="rating_review"><a href="<?php echo $offer1link ?>" target="blank">Go to Site</a> | <a href="<?php echo $offer1anchor ?>">Review</a></div> </div> <br style="clear: both;"> </div> ``` Oh and thanks in advance for any help you can give. Anyone who has helps me is the greatest. I feel bad cause sometimes two people answer the question and I can't give the green check to both.
The type of include you are trying to do is blocked by default, not to say that it is dangerous. You are trying to include a remote file. If your script is in the same machine as the "values.php" you should use an absolute path similar to "/var/www/nextadvisor.com/credit\_report\_services/values.php" or a relative path depending on the location of your file, instead of <http://www.nextadvisor.com/credit_report_services/values.php> It doesn't seem to me that you are trying to include a remote file but if you still want to include a remote file you must set the following directives in your php.ini ``` allow_url_fopen = 1 allow_url_include = 1 ```
Since you're using a URL, PHP will send a request to the server for the file, and the server will parse it just as it would if a browser requested it. What you probably want to do is use a path relative to the script for your include. If the file you want to include is in the same folder, just use `include('values.php');`
Absolute paths for PHP include
[ "", "php", "include", "" ]
It is easy to read an XML file and get the exact Node Text, but how do I Update that Node with a new value? To read: ``` public static String GetSettings(SettingsType type, SectionType section) { XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH)); XmlDocument document = new XmlDocument(); document.Load(reader); XmlNode node = document.SelectSingleNode( String.Format("/MyRootName/MySubNode/{0}/{1}", Enum.Parse(typeof(SettingsType), type.ToString()), Enum.Parse(typeof(SectionType), section.ToString()))); return node.InnerText; } ``` to write ...? ``` public static void SetSettings(SettingsType type, SectionType section, String value) { try { XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH)); XmlDocument document = new XmlDocument(); document.Load(reader); XmlNode node = document.SelectSingleNode( String.Format("/MyRootName/MySubNode/{0}/{1}", Enum.Parse(typeof(SettingsType), type.ToString()), Enum.Parse(typeof(SectionType), section.ToString()))); node.InnerText = value; node.Update(); } catch (Exception ex) { throw new Exception("Error:", ex); } } ``` **Note** the line, node.Update(); does not exist, but that's what I wanted :) I saw the XmlTextWriter object, but it will write the entire XML to a new file, and I just need to update one value in the original Node, I can save as a new file and then rename the new file into the original name but... it has to be simpler to do this right? Any of you guys have a sample code on about to do this? Thank you
You don't need an "update" method - setting the InnerText property updates it. However, it only applies the update in memory. You *do* need to rewrite the whole file though - you can't just update a small part of it (at least, not without a *lot* of work and no out-of-the-box support).
`XmlDocument.Load` has an overload that will take the filename directly so there is no need for the reader. Similarly when you are done `XmlDocument.Save` will take a filename to which it will save the document.
How to Update a XML Node?
[ "", "c#", "asp.net", "xml", "" ]
I need to use a query which will pull data from a field when it is less then 4 words, is this possible and if so could you give some pointers? I suppose if not possible it could cycle through the results until it found one which was 3 words and then end the while statement when it has found one.
``` SELECT column FROM table where LENGTH(column) - LENGTH(REPLACE(column, ' ', ''))+1 < 4 ``` [Credits and full explanation](http://www.mwasif.com/2008/12/count-number-of-words-in-a-mysql-column/) Here [Regexp Solution](http://www.experts-exchange.com/Database/MySQL/Q_22682620.html). ``` select * from TABLE where column not regexp '^.+( .+){4}$' ```
Calling functions in a select on a per-record basis is almost always a bad idea in terms of performance - disk space is usually much 'cheaper' than CPU capacity (I enclose that in quotes since I'm not talking about dollar costs). Most databases tend to be "more read than write" as my DBA mentor once told me; the ideal solution in that situation is to have a trigger when inserting or updating the row to calculate the number of words in that column and store them in another column. The reason it's ideal is that the number of words only changes when you update the field, so it's better to perform the time-intensive calculation at that point rather than (unnecessarily) every time you read the record. The added required space will be minimal since you're adding an (short) integer to a long (string) but you'll find your queries scream along by just using the integer field (make sure you index on it).
PHP MySql Where Field = <4 Words
[ "", "php", "mysql", "" ]
> **Possible Duplicate:** > [Could you explain STA and MTA?](https://stackoverflow.com/questions/127188/could-you-explain-sta-and-mta) > All ThreadPool threads are in the > multithreaded apartment. --As per the MSDN What does that mean? I am really concerned with what the difference between the multi vs single threaded apartment model is. Or what does the apartment model mean? I have read the MSDN on it, and it doesn't really make sense to me. I think I may have an idea, but I was thinking someone on here could explain it in plain English. Thanks, Anthony D **Update 1** Found this [Could you explain STA and MTA?](https://stackoverflow.com/questions/127188/could-you-explain-sta-and-mta) Can anyone be more descriptive? **Update 2** I am also looking for an answer about how this applies to the thread pool, and what I need to watch out for because of this.
STA (single-threaded apartment) and MTA (multi-threaded apartment) are to do with [COM](http://msdn.microsoft.com/en-us/library/ms690156(VS.85).aspx). COM components can be designed to be accessed by a single thread, in which case it they are hosted in an [STA](http://msdn.microsoft.com/en-us/library/ms680112.aspx), or they can be made internally thread safe, and hosted in an [MTA](http://msdn.microsoft.com/en-us/library/ms693421(VS.85).aspx). A process can have only one MTA, but many STAs. If you're only going to consume COM components all that you really need to know is that you have to match the apartment to the component or nasty things will happen.
In actuality, STAs and MTAs have an impact on .NET code. See Chris Brumme's blog entry for way more detail then you probably need: <https://devblogs.microsoft.com/cbrumme/apartments-and-pumping-in-the-clr/> It's really important to understand how STAs pump messages in .NET. It does have consequences.
Single-Threaded Apartments vs Multi-Threaded Apartments
[ "", "c#", ".net", "multithreading", "apartments", "" ]
I currently have the query running on Postgres: ``` SELECT * FROM addenda.users WHERE users.username LIKE '%\_' ``` But rather then returning just entries ending in an underscore, I get all results back, regardless of whether it contains an underscore or not. Running the query below returns a username which is just an underscore, so the escaping does work: ``` SELECT * FROM addenda.users WHERE users.username LIKE '\_' ``` And running the query below returns a username which ends with a specific letter (s): ``` SELECT * FROM addenda.users WHERE users.username LIKE '%s' ``` What am I doing wrong?
Is your backslash not getting through to PostgreSQL? If you're passing the string through another layer that treats the backslash as an escape character (e.g. a Java String), then that layer may be removing the backslash, and you might need to escape your backslash for that layer. Do you have any more single character usernames? If the backslash wasn't getting through to PostgreSQL then they would also match `'_'` You might be able to try the [ESCAPE clause](http://www.postgresql.org/docs/8.3/interactive/functions-matching.html#FUNCTIONS-LIKE): `username LIKE '%!_' ESCAPE '!'`
`"_"` is the single-character wildcard in most SQL variants. You HAVE to escape it if you want to match an actual `"_"` character.
Why does my query with LIKE '%\_' return all rows and not just those ending in an underscore?
[ "", "sql", "postgresql", "" ]
**bpp** = bits per pixel, so 32bpp means 8/8/8/8 for R/G/B/A. Like .NET has an enum for these "System.Drawing.Imaging.PixelFormat". Now once I have a **Bitmap** or **Image** object with my graphics, **how would I save it** to a file / what format would I use? What image file format (JPEG/GIF/PNG) supports low bit-depths like 16bpp or 8bpp *(instead of the usual 32bpp or 24bpp)*
Try this: ``` ImageCodecInfo pngCodec = ImageCodecInfo.GetImageEncoders().Where(codec => codec.FormatID.Equals(ImageFormat.Png.Guid)).FirstOrDefault(); if (pngCodec != null) { EncoderParameters parameters = new EncoderParameters(); parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8); myImage.Save(myStream, pngCodec, parameters); } ```
I don't think the other's answering tested their code as GDI+ PNG does not support the Encoder.BitDepth EncoderParameter. In fact, the only Codec which does is TIFF. You need to change your image's PixelFormat before saving in order to have any effect out the output. This won't always produce the PixelFormat you expect. See [my post here](https://web.archive.org/web/20140729141035/http://www.atalasoft.com/cs/blogs/rickm/archive/2009/10/07/system-drawing-round-trip-pixelformat-stability.aspx) for more information on which PixelFormats turn into what. As for PixelFormat conversions, something like the following will work: ``` private Bitmap ChangePixelFormat(Bitmap inputImage, PixelFormat newFormat) { Bitmap bmp = new Bitmap(inputImage.Width, inputImage.Height, newFormat); using (Graphics g = Graphics.FromImage(bmp)) { g.DrawImage(inputImage, 0, 0); } return bmp; } ``` Unfortunately, these conversions can produce some really bad output. This is especially true in the case where you are performing a lossy conversion (high bit depth to lower).
Generate image file with low bit depths?
[ "", "c#", "vb.net", "bitmap", "imaging", "" ]
Is there a way to convert variable names to strings in javascript? To be more specific: ``` var a = 1, b = 2, c = 'hello'; var array = [a, b, c]; ``` Now at some point as I go through the array, I need to get variable names (instead of their values) as strings - that would be 'a' or 'b' or 'c'. And I really need it to be a string so it is writeable. How can I do that?
Use a Javascript object literal: ``` var obj = { a: 1, b: 2, c: 'hello' }; ``` You can then traverse it like this: ``` for (var key in obj){ console.log(key, obj[key]); } ``` And access properties on the object like this: ``` console.log(obj.a, obj.c); ```
What you could do is something like: ``` var hash = {}; hash.a = 1; hash.b = 2; hash.c = 'hello'; for(key in hash) { // key would be 'a' and hash[key] would be 1, and so on. } ```
How to make a variable addressable by name as string in JavaScript?
[ "", "javascript", "" ]
This question is inspired by Jon Skeet's answer: [Is there a c# equivalent to c++'s access-modifier regions](https://stackoverflow.com/questions/431091/is-there-a-c-equivalent-to-cs-access-modifier-regions#431105) He makes a comment that it is possible for the order of fields in a file to matter. I am guessing that this has to do with the order that the fields are initialized, but I think it's a dangerous enough thing to code based on this side effect that it warranted its own question and discussion. Are there other thoughts around how the order of fields within your code file could be manipulated and what impact that might have?
Here is a classic example from the C# language spec (Section 10.5.5) ``` class Test { static int a = b + 1; static int b = a + 1; static void Main() { Console.WriteLine("a = {0}, b = {1}", a, b); } } ``` This is a completely valid program and as written (a = 1, b =2). However if you swap the ordering of the fields they will also swap values.
Yeah, it does matter when interfacing with unmanaged code.
Does the order of fields in C# matter?
[ "", "c#", "field", "specifications", "" ]
I recently [read this thread on MSDN](http://social.msdn.microsoft.com/Forums/en-US/clr/thread/b18b0a27-e2fd-445a-bcb3-22a315cd6f0d/). So I was thinking of using a lambda expression as a way of calling EndInvoke just as a way to make sure everything is nice and tidy. Which would be more correct? Example 1: ``` Action<int> method = DoSomething; method.BeginInvoke(5, (a)=>{method.EndInvoke(a);}, null); ``` Example 2: ``` Action<int> method = DoSomething; method.BeginInvoke(5, (a)=> { Action<int> m = a.AsyncState as Action<int>; m.EndInvoke(a); }, method); ```
Your 2nd example is slightly more efficient because the "method" delegate instance doesn't have to be captured in the closure. I doubt you'd ever notice.
I don't know if this was possible way back in Jan '09, but certainly now you can just write this: ``` method.BeginInvoke(5, method.EndInvoke, null); ```
The proper way to end a BeginInvoke?
[ "", "c#", "lambda", "" ]
I am writing a web application using PHP. I want to use the MVC pattern for this, and decided to go with [CodeIgniter](http://codeigniter.com/). My application will have some pages which will require authentication, and some pages won't. I want to design this in a very generic way, so that there should be no code duplication. Can any one point to some good "design/class structure" for this?
Write a custom library that you can autoload in your code igniter app on every page view. It should have functions that: * Authenticate the user ie. check if a user is logged in or not * Log you in ie. set a session variable or something * Log you out Then in your controller classes you can do a call to the authentication function in the constructor then depending on the outcome continue as normal or redirect them to a login screen with an access denied message. Do a search on the code igniter wiki for 'authentication' and there are a number of results that may help: <http://codeigniter.com/wiki/>
"Ion Auth" is lean, well-programmed, somewhat widely used and is actively maintained. <http://github.com/benedmunds/CodeIgniter-Ion-Auth>
User authentication with CodeIgniter
[ "", "php", "codeigniter", "authentication", "" ]
I need a library that allows me to do email operations(e.g Sent/Receive mail) in Gmail using Java.
Have you seen [g4j - GMail API for Java](http://g4j.sourceforge.net/)? > GMailer API for Java (g4j) is set of > API that allows Java programmer to > communicate to GMail. With G4J > programmers can made Java based > application that based on huge storage > of GMail.
You can use the Javamail for that. The thing to remember is that GMail uses SMTPS not SMTP. ``` import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; public class SimpleSSLMail { private static final String SMTP_HOST_NAME = "smtp.gmail.com"; private static final int SMTP_HOST_PORT = 465; private static final String SMTP_AUTH_USER = "myaccount@gmail.com"; private static final String SMTP_AUTH_PWD = "mypwd"; public static void main(String[] args) throws Exception{ new SimpleSSLMail().test(); } public void test() throws Exception{ Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", SMTP_HOST_NAME); props.put("mail.smtps.auth", "true"); // props.put("mail.smtps.quitwait", "false"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(true); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject("Testing SMTP-SSL"); message.setContent("This is a test", "text/plain"); message.addRecipient(Message.RecipientType.TO, new InternetAddress("elvis@presley.org")); transport.connect (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); } } ```
Access gmail from Java
[ "", "java", "gmail", "" ]
I am not that familiar with Javascript, and am looking for the function that returns the UNICODE value of a character, and given the UNICODE value, returns the string equivalent. I'm sure there is something simple, but I don't see it. Example: * ASC("A") = 65 * CHR(65) = "A" * ASC("ਔ") = 2580 * CHR(2580) = "ਔ"
Have a look at: ``` String.fromCharCode(64) ``` and ``` String.prototype.charCodeAt(0) ``` The first must be called on the String **class** (literally `String.fromCharCode...`) and will return "@" (for 64). The second should be run on a String **instance** or **primitive** (e.g., `"@@@".charCodeAt...`) and returns the Unicode code of the first character (the '0' is a position within the string, you can get the codes for other characters in the string by changing that to another number). The script snippet: ``` document.write("Unicode for character ਔ is: " + "ਔ".charCodeAt(0) + "<br />"); document.write("Character 2580 is " + String.fromCharCode(2580) + "<br />"); ``` gives: ``` Unicode for character ਔ is: 2580 Character 2580 is ਔ ```
Because [JavaScript uses UCS-2 internally](http://mathiasbynens.be/notes/javascript-encoding), `String.fromCharCode(codePoint)` won’t work for supplementary Unicode characters. If `codePoint` is `119558` (`0x1D306`, for the `''` character), for example. If you want to create a string based on a non-BMP Unicode code point, you could use [Punycode.js](http://mths.be/punycode)’s utility functions to convert between UCS-2 strings and UTF-16 code points: ``` // `String.fromCharCode` replacement that doesn’t make you enter the surrogate halves separately punycode.ucs2.encode([0x1d306]); // '' punycode.ucs2.encode([119558]); // '' punycode.ucs2.encode([97, 98, 99]); // 'abc' ``` if you want to get the Unicode code point for every character in a string, you’ll need to convert the UCS-2 string into an array of UTF-16 code points (where each surrogate pair forms a single code point). You could use [Punycode.js](http://mths.be/punycode)’s utility functions for this: ``` punycode.ucs2.decode('abc'); // [97, 98, 99] punycode.ucs2.decode(''); // [119558] ```
What is an easy way to call Asc() and Chr() in JavaScript for Unicode values?
[ "", "javascript", "unicode", "" ]
i have a module (a single .py file, actually), with a class called HashedDir. when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different. Eg: ``` h1 = HashedDir('/path/to/dir') print h1.getList()['files'] # /path/to/dir h2 = HashedDir('some/other/path') print h1.getList()['files'] # some/other/path print h2.getList()['files'] # some/other/path ``` Any idea? This is the class: ``` from os import walk from os import path from hashlib import md5 import re class HashedDir: """ A list of files with associated md5 hashes generated retrieving thou a recursive walk in the directory tree starting from a provided root directory. Also stores the dirs in each dir """ # {'files': [ # ('/path/to/file1', '52bc309e11259af15e4623c7a0abc28c'), # ('/path/to/file2', '52bc309e11259af15e4623c7a0abc28c'), # ('/path/to/dir/file3', '52bc309e11259af15e4623c7a0abc28c') # ], # 'dirs': ['/path/to/dir1', '/path/to/dir2'] # } fileList = {'files': [], 'dirs': []} ignoreList = [] def __init__(self, rootDir, ignoreList=[]): """ ignoreList is a list of regular expressions. If a file or a dir matches that regular expression, don't count it """ self.ignoreList = ignoreList for dirpath, dirnames, filenames in walk(rootDir): for fileName in filenames: completeName = path.join(dirpath,fileName) hash = md5(open(completeName).read()).hexdigest() relativePath = self._relativePath(completeName, rootDir) if not self._toBeIgnored(relativePath): self.fileList['files'].append((relativePath, hash)) for dirName in dirnames: completeName = path.join(dirpath, dirName) relativePath = self._relativePath(completeName, rootDir) if not self._toBeIgnored(relativePath): self.fileList['dirs'].append(relativePath) def _relativePath(self, path, base): return path.replace(base, '') def _toBeIgnored(self, path): for regex in self.ignoreList: if re.compile(regex).search(path) != None: return True return False def getList(self): return self.fileList ``` Thanks in advance
There are two kinds of variables in a class: * class variables, defined at the class level, and common to all instances * instance variables, defined within a class method (usually `__init__`) and qualified by the instance (usually `self.`). Example ``` class SomeClass( object ): classVariable = 0 def __init__( self ): self.instanceVariable= 0 ``` The variable named `classVariable` is part of the class, common to all instances. Because of the way Python does search, it's available as a member of `self.classVariable`, as well as `SomeClass.classVariable`. The variable named `instanceVariable` is part of the instance (`self.`) and is unique to each instance. Note. There's a third kind, global, but that's not what you're asking about.
Is it fileList you're talking about? You have it as a class variable, to make it an instance variable you need to do: ``` self.fileList = {'files': [], 'dirs': []} ``` in you \_\_ init \_\_ function.
How come my class is behaving like a static class?
[ "", "python", "" ]