Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a python script that is a http-server: <http://paste2.org/p/89701>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level...
I cannot confirm your results, and your server is coded fishy. I whipped up my own server and do not have this problem either. Let's move the discussion to a simpler level: ``` import thread, socket, Queue connections = Queue.Queue() num_threads = 10 backlog = 10 def request(): while 1: conn = connection...
For the heck of it I also implemented an asynchronous version: ``` import socket, Queue, select class Request(object): def __init__(self, conn): self.conn = conn self.fileno = conn.fileno self.perform = self._perform().next def _perform(self): data = self.conn.recv(4048) ...
I’m stunned: weird problem with python and sockets + threads
[ "", "python", "multithreading", "apache", "sockets", "" ]
I used to use the standard mysql\_connect(), mysql\_query(), etc statements for doing MySQL stuff from PHP. Lately I've been switching over to using the wonderful MDB2 class. Along with it, I'm using prepared statements, so I don't have to worry about escaping my input and SQL injection attacks. However, there's one p...
This sounds like a problem with the MDB2 API fumbling PHP's duck typing semantics. Because the empty string in PHP is equivalent to NULL, MDB2 is probably mis-treating it as such. The ideal solution would be to find a workaround for it within it's API, but I'm not overly familiar with it. One thing that you should con...
Thanks to some of the answers, I realized that the problem may be in the MDB2 API, and not in the PHP or MYSQL commands themselves. Sure enough, I found this in the MDB2 FAQ: > * Why do empty strings end up as NULL in the database? Why do I get an NULL > not allowed in NOT NULL text fields > eventhough the default...
Empty string in not-null column in MySQL?
[ "", "php", "mysql", "mysqli", "nullable", "prepared-statement", "" ]
I want to find in a vector of Object pointers for a matching object. Here's a sample code to illustrate my problem: ``` class A { public: A(string a):_a(a) {} bool operator==(const A& p) { return p._a == _a; } private: string _a; }; vector<A*> va; va.push_back(new A("one")); va.push_back(n...
Use find\_if with a functor: ``` template <typename T> struct pointer_values_equal { const T* to_find; bool operator()(const T* other) const { return *to_find == *other; } }; // usage: void test(const vector<A*>& va) { A* to_find = new A("two"); pointer_values_equal<A> eq = { to_find...
Either use std::find\_if and provide a suitable predicate yourself, see other answers for an example of this. Or as an alternative have a look at [boost::ptr\_vector](http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_container.html), which provides transparent reference access to elements which are reall...
How to use find algorithm with a vector of pointers to objects in c++?
[ "", "c++", "algorithm", "stl", "pointers", "vector", "" ]
I am calling a SQL proc that has 3 OUTPUT params. After the call to the proc one of the params does not return a value when the other two do. Profiler shows that all 3 values are being returned. The params are declared as follows in the proc... ``` @UsrVariableID INT OUTPUT, @OrganisationName NVARCHAR(256) OUTPUT, @V...
With output parameters that have variable length data types (nvarchar, varchar, etc), I've found that being more explicit leads to better results. In the case you've posted, a type is not specified on the C# side. I would probably change things to look something like the following: ``` SqlParameter theOrganizationName...
You could try declaring the parameters first (then set the values), and see if this make a difference. ``` cm.Parameters.Add["@OrganisationName", SqlDbType.NVarChar, 256].Direction = ParameterDirection.Output cm.Parameters["@OrganisationName"].Value = name ``` But to me there doesn't look like anything wrong with wha...
Output Parameter not Returned from Stored Proc
[ "", "c#", ".net", "sql-server", "stored-procedures", "ado.net", "" ]
In my database, in one of the table I have a GUID column with allow nulls. I have a method with a Guid? parameter that inserts a new data row in the table. However when I say `myNewRow.myGuidColumn = myGuid` I get the following error: ``` Cannot implicitly convert type 'System.Guid?' to 'System.Guid'. ```
The ADO.NET API has some problems when it comes to handling nullable value types (i.e. it simply doesn't work correctly). We've had no end of issues with it, and so have arrived at the conclusion that it's best to manually set the value to null, e.g. ``` myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : ...
OK; how is myGuidColumn defined, and how is myGuid defined? If myGuid is `Guid?` and myGuidColumn is `Guid`, then the error is correct: you will need to use `myGuid.Value`, or `(Guid)myGuid` to get the value (which will throw if it is null), or perhaps `myGuid.GetValueOrDefault()` to return the zero guid if null. If ...
"Cannot implicitly convert type 'System.Guid?' to 'System.Guid'." - Nullable GUID
[ "", "c#", ".net", "sql-server", "guid", "nullable", "" ]
I have a custom class that implements `ICollection`, and this class is readonly, ie. `IsReadOnly` returns true (as opposed to using the `readonly` keyword), and all functions that would normally modify the data in the collection throw `InvalidOperationException`'s. Now, given such a construct, and a quick skim over th...
Yes this is an issue in some cases. Even though the collection is read only and cannot be changed, the objects the collection references are not read only. Thus if the clients use the SyncRoot to perform locking they will not be thread safe when modifying the objects referenced by the collection. I would recommend add...
I guess the issue would be if clients used your sync root to achieve locking of not only your collection, but something else. Supposed they cached the size of the collection - or maybe "what subset of this collection matches a predicate" - they would reasonably assume that they could use your SyncRoot to guard both you...
ICollection, readonly collections, and synchronisation. Is this right?
[ "", "c#", ".net-2.0", "" ]
How to, in C# round any value to 10 interval? For example, if I have 11, I want it to return 10, if I have 136, then I want it to return 140. I can easily do it by hand ``` return ((int)(number / 10)) * 10; ``` But I am looking for an builtin algorithm to do this job, something like Math.Round(). The reason why I wo...
There is no built-in function in the class library that will do this. The closest is [System.Math.Round()](http://msdn.microsoft.com/en-us/library/system.math.round.aspx) which is only for rounding numbers of types Decimal and Double to the nearest integer value. However, you can wrap your statement up in a extension m...
Use Math.Ceiling to always round up. ``` int number = 236; number = (int)(Math.Ceiling(number / 10.0d) * 10); ``` Modulus(%) gets the remainder, so you get: ``` // number = 236 + 10 - 6 ``` Put that into an extension method ``` public static int roundupbyten(this int i){ // return i + (10 - i % 10); <-- logic ...
Built in .Net algorithm to round value to the nearest 10 interval
[ "", "c#", "math", "rounding", "" ]
So... I used to think that when you accessed a file but specified the name without a path (CAISLog.csv in my case) that .NET would expect the file to reside at the same path as the running .exe. This works when I'm stepping through a solution (C# .NET2.\* VS2K5) but when I run the app in normal mode (Started by a Webs...
When an application (WinForms) starts up, the `Environment.CurrentDirectory` contains the path to the application folder (i.e. the folder that contains the .exe assembly). Using any of the File Dialogs, ex. `OpenFileDialog`, `SaveFileDialog`, etc. will cause the current directory to change (if a different folder was se...
It is based on the current working directory which may or may not be the same as where your application resides, especially if started from a different program or a shortcut with a different working directory. Rather than hard code the path, get the path to your program and use it. You can do this with something like ...
How does default/relative path resolution work in .NET?
[ "", "c#", "visual-studio", "file-io", ".net-2.0", "" ]
I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?
While the `Popen` answers are reasonable for the general case, I would recommend `win32api` for this specific case, if you want to do something useful with it: It goes something like this: ``` from win32com.client import Dispatch xl = Dispatch('Excel.Application') wb = xl.Workbooks.Open('C:\\Documents and Settings\\G...
or ``` os.system("start excel.exe <path/to/file>") ``` (presuming it's in the path, and you're on windows) and also on Windows, just `start <filename>` works, too - if it's an associated extension already (as xls would be)
How can I launch an instance of an application using Python?
[ "", "python", "scripting", "ipc", "" ]
I have been working on a childish little program: there are a bunch of little circles on the screen, of different colors and sizes. When a larger circle encounters a smaller circle it eats the smaller circle, and when a circle has eaten enough other circles it reproduces. It's kind of neat! However, the way I have it ...
Computers are usually single tasked, this means they can usually execute one instruction at a time per CPU or core. However, as you have noticed, your operation system (and other programs) appear to run many tasks at the same time. This is accomplished by splitting the work into processes, and each process can furthe...
the problem you have here can actually be solved without threads. What you need is a spatial data structure. a quad tree would be best, or if the field in which the spheres move is fixed (i assume it is) you could use a simple grid. Heres the idea. Divide the display area into a square grid where each cell is at leas...
How do I make for loops run side by side?
[ "", "java", "loops", "" ]
I need to find two adjacent repeating digits in a string and replace with a single one. How to do this in Java. Some examples: 123345 should be 12345 77433211 should be 74321
Probably a `replaceAll("(\\d)\\1+", "$1")` * `$` plays a special role in a replacing string, designating the first capturing group. * `+` allows for replacing as many identical number as possible `(\\d)\\1` would only replace them by pair: `777xx` => `77xx` (thank you [Ben Doom](https://stackoverflow.com/users/12267/b...
I finally did it myself. Those who are looking for the solution, this is how I did it: ``` import java.util.regex.*; public class RepetingDigits{ public static void main(String[] args) { String word = "77433211"; Pattern pattern = Pattern.compile("(\\d)\\1"); Matcher matcher = pattern.matc...
How to find two adjacent repeating digits and replace them with a single digit in Java?
[ "", "java", "regex", "string", "" ]
If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory? e.g. ``` vector<char> vc(100); // do some stuff with vc vc.resize(200); char* p = &vc[0]; // do stuff with *p ```
**Yes, that is a valid assumption (\*).** From the C++03 standard (23.2.4.1): > The elements of a vector are stored > contiguously, meaning that if v is a > vector where T is some > type other than bool, then it obeys > the identity &v[n] == &v[0] + n for > all 0 <= n < v.size(). (\*) ... but watch out for the array...
The C++03 standard added wording to make it clear that vector elements must be contiguous. C++03 23.2.4 Paragraph 1 contains the following language which is *not* in the C++98 standard document: > The elements of a `vector` are stored > contiguously, meaning that if `v` is a > `vector<T, Allocator>` where `T` is > so...
Is it safe to assume that STL vector storage is always contiguous?
[ "", "c++", "stl", "vector", "" ]
> **Possible Duplicate:** > [How to convert UNIX timestamp to DateTime and vice versa?](https://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa) I've got the following class: ``` [DataContractAttribute] public class TestClass { [DataMemberAttribute] public DateTime My...
Finishing what you posted, AND making it private seemed to work fine for me. ``` [DataContract] public class TestClass { private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); [IgnoreDataMember] public DateTime MyDateTime { get; set; } [DataMember(Name =...
``` private DateTime ConvertJsonStringToDateTime(string jsonTime) { if (!string.IsNullOrEmpty(jsonTime) && jsonTime.IndexOf("Date") > -1) { string milis = jsonTime.Substring(jsonTime.IndexOf("(") + 1); string sign = milis.IndexOf("+") > -1 ? "+" : "-"; ...
How to convert DateTime from JSON to C#?
[ "", "c#", "json", "serialization", "silverlight-2.0", "" ]
I have a table of data, and I allow people to add meta data to that table. I give them an interface that allows them to treat it as though they're adding extra columns to the table their data is stored in, but I'm actually storing the data in another table. ``` Data Table DataID Data Meta Table DataID Me...
You want to pivot each of your name-value pair rows in the MyTable... Try this sql: ``` DECLARE @Data TABLE ( DataID INT IDENTITY(1,1) PRIMARY KEY, Data VARCHAR(MAX) ) DECLARE @Meta TABLE ( DataID INT , MetaName VARCHAR(MAX), MetaData VARCHAR(MAX) ) INSERT INTO @Data ...
``` SELECT DataTable.Data AS Data, MetaTable.MetaData AS Date, MetaTable.MetaName AS Name FROM DataTable, MetaTable WHERE DataTable.DataID = MetaTable.DataID ``` You'll probably want to add an additional clause (AND Data = 'some value') to return the rows the user is interested in.
What SQL query or view will show "dynamic columns"
[ "", "sql", "database", "metadata", "dataview", "" ]
I am looking for lightweight messaging framework in Java. My task is to process events in a SEDA’s manner: I know that some stages of the processing could be completed quickly, and others not, and would like to decouple these stages of processing. Let’s say I have components A and B and processing engine (be this cont...
Do you need any kind of persistence (e.g. if your JVM dies in between processing thousands of messages) and do you need messages to traverse to any other JVMs? If its all in a single JVM and you don't need to worry about transactions, recovery or message loss if a JVM dies - then as Chris says above, Executors are fin...
*Really* lightweight? [Executors](http://java.sun.com/javase/6/docs/technotes/guides/concurrency/overview.html). :-) So you set up an executor (B, in your description), and A simply submits tasks to the executor.
Lightweight messaging (async invocations) in Java
[ "", "java", "messaging", "" ]
How can I launch an event that has accessors like this : ``` public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } ``` If it were a normal event I would launch i...
That event is just subscribing to and unsubscribing from another event. If you want your subscribers (and *only* your subscribers - not separate ones to the other event) to be invoked, you'll need to keep hold of your subscribers separately. For instance, you could change the code to something like: ``` private EventH...
I think you have events confused with delegates. Only the class exposing the event can raise it... Others can only subscribe-unsubscribe to it. If you are invoking the event from within the class declaring the event, it should work like a regular delegate. The best page I could find on [Events vs Delegates](http://blo...
Launch an event that has accessors
[ "", "c#", "events", "accessor", "" ]
I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g. ``` hashlib.sha256(str(user_id)+str(expiry_time)) hmac.new(str(random.randbits(256))) ``` (ignore for the moment that random.randbits() might not be cryptographically good). edit: I realise ...
Well, usually hash-functions (and cryptographic functions generally) work on bytes. The Python strings are basically byte-strings. If you want to compute the hash of some object you have to convert it to a string representation. Just make sure to apply the same operation later if you want to check if the hash is correc...
You can. However, for the HMAC, you actually want to store the key somewhere. Without the key, there is no way for you to verify the hash value later. :-)
arguments to cryptographic functions
[ "", "python", "cryptography", "" ]
I am creating an application in java which will be the part of an external application. My application contains a viewport which shows some polygons and stuff like that. The external application needs to get the image of the viewport in gif format. For that it calls a method in an interface (implemented by my applicati...
A byte array could be appropriate if you expect the GIFs to be small, but you might consider using an `OutputStream` so you can stream bits more efficiently. Even if today you just return a fully-populated `ByteArrayOutputStream`, this would allow you to change your implementation in future without affecting cilent co...
A more intuitive return type might be java.awt.Image. Here are some examples: <http://www.google.com/codesearch?q=java+gif+image&hl=en&btnG=Search+Code>
Returning a gif image from a method
[ "", "java", "image", "gif", "" ]
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?
``` import a_module print(a_module.__file__) ``` Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do: ``` import os path = os.path.abspath(a_module.__file__) ``` You can also try: ``` path = os.path.dirname(a_module.__file__) ``` To get the module's directo...
There is `inspect` module in python. ## [Official documentation](http://docs.python.org/library/inspect.html) > The inspect module provides several useful functions to help get > information about live objects such as modules, classes, methods, > functions, tracebacks, frame objects, and code objects. For example, > ...
How to retrieve a module's path?
[ "", "python", "module", "inotify", "" ]
``` a:3:{i:0;i:4;i:1;i:3;i:2;i:2;} ``` Am I right to say that this is an array of size 3 where the key value pairs are `0->4`, `1->3`, and `2->2`? If so, I find this representation awfully confusing. At first, I thought it was a listing of values (or the array contained `{0, 4, 1, 3, 2, 2}`), but I figured that the `...
``` $string="a:3:{i:0;i:4;i:1;i:3;i:2;i:2;}"; $array=unserialize($string); print_r($array); ``` outpts: ``` Array ( [0] => 4 [1] => 3 [2] => 2 ) ``` If think the point is that PHP does not differentiate between integer indexed arrays and string indexed hashtables. The serialization format can be used for...
Yes that's `array(4, 3, 2)` `a` for array, `i` for integer as key then value. You would have to count to get to a specific one, but PHP always deserialises the whole lot, so it has a count anyway. Edit: It's not too confusing when you get used to it, but it can be somewhat long-winded compared to, e.g. JSON > Note: ...
How do you interpret a serialized associative array in PHP and why was this serialization method chosen?
[ "", "php", "arrays", "serialization", "" ]
I need to store a url in a MySQL table. What's the best practice for defining a field that will hold a URL with an undetermined length?
> 1. [Lowest common denominator max URL length among popular web browsers: **2,083** (Internet Explorer)](https://web.archive.org/web/20060217120846/http://www.boutell.com/newfaq/misc/urllength.html) > 2. <http://dev.mysql.com/doc/refman/5.0/en/char.html> > *Values in VARCHAR columns are variable-length strings. ...
`VARCHAR(512)` (or similar) should be sufficient. However, since you don't really know the maximum length of the URLs in question, I might just go direct to `TEXT`. The danger with this is of course loss of efficiency due to `CLOB`s being far slower than a simple string datatype like `VARCHAR`.
Best database field type for a URL
[ "", "sql", "mysql", "database", "" ]
When copying large files using `shutil.copy()`, you get no indication of how the operation is progressing.. I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of `open().read()` and `.write()` to do the actual copyin...
Two things: * I would make the default block size a *lot* larger than 512. I would start with 16384 and perhaps more. * For modularity, it might be better to have the `copy_with_prog` function not output the progress bar itself, but call a callback function so the caller can decide how to display the progress. Perhap...
Overkill? Perhaps. But on almost any system, Linux, Mac, and With a quick wxWidgets install on Windows, you can have the real deal, with pause and cancel buttons in a gui setup. Macs ship with wxWidgets these days, and it's a common package on Linux. A single file is very quick (it will immediately finish and look bro...
How to copy a file in Python with a progress bar?
[ "", "python", "file-io", "" ]
I've got a script that dynamically calls and displays images from a directory, what would be the best way to paginate this? I'd like to be able to control the number of images that are displayed per page through a variable within the script. I'm thinking of using URL varriables (ie - <http://domain.com/page.php?page=1>...
pagination is the same concept with or without sql. you just need your basic variables, then you can create the content you want. here's some quasi-code: ``` $itemsPerPage = 5; $currentPage = isset($_GET['page']) ? $_GET['page'] : 1; $totalItems = getTotalItems(); $totalPages = ceil($totalItems / $itemsPerPage); fun...
This is a function I often use to do pagination. Hope it helps. ``` function paginate($page, $total, $per_page) { if(!is_numeric($page)) { $page = 1; } if(!is_numeric($per_page)) { $per_page = 10; } if($page > ceil($total / $per_page)) $page = 1; if($page == "" || $page == 0) { $page = 1; ...
PHP Dynamic Pagination Without SQL
[ "", "php", "pagination", "" ]
I'm *extremely new* to Java, and have mostly just been teaching myself as I go, so I've started building an applet. I'd like to make one that can select a file from the local disk and upload it as a multipart/form-data POST request but **with a progress bar**. Obviously the user has to grant permission to the Java appl...
I ended up stumbling across an open source Java uploader applet and found everything I needed to know within its code. Here are links to a blog post describing it as well as the source: [Article](http://panyasan.wordpress.com/2008/02/29/open-source-drag-drop-upload-java-applet-for-websites/) [Source Code](https://qo...
To check progress using HttpClient, wrap the MultipartRequestEntity around one that counts the bytes being sent. Wrapper is below: ``` import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.httpclient.methods.RequestEntity; public class CountingMultipartR...
File Upload with Java (with progress bar)
[ "", "java", "file-io", "upload", "progress-bar", "" ]
Is there an easy way to modify this code so that the target URL opens in the SAME window? ``` <a href="javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'','resizable,location,menubar,toolbar,scrollbars,status'));">click here</a>`` ```
The second parameter of *window.open()* is a string representing the name of the target window. Set it to: "\_self". ``` <a href="javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'_self','resizable,location,menubar,toolbar,scrollbars,status'));">click here</a> ``` **Side...
``` <script type="text/javascript"> window.open ('YourNewPage.htm','_self',false) </script> ``` see reference: <http://www.w3schools.com/jsref/met_win_open.asp>
Javascript: open new page in same window
[ "", "javascript", "window", "" ]
One thing I've run into a few times is a service class (like a JBoss service) that has gotten overly large due to helper inner classes. I've yet to find a good way to break the class out. These helpers are usually threads. Here's an example: ``` /** Asset service keeps track of the metadata about assets that live on o...
On bytecode level inner classes are just plain Java classes. Since the Java bytecode verifier does not allow access to private members, it generates synthetic accessor methods for each private field which you use. Also, in order to link the inner class with its enclosing instance, the compiler adds synthetic pointer to...
The line between encapsulation and separation can be difficult to walk. However, I think the main issue here is that you need some kind of solid interaction model to use as a basis of separating your classes. I think it's reasonable to have external helper utility classes which are used in many places, as long as they...
Large Inner classes and private variables
[ "", "java", "jboss", "class-design", "" ]
Ok I'm working on a little project at the moment, the Report expects an int but the ReportParameter class only lets me have a value that's a string or a string[] How can I pass an int? thanks dan
Still no answer to this one, ended up casting in the underlying stored procs.
You can call the method `GetReportParameters()` which will return a `ReportParameter[]` array. If you iterate through each parameter and look at its Type property it will indicate if it is an `int`. The Type property is an `enum` of type `ParameterTypeEnum` and would be `ParameterTypeEnum.Integer` for an `int`.
c# Reporting Services -- ReportParameter value that isn't a string
[ "", "c#", "asp.net", "reporting-services", "reportparameter", "" ]
I would like to access a class everywhere in my application, how can I do this? To make it more clear, I have a class somewhere that use some code. I have an other class that use the same code. I do not want to duplicate so I would like to call the same code in both place by using something. In php I would just includ...
The concept of global classes in C# is really just a simple matter of referencing the appropriate assembly containing the class. Once you have reference the needed assembly, you can refer to the class of choice either by it's fully qualified Type name, or by importing the namespace that contains the class. (**Concrete ...
Do you want to access the class or access an instance of the class from everywhere? You can either make it a static class - `public static class MyClass { }` - or you can use the [Singleton Pattern](http://en.wikipedia.org/wiki/Singleton_pattern). For the singleton pattern in its simplest form you can simply add a st...
How can I make a class global to the entire application?
[ "", "c#", ".net", "" ]
I have a number of generated .sql files that I want to run in succession. I'd like to run them from a SQL statement in a query (i.e. Query Analyzer/Server Management Studio). Is it possible to do something like this and if so what is the syntax for doing this? I'm hoping for something like: ``` exec 'c:\temp\file01...
use [xp\_cmdshell](http://msdn.microsoft.com/en-us/library/aa260689(SQL.80).aspx) and [sqlcmd](http://msdn.microsoft.com/en-us/library/ms166559.aspx) ``` EXEC xp_cmdshell 'sqlcmd -S ' + @DBServerName + ' -d ' + @DBName + ' -i ' + @FilePathName ```
Very helpful thanks, see also this link: [Execute SQL Server scripts](https://stackoverflow.com/questions/3523365/execute-sql-server-scripts?rq=1) for a similar example. To turn `xp_cmdshell` on and off see below: On ``` SET NOCOUNT ON EXEC master.dbo.sp_configure 'show advanced options', 1 RECONFIGURE EXEC maste...
Is it possible to execute a text file from SQL query?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
The deceptively simple foundation of dynamic code generation within a C/C++ framework has already been covered in [another question](https://stackoverflow.com/questions/45408/). Are there any gentle introductions into topic with code examples? My eyes are starting to bleed staring at highly intricate open source JIT c...
Well a pattern I've used in emulators goes something like this: ``` typedef void (*code_ptr)(); unsigned long instruction_pointer = entry_point; std::map<unsigned long, code_ptr> code_map; void execute_block() { code_ptr f; std::map<unsigned long, void *>::iterator it = code_map.find(instruction_pointer); ...
I'm not aware of any sources specifically related to JITs, but I imagine that it's pretty much like a normal compiler, only simpler if you aren't worried about performance. The easiest way is to start with a VM interpreter. Then, for each VM instruction, generate the assembly code that the interpreter would have execu...
Gentle introduction to JIT and dynamic compilation / code generation
[ "", "c++", "assembly", "code-generation", "" ]
In JSP I can reference a bean's property by using the tag ${object.property} Is there some way to deal with properties that might not exist? I have a JSP page that needs to deal with different types. Example: ``` public class Person { public String getName() } public class Employee extends Person { public flo...
Just use the EL empty operator IF it was a scoped attribute, unfortunately you'll have to go with surrounding your expression using employee.salary with <c:catch>: ``` <c:catch var="err"> <c:out value="${employee.salary}"/> </c:catch> ``` If you really need *instanceof*, you might consider a custom tag.
If you want the class, just use `${person.class}`. You can also use `${person.class.name eq 'my.package.PersonClass'}` You can also use the "default" on c:out. ``` <c:out value='${person.salary}' default="Null Value" /> ```
JSP bean tag for property that might not exist
[ "", "java", "jsp", "jsp-tags", "javabeans", "" ]
I write a singleton c++ in the follow way: ``` class A { private: static A* m_pA; A(); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); } } A* A::GetInstance() { if (m_...
You can avoid needing to delete it by using a static object like this: ``` if(m_pA == 0) { static A static_instance; m_pA = &static_instance; } ```
Why does everybody want to return a singleton as a pointer? Return it as a reference seems much more logical! You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don't know (or can't guarantee) nobody has a reference (in your case via a pointer) ...
Can any one provide me a sample of Singleton in c++?
[ "", "c++", "design-patterns", "singleton", "" ]
Are there any tricks for preventing SQL Server from entitizing chars like &, <, and >? I'm trying to output a URL in my XML file but SQL wants to replace any '&' with '`&amp;`' Take the following query: ``` SELECT 'http://foosite.com/' + RTRIM(li.imageStore) + '/ImageStore.dll?id=' + RTRIM(li.imageID) ...
What SQL Server generates is correct. What you expect to see is not well-formed XML. The reason is that `&` character signifies the start of an entity reference, such as `&amp;`. See the [XML specification](http://www.w3.org/TR/REC-xml/#sec-references) for more information. When your XML parser parses this string out ...
There are situations where a person may not want well formed XML - the one I (and perhaps the original poster) encountered was using the For XML Path technique to return a single field list of 'child' items via a recursive query. More information on this technique is here (specifically in the 'The blackbox XML methods'...
How to preserve an ampersand (&) while using FOR XML PATH on SQL 2005
[ "", "sql", "xml", "sql-server-2005", "" ]
What is a doubly linked list's remove method?
The same algorithm that [Bill the Lizard](https://stackoverflow.com/questions/270950/linkedlist-remove-method#270962) said, but in a graphical way :-) [![Remove From Linked List](https://i.stack.imgur.com/dbGK6.gif)](https://i.stack.imgur.com/dbGK6.gif) (source: [jaffasoft.co.uk](http://www.jaffasoft.co.uk/feature/l...
The general algorithm is as follows: * Find the node to remove.* node.previous.next = node.next* node.next.previous = node.previous* node.previous = null* node.next = null* Dispose of node if you're in a non-GC environment You have to check the previous and next nodes for null to see if you're removing the head or th...
LinkedList remove method
[ "", "java", "data-structures", "linked-list", "" ]
I have a lot of buttons and by clicking on different button, different image and text would appear. I can achieve what I want, but the code is just so long and it seems very repetitive. For example: ``` var aaClick = false; $("aa").observe('click', function() { unclick(); $('characterPic').write...
Build it all into a function where you can simply pass it the names of the DIVs you want to register. As long are you are consistent with your .jpg names, it should work. ``` var clicks = [] function regEvents(divName) { $(divName).observe('click', function() { unclick(divName); $('characterPic').w...
Event delegation. Give all your buttons a class (eg `yourButtonClass`), then... ``` var clicks = []; $$('.yourButtonClass').each(function(button) { clicks.push(button.id); }); $(document).observe('click', function(e) { // If your click registered on an element contained by the button, this comes in handy... ...
Shorten the code for a lot of buttons in Prototype
[ "", "javascript", "button", "prototypejs", "mouseevent", "" ]
I find myself writing code that looks like this a lot: ``` set<int> affected_items; while (string code = GetKeyCodeFromSomewhere()) { if (code == "some constant" || code == "some other constant") { affected_items.insert(some_constant_id); } else if (code == "yet another constant" || code == "the consta...
Since you don't seem to care about the actual values in the set you could replace it with setting bits in an int. You can also replace the linear time search logic with log time search logic. Here's the final code: ``` // Ahead of time you build a static map from your strings to bit values. std::map< std::string, int ...
One approach is to maintain a map from strings to booleans. The main logic can start with something like: ``` if(done[code]) continue; done[code] = true; ``` Then you can perform the appropriate action as soon as you identify the code. Another approach is to store something executable (object, function pointer, ...
Checking lists and running handlers
[ "", "c++", "c", "idioms", "" ]
In C++, a function's signature depends partly on whether or not it's const. This means that a class can have two member functions with identical signatures except that one is const and the other is not. If you have a class like this, then the compiler will decide which function to call based on the object you call it o...
This really only makes sense when the member function returns a pointer or a reference to a data member of your class (or a member of a member, or a member of a member of a member, ... etc.). Generally returning non-const pointers or references to data members is frowned upon, but sometimes it is reasonable, or simply ...
It's there so you can make the compiler enforce whether you return a const object or a regular one, and still maintain the same method signature. There's an in-depth explanation at [Const Correctness](https://isocpp.org/wiki/faq/const-correctness#const-overloading).
What is the use of const overloading in C++?
[ "", "c++", "function", "constants", "overloading", "" ]
I'm wondering what the best way is to have a "if all else fails catch it". I mean, you're handling as much exceptions as possible in your application, but still there are bound to be bugs, so I need to have something that catches all unhandled exceptions so I can collect information and store them in a database or sub...
I have just played with AppDomain's UnhandledException behavior, (this is the last stage the unhandled exception is registered at) Yes, after processing the event handlers your application will be terminated and the nasty "... program stopped working dialog" shown. :) You *still* can avoid that. Check out: ``` clas...
In ASP.NET, you use the `Application_Error` function in the `Global.asax` file. In WinForms, you use the `MyApplication_UnhandledException` in the `ApplicationEvents` file Both of these functions are called if an unhandled exception occurs in your code. You can log the exception and present a nice message to the user...
.NET - What's the best way to implement a "catch all exceptions handler"
[ "", "c#", ".net", "exception", "" ]
From the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map): ``` [1,4,9].map(Math.sqrt) ``` will yield: ``` [1,2,3] ``` Why then does this: ``` ['1','2','3'].map(parseInt) ``` yield this: ``` [1, NaN, NaN] ``` I have tested in Firefox 3.0.1 an...
The callback function in `Array.map` has *three* parameters: From the same [Mozilla page](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map) that you linked to: > callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being tra...
`map` is passing along a 2nd argument, which is (in many of the cases) messing up `parseInt`'s radix parameter. If you're using underscore you can do: `['10','1','100'].map(_.partial(parseInt, _, 10))` Or without underscore: `['10','1','100'].map(function(x) { return parseInt(x, 10); });`
Why does parseInt yield NaN with Array#map?
[ "", "javascript", "" ]
What are the best algorithms for sorting data in C#? Is there one sorting algorithm that can handle 80% of sorts well? Please give code examples if applicable.
Check out this site: [Sorting Comparisons with Animations](http://www.sorting-algorithms.com/) Short answer: Quick Sort Longer answer: The above site will show you the strengths and weaknesses of each algorithm with some nifty animations. The short answer is there is no best all around sort (but you knew that since ...
What are you trying to sort? Is there any reason not to use: ``` List<T>.Sort() ? ``` I'm sure this uses QuickSort and you don't have to worry about making any coding errors. You can implement IComparable to change what you want to sort on. If all your data doesn't fit in memory... well the you're off to the races w...
Best sorting algorithms for C# / .NET in different scenarios
[ "", "c#", ".net", "algorithm", "sorting", "" ]
I've been trying to find a free database creator for mac os, and i'm not being able to find any. Anyone know of a free one i could download? EDIT: I need that the application generate the sql (mysql in this case) also :) ty
[SQL Designer](http://ondras.zarovi.cz/sql/demo/) is web-based. There's also more options at [this question](https://stackoverflow.com/questions/30474/database-schema-diagram-design-tool).
I think the [Entity modeling stuff in XCode](http://developer.apple.com/documentation/Cocoa/Conceptual/CoreData/Articles/cdBasics.html#//apple_ref/doc/uid/TP40001650) might be of us to you...
DB sketcher for MacOS?
[ "", "sql", "database", "database-design", "ddl", "" ]
I've got a project which requires a fairly complicated process and I want to make sure I know the best way to do this. I'm using ASP.net C# with Adobe Flex 3. The app server is Mosso (cloud server) and the file storage server is Amazon S3. The existing site can be viewed at [NoiseTrade.com](https://www.noisetrade.com) ...
The bit about updating the zip but not having the temporary files if the user adds or removes a track leads me to suspect that you want to build zips containing multiple tracks, possibly complete albums. If this is incorrect and you're just putting a single mp3 into each zip, then StingyJack is right and you'll probabl...
MP3's are compressed. Why bother zipping them?
Best process for auto-zipping of multiple MP3s
[ "", "c#", "asp.net", "zip", "amazon-s3", "" ]
I'm developing a kind of an exchange format between instances of an application so that user could save information to file and restore it later. The whole 'exchange format' is a single class that gets serialized and written to disk. How would you suggest to store graphical/sound information inside that class? I'd lik...
You might keep your resources stored in the class as byte[] arrays. Using ByteArrayInputStream and ByteArrayOutputStream you are able to wrap the arrays as streams and use them to store and retrieve resources.
\*\* me \*\* how about more details on your case? the "best" method usually depends on the particular application/use. does the image/sound come from files? from a stream? Is each instance of the class expected to store separate images? Or can an image be shared between different instances? **gsmd** > images come fr...
The best way of storing an image/sound inside a class?
[ "", "java", "serialization", "image", "audio", "persistence", "" ]
I'm looking for (simple) examples of problems for which JMS is a good solution, and also reasons why JMS is a good solution in these cases. In the past I've simply used the database as a means of passing messages from A to B when the message cannot necessarily be processed by B immediately. A hypothetical example of s...
JMS and messaging is really about 2 totally different things. * publish and subscribe (sending a message to as many consumers as are interested - a bit like sending an email to a mailing list, the sender does not need to know who is subscribed * high performance reliable load balancing (message queues) See more info ...
In my opinion JMS and other message-based systems are intended to solve problems that need: * **Asynchronous** communications : An application need to notify another that an event has occurred with no need to wait for a response. * **Reliability**. Ensure once-and-only-once message delivery. With your DB approach you ...
what is JMS good for?
[ "", "java", "jms", "messaging", "" ]
I have essentially a survey that is shown, and people answer questions a lot like a test, and there are different paths, it is pretty easy so far, but i wanted to make it more dynamic, so that i can have a generic rule that is for the test with all the paths, to make the evaluator easier to work with currently i just a...
This doesn't have to be complicated: you're most of the way already, since your and elements effectively implement an AND-type rule. I would introduce an element that can hold and elements. In your could, you could have: * A RuleBase class, with a "public abstract bool Evaluate()" method * TrueRule, FalseRule and OrR...
If you use a proper Rule Engine that supports inferencing it would be more efficient and extensible. Take a look at <http://www.flexrule.com> which is a flexible, extensible rule engine that supports three types of rule. Procedural, Inference and Rule-Flow rules can be externalized from your application and get execut...
Boolean logic rule evaluator
[ "", "c#", "xml", "logic", "boolean", "rule-engine", "" ]
I don't think this is possible, but if is then I need it :) I have a auto-generated proxy file from the wsdl.exe command line tool by Visual Studio 2008. The proxy output is partial classes. I want to override the default constructor that is generated. I would rather not modify the code since it is auto-generated. I...
This is not possible. Partial classes are essentially parts of the same class; no method can be defined twice or overridden, and that includes the constructor. You could call a method in the constructor, and only implement it in the other part file.
I had a similar problem, with my generated code being created by a DBML file (I'm using Linq-to-SQL classes). In the generated class it calls a partial void called OnCreated() at the end of the constructor. Long story short, if you want to keep the important constructor stuff the generated class does for you (which y...
Override Default Constructor of Partial Class with Another Partial Class
[ "", "c#", "web-services", "wsdl", "overriding", "partial-classes", "" ]
I have two objects, let's call them **`Input`** and **`Output`** **`Input`** has properties *`Input_ID`*, *`Label`*, and *`Input_Amt`* **`Output`** has properties *`Output_ID`* and *`Output_Amt`* I want to perform the equivalent SQL statement in LINQ: ``` SELECT Label, Sum(Added_Amount) as Amount FROM (SELECT ...
Okay, now that I understand what's going on a bit better, the main problem is that you haven't got the equivalent of the ISNULL bit. Try this instead: ``` var InnerQuery = from i in input join o in output on i.Input_ID equals o.Output_ID into joined from leftjoin in j...
Which LINQ provider is this actually using? Are you actually talking to a database, or just working in-process? If you're using LINQ to SQL, you can turn the log on to see what SQL is being generated. I'm sure that InnerQuery itself won't be null - how are you examining the output?
How can I perform a nested Join, Add, and Group in LINQ?
[ "", "c#", "linq", "" ]
How can I get a list of the IP addresses or host names from a local network easily in Python? It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow. **Edit:** By local I mean all **active** addresses within a local network, such as `192.168.xxx.xxx`. So, if the IP addr...
If by "local" you mean on the same network segment, then you have to perform the following steps: 1. Determine your own IP address 2. Determine your own netmask 3. Determine the network range 4. Scan all the addresses (except the lowest, which is your network address and the highest, which is your broadcast address). ...
**Update**: The script is now located on [github](http://github.com/bwaldvogel/neighbourhood). I wrote a [small python script](https://github.com/bwaldvogel/neighbourhood/blob/master/neighbourhood.py), that leverages [scapy](http://www.secdev.org/projects/scapy/)'s `arping()`.
List of IP addresses/hostnames from local network in Python
[ "", "python", "networking", "" ]
What is the best way to allow a team of programmers to use Netbeans, Eclipse and IntelliJ on the same project, thus eliminating the "which IDE is better" question. Which files should or should not be checked into source code control?
I think the best way is to make the build process independent of IDE. This means that your project should not rely on any IDE-specific files to build, but rather use an external build system, like [Apache Maven](http://maven.apache.org/), [Apache Ant](http://ant.apache.org), or even make or custom scripts. Maven is sup...
Well, that's a pretty self-answering question. The files to not check into source control are files that have to do with the IDEs themselves. Leave it to the developers to generate these files. If you use Maven, it can generate the files such as Eclipse's `.project` and `.classpath` for you. Eclipse in general is ve...
Multi-IDE Support in Java for one Team
[ "", "java", "eclipse", "ide", "netbeans", "intellij-idea", "" ]
I have a big lump of binary data in a char[] array which I need to interpret as an array of packed 6-bit values. I *could* sit down and write some code to do this but I'm thinking there has to be a good extant class or function somebody has written already. What I need is something like: ``` int get_bits(char* data,...
This may not work for sizes greater than 8, depending on endian system. It's basically what Marco posted, though I'm not entirely sure why he'd gather one bit at a time. ``` int get_bits(char* data, unsigned int bitOffset, unsigned int numBits) { numBits = pow(2,numBits) - 1; //this will only work up to 32 bits, o...
[Boost.DynamicBitset](http://www.boost.org/doc/libs/release/libs/dynamic_bitset/dynamic_bitset.html) - try it.
C/C++ Code to treat a character array as a bitstream
[ "", "c++", "bit-manipulation", "extract", "" ]
Currently I have an application that receives an uploaded file from my web application. I now need to transfer that file to a file server which happens to be located on the same network (however this might not always be the case). I was attempting to use the webclient class in C# .NET. ``` string filePath = "C:\\...
Just use ``` File.Copy(filepath, "\\\\192.168.1.28\\Files"); ``` A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web. The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it...
``` namespace FileUpload { public partial class Form1 : Form { string fileName = ""; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string path = ""; OpenFileDialog fDialog = new OpenFileDialog(); fDialog.Title...
Uploading files to file server using webclient class
[ "", "c#", "file-upload", "webclient", "fileserver", "" ]
My application uses loads of Java threads. I am looking for a reliable understanding how the JVM (version 5 and 6) maps the Java threads to underlying Windows threads. I know there is a document for mapping to Solaris threads, but not Windows. Why doesn't Sun publish this information? I want to know if there's a 1:1 ...
Don't have a document for you, but from the Threads column in the task-manager you can pretty reliably guess that it maps 1:1 to native threads (you need to enable the Threads column in the task manager first). Oh, almost forgot, you can download the jdk src [here](https://jdk6.dev.java.net/) and look yourself.
The mapping is platform-dependent, however I found an interesting [comparison](http://www2.sys-con.com/itsg/virtualcd/Java/archives/0306/gal/index.html) between platform threads for the vm (although probably a bit old). The bottom line is: you don't need to know. What you probably are more interested is to know about [...
How does the Sun JVM map Java threads to Windows threads?
[ "", "java", "windows", "multithreading", "jvm", "" ]
Lots of frameworks let me expose an ejb as a webservice. But then 2 months after publishing the initial service I need to change the ejb or any part of its interface. I still have clients that need to access the old interface, so I obviously need to have 2 webservices with different signatures. Anyone have any sugges...
I don't think, you need any additional frameworks to do this. Java EE lets you directly expose the EJB as a web service (since [EJB 2.1](http://www.jcp.org/en/jsr/detail?id=153); see [example for J2EE 1.4](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Session3.html#wp79822)), but with EE 5 it's even simpler: ``` @Web...
Ok here goes; it seems like dozer.sourceforge.net is an acceptable starting-point for doing the grunt work of copying data between two parallel structures. I suppose a lot of web frameworks can generate client proxies that can be re-used in a server context to maintain compatibility.
How to expose an EJB as a webservice that will later let me keep client compatibility when ejb changes?
[ "", "java", "web-services", "" ]
the WPF Popup control is nice, but somewhat limited in my opinion. is there a way to "drag" a popup around when it is opened (like with the DragMove() method of windows)? can this be done without big problems or do i have to write a substitute for the popup class myself? thanks
Here's a simple solution using a Thumb. * Subclass Popup in XAML and codebehind * Add a Thumb with width/height set to 0 (this could also be done in XAML) * Listen for MouseDown events on the Popup and raise the same event on the Thumb * Move popup on DragDelta XAML: ``` <Popup x:Class="PopupTest.DraggablePopup" ......
There is no DragMove for PopUp. Just a small work around, there is lot of improvements you can add to this. ``` <Popup x:Name="pop" IsOpen="True" Height="200" Placement="AbsolutePoint" Width="200"> <Rectangle Stretch="Fill" Fill="Red"/> </Popup> ``` In the code behind , add this mousemove event ``` ...
Drag WPF Popup control
[ "", "c#", ".net", "wpf", "xaml", "popup", "" ]
How can I create 7-Zip archives from my C# console application? I need to be able to extract the archives using the regular, widely available [7-Zip](http://www.7-zip.org/) program. --- ## Here are my results with the examples provided as answers to this question * "Shelling out" to 7z.exe - this is the simplest and...
If you can guarantee the 7-zip app will be installed (and in the path) on all target machines, you can offload by calling the command line app 7z. Not the most elegant solution but it is the least work.
[EggCafe 7Zip cookie example](http://www.eggheadcafe.com/tutorials/aspnet/064b41e4-60bc-4d35-9136-368603bcc27a/7zip-lzma-inmemory-com.aspx) This is an example (zipping cookie) with the DLL of 7Zip. [CodePlex Wrapper](http://www.codeplex.com/7zsharp) This is an open source project that warp zipping function of 7z. [7Z...
How do I create 7-Zip archives with .NET?
[ "", "c#", ".net", "compression", "7zip", "" ]
There is this example code, but then it starts talking about millisecond / nanosecond problems. The same question is on MSDN, *[Seconds since the Unix epoch in C#](https://learn.microsoft.com/archive/blogs/brada/seconds-since-the-unix-epoch-in-c)*. This is what I've got so far: ``` public Double CreatedEpoch { get...
Here's what you need: ``` public static DateTime UnixTimeStampToDateTime( double unixTimeStamp ) { // Unix timestamp is seconds past epoch DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime(); return dateTime; } ``` O...
The [latest version of .NET (v4.6)](http://www.visualstudio.com/en-us/news/vs2015-preview-vs#Net) has added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds. * Unix time in seconds to UTC `DateTimeOffset`: ``` DateTimeOffset dateTimeOff...
How can I convert a Unix timestamp to DateTime and vice versa?
[ "", "c#", "datetime", "unix", "epoch", "data-conversion", "" ]
I have this doubt, I've searched the web and the answers seem to be diversified. Is it better to use mysql\_pconnect over mysql\_connect when connecting to a database via PHP? I read that pconnect scales much better, but on the other hand, being a persistent connection... having 10 000 connections at the same time, all...
Persistent connections should be unnecessary for MySQL. In other databases (such as Oracle), making a connection is expensive and time-consuming, so if you can re-use a connection it's a big win. But those brands of database offer connection pooling, which solves the problem in a better way. Making a connection to a M...
Basically you have to balance the cost of creating connections versus keeping connections. Even though MySQL is very fast at setting up a new connection, it still costs -- in thread setup time, and in TCP/IP setup time from your web server. This is noticeable on a high-enough traffic site. Unfortunately, PHP does not h...
mysql_connect VS mysql_pconnect
[ "", "php", "mysql", "mysql-connect", "mysql-pconnect", "" ]
Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop. ``` i=1 while (i>0): x_past = x_present j=0 while(j<3): value=0 k=0 while(k<3): if(k!=j): ...
Yes, I think the answers here show your problem. Just to try and clarify a little bit. You're referencing a list, so when the list changes any reference to that list will reflect that change. To demonstrate: ``` >>> x_present = [4,5,6] >>> >>> x_past = x_present >>> >>> x_past [4, 5, 6] >>> >>> x_present.append(7) >>...
What are x\_past and x\_present? I don't know much Python, but from a .NET/Java perspective, if they're references to some data structure (a map or whatever) then making them references to the same object (as you do at the start) will mean that any changes made through one variable will be visible through the other. It...
Python - one variable equals another variable when it shouldn't
[ "", "python", "variables", "" ]
How to set internationalization to a `DateTimepicker` or `Calendar WinForm` control in .Net when the desire culture is different to the one installed in the PC?
It doesn't seem to be possible to change the culture. See this [KB article](http://support.microsoft.com/Default.aspx?scid=kb%3ben-us%3b889834&x=18&y=19).
Based on previous solution, I think the better is: ``` dateTimePicker.Format = DateTimePickerFormat.Custom; dateTimePicker.CustomFormat = Application.CurrentCulture.DateTimeFormat.ShortDatePattern; ```
How to change culture to a DateTimepicker or calendar control in .Net
[ "", "c#", ".net", "internationalization", "datetimepicker", "culture", "" ]
I am very familiar with the Command pattern, but I don't yet understand the difference in theory between a Functor and a command. In particular, I am thinking of Java implementations. Both are basically programming "verbs" represented as objects. However, in the case of functors, as I have seen from some examples anony...
A functor is a 'syntax level' concept - it packages up code in an object that can be treated syntactically like a function pointer - i.e. it can be 'called' by putting parameter list in brackets after it. In C++ you could make a class a functor by overriding operator(). A Command in the command pattern is an object th...
A functor is an implementation, a way of making an object behave like a function. The 'Command Pattern' is a design pattern. The functor is one way to implement the 'Command Pattern'.
What is the difference between a Functor and the Command pattern?
[ "", "java", "design-patterns", "oop", "theory", "functor", "" ]
Quick add on requirement in our project. A field in our DB to hold a phone number is set to only allow 10 characters. So, if I get passed "(913)-444-5555" or anything else, is there a quick way to run a string through some kind of special replace function that I can pass it a set of characters to allow? Regex?
Definitely regex: ``` string CleanPhone(string phone) { Regex digitsOnly = new Regex(@"[^\d]"); return digitsOnly.Replace(phone, ""); } ``` or within a class to avoid re-creating the regex all the time: ``` private static Regex digitsOnly = new Regex(@"[^\d]"); public static string CleanPhone(string p...
You can do it easily with regex: ``` string subject = "(913)-444-5555"; string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555" ```
Replace non-numeric with empty string
[ "", "c#", "regex", "string", "phone-number", "" ]
Why is using '\*' to build a view bad ? Suppose that you have a complex join and all fields may be used somewhere. Then you just have to chose fields needed. ``` SELECT field1, field2 FROM aview WHERE ... ``` The view "aview" could be `SELECT table1.*, table2.* ... FROM table1 INNER JOIN table2 ...` We have a prob...
I don't think there's much in software that is "just bad", but there's plenty of stuff that is misused in bad ways :-) The example you give is a reason why \* might not give you what you expect, and I think there are others. For example, if the underlying tables change, maybe columns are added or removed, a view that ...
Although many of the comments here are very good and reference one common problem of using wildcards in queries, such as causing errors or different results if the underlying tables change, another issue that hasn't been covered is optimization. A query that pulls every column of a table tends to not be quite as effici...
Why is using '*' to build a view bad?
[ "", "sql", "view", "" ]
ShellExecute() allows me to perform simple shell tasks, allowing the system to take care of opening or printing files. I want to take a similar approach to sending an email attachment programmatically. I don't want to manipulate Outlook directly, since I don't want to assume which email client the user uses by default...
This is my MAPI solution: ``` #include <tchar.h> #include <windows.h> #include <mapi.h> #include <mapix.h> int _tmain( int argc, wchar_t *argv[] ) { HMODULE hMapiModule = LoadLibrary( _T( "mapi32.dll" ) ); if ( hMapiModule != NULL ) { LPMAPIINITIALIZE lpfnMAPIInitialize = NULL; LPMAPIUNIN...
You can use a standard "mailto:" command in windows shell. It will run the default mail client.
How do I programmatically send an email in the same way that I can "Send To Mail Recipient" in Windows Explorer?
[ "", "c++", "windows", "email", "shell", "" ]
I know there is a `WeakHashMap` in `java.util`, but since it uses `WeakReference`s for everything, which is only referenced by this `Map`, referenced objects will get lost on the next GC cycle. So it's nearly useless if you want to cache random data, which is very likely to be requested again without being Hard-linked ...
Edit (Aug. 2012): It turns out that currently the best solution are probably Guava 13.0's `Cache` classes, explained on [Guava's Wiki](https://github.com/google/guava/wiki/CachesExplained) - that's what I'm going to use. It even supports building a `SoftHashMap` (see `CacheBuilder.newBuilder().softKeys()`), but it is ...
I am familiar with two libraries that offer a SoftHashMap implementation: 1. [Apache Commons](http://commons.apache.org/collections/): org.apache.commons.collections.map.ReferenceMap 2. [Google Collections](http://google-collections.googlecode.com/): com.google.common.collect.ReferenceMap
Is there a SoftHashMap in Java?
[ "", "java", "hashmap", "weak-references", "soft-references", "" ]
I need to do a date comparison in Mysql without taking into account the time component i.e. i need to convert '2008-11-05 14:30:00' to '2008-11-05' Currently i am doing this: ``` SELECT from_days(to_days(my_date)) ``` Is there a proper way of doing this?
Yes, use the [date](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date) function: ``` SELECT date(my_date) ```
`select date(somedate)` is the most common. If you need to accommodate other formats, you can use: ``` SELECT DATE_FORMAT(your_date, '%Y-%m-%d'); ```
Mysql strip time component from datetime
[ "", "sql", "mysql", "datetime", "" ]
I'm writing code to do Xml serialization. With below function. ``` public static string SerializeToXml(object obj) { XmlSerializer serializer = new XmlSerializer(obj.GetType()); using (StringWriter writer = new StringWriter()) { serializer.Serialize(writer, obj); return writer.ToString(); ...
During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate. You can make your constructor `private` or `internal` if you want, just so...
This is a limitation of `XmlSerializer`. Note that `BinaryFormatter` and `DataContractSerializer` *do not* require this - they can create an uninitialized object out of the ether and initialize it during deserialization. Since you are using xml, you might consider using `DataContractSerializer` and marking your class ...
Why XML-Serializable class need a parameterless constructor
[ "", "c#", ".net", "xml-serialization", "" ]
We use GUIDs for primary key, which you know is clustered by default. When inserting a new row into a table it is inserted at a random page in the table (because GUIDs are random). This has a measurable performance impact because the DB will split data pages all the time (fragmentation). But the main reason I what a s...
It should be possible to create a sequential GUID in c# or vb.net using an API call to UuidCreateSequential. The API declaration (C#) below has been taken from [Pinvoke.net](http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html) where you can also find a full example of how to call the function. ``` [Dl...
**Update 2018:** Also [check my other answer](https://stackoverflow.com/a/49256827/66629) This is how NHibernate generate sequantial IDs: [NHibernate.Id.GuidCombGenerator](https://github.com/nhibernate/nhibernate-core/blob/5e71e83ac45439239b9028e6e87d1a8466aba551/src/NHibernate/Id/GuidCombGenerator.cs) ``` /// <summ...
Is there a .NET equivalent to SQL Server's newsequentialid()
[ "", "c#", ".net", "sql-server", "" ]
I'm trying to find a way to determine how many parameters a constructor has. Now I've built one constructor with no parameters and 1 constructor with 4 parameters. Is there, in C#, a way to find out how many parameters a used or given constructor has? Thing is, I'm using a third constructor to read log files. These ...
You should look at the System.Reflection Namespace. More specifically, you can get a list of the constructors of a class with: ``` System.Type.GetType("MYClassName").GetConstructors() ```
It sounds as if you need to re think your code a bit. From your description, having to dynamically determine the number of arguments in a constructor sounds a bit hairy. You might consider a factory design pattern since the type of object created is determined at runtime. If I misunderstand your problem then using refl...
How to find amount of parameters in a constructor
[ "", "c#", "visual-studio-2008", "constructor", "" ]
I am trying to write a stored procedure which selects columns from a table and adds 2 extra columns to the ResultSet. These 2 extra columns are the result of conversions on a field in the table which is a Datetime field. The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S' The 2 additional field...
If dt is your datetime column, then For 1: ``` SUBSTRING(CONVERT(varchar, dt, 13), 1, 2) + UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3)) ``` For 2: ``` SUBSTRING(CONVERT(varchar, dt, 100), 13, 2) + SUBSTRING(CONVERT(varchar, dt, 100), 16, 3) ```
Use DATENAME and wrap the logic in a Function, not a Stored Proc ``` declare @myTime as DateTime set @myTime = GETDATE() select @myTime select DATENAME(day, @myTime) + SUBSTRING(UPPER(DATENAME(month, @myTime)), 0,4) ``` Returns "14OCT" Try not to use any Character / String based operations if possible when workin...
Custom Date/Time formatting in SQL Server
[ "", "sql", "sql-server", "datetime", "stored-procedures", "sql-convert", "" ]
I'm looking for a way to sequentially number rows in a *result set* (not a table). In essence, I'm starting with a query like the following: ``` SELECT id, name FROM people WHERE name = 'Spiewak' ``` The `id`s are obviously not a true sequence (e.g. `1, 2, 3, 4`). What I need is another column in the result set which...
To have a meaningful row number you need to order your results. Then you can do something like this: ``` SELECT id, name , (SELECT COUNT(*) FROM people p2 WHERE name='Spiewak' AND p2.id <= p1.id) AS RowNumber FROM people p1 WHERE name = 'Spiewak' ORDER BY id ``` Note that the WHERE clause of the sub query needs t...
AFAIK, there's no "standard" way. MS SQL Server has row\_number(), which MySQL has not. The simplest way to do this in MySQL is `SELECT a.*, @num := @num + 1 b from test a, (SELECT @num := 0) d;` Source: comments in <http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/>
Pure-SQL Technique for Auto-Numbering Rows in Result Set
[ "", "sql", "mysql", "" ]
this is my first question here so I hope I can articulate it well and hopefully it won't be too mind-numbingly easy. I have the following class *SubSim* which extends *Sim*, which is extending *MainSim*. In a completely separate class (and library as well) I need to check if an object being passed through is a type of...
There are 4 related standard ways: ``` sim is MainSim; (sim as MainSim) != null; sim.GetType().IsSubclassOf(typeof(MainSim)); typeof(MainSim).IsAssignableFrom(sim.GetType()); ``` You can also create a recursive method: ``` bool IsMainSimType(Type t) { if (t == typeof(MainSim)) return true; if (t == typeof(obj...
``` if (sim is MainSim) ``` is all you need. "is" looks up the inheritance tree.
BaseType of a Basetype
[ "", "c#", "" ]
I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in produc...
AFAIK an SQLITE database is just a file. To check if the database exists, check for file existence. When you open a SQLITE database it will automatically create one if the file that backs it up is not in place. If you try and open a file as a sqlite3 database that is NOT a database, you will get this: "sqlite3.Datab...
Don't make this more complex than it needs to be. The big, independent databases have complex setup and configuration requirements. SQLite is just a file you access with SQL, it's much simpler. Do the following. 1. Add a table to your database for "Components" or "Versions" or "Configuration" or "Release" or somethin...
Using SQLite in a Python program
[ "", "python", "exception", "sqlite", "" ]
Simply moving the file to `~/.Trash/` will not work, as if the file os on an external drive, it will move the file to the main system drive.. Also, there are other conditions, like files on external drives get moved to `/Volumes/.Trash/501/` (or whatever the current user's ID is) Given a file or folder path, what is ...
Alternatively, if you're on OS X 10.5, you could use Scripting Bridge to delete files via the Finder. I've done this in Ruby code [here](http://osx-trash.rubyforge.org/git?p=osx-trash.git;a=blob;f=bin/trash;h=26911131eacafd659b4d760bda1bd4c99dc2f918;hb=HEAD) via RubyCocoa. The the gist of it is: ``` url = NSURL.fileUR...
Based upon code from <http://www.cocoadev.com/index.pl?MoveToTrash> I have came up with the following: ``` def get_trash_path(input_file): path, file = os.path.split(input_file) if path.startswith("/Volumes/"): # /Volumes/driveName/.Trashes/<uid> s = path.split(os.path.sep) # s[2] is dr...
OS X: Determine Trash location for a given path
[ "", "python", "macos", "filesystems", "" ]
I have a DTS package that drops a table then creates it and populates it but sometimes something happens and the package fails after the drop table. If it's rerun it fails cuz the table hasn't been created yet. Is there something like "if exists" for SQLServer 2000 like in MySQL? thanks.
Or quicker: ``` IF OBJECT_ID('temp_ARCHIVE_RECORD_COUNTS') IS NOT NULL DROP TABLE temp_ARCHIVE_RECORD_COUNTS ``` * [OBJECT\_ID - MSDN Reference - SQL Server 2000](http://msdn.microsoft.com/en-us/library/aa276843%28v=sql.80%29.aspx) * [OBJECT\_ID - MSDN Reference - SQL Server 2008](http://msdn.microsoft.com/en-us/...
``` IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U')) DROP TABLE TableName; GO ``` You can check a [list of type definitions in the sys.objects table here](http://msdn.microsoft.com/en-us/library/ms177596.aspx) if you want to check if other objects in your datab...
How can I drop a table if it exists in SQL Server 2000?
[ "", "sql", "sql-server", "" ]
I am developing a C# program, and i have one function that consumes too much CPU. I would like to know a way to control this by code (not with any external application) and restrict the percentage of CPU usage. For example, if it uses 90% of the CPU usage, to make my app consume only a 20%, even if it becomes slower. I...
I don't know if you can do that, but you can change the thread priority of the executing thread via the [Priority](http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx) property. You would set that by: ``` Thread.CurrentThread.Priority = ThreadPriority.Lowest; ``` Also, I don't think you real...
I guess you need to query some kind of OS API to find out how much of the CPU are you consuming and take throttling decisions (like Thread.Sleep) from that on.
How to restrict the CPU usage a C# program takes?
[ "", "c#", "cpu", "" ]
Let's have the following class hierarchy: ``` public class ParentClass implements SomeInterface { } public class ChildClass extends ParentClass { } ``` Then let's have these two instances: ``` ParentClass parent; ChildClass child; ``` Then we have the following TRUE statements ``` (parent instanceof SomeInterface...
No it is not possible, and your intent to do so is a good hint that something is flawed in your class hierarchy. Workaround: change the class hierarchy, eg. like this: ``` interface SomeInterface {} abstract class AbstractParentClass {} class ParentClass extends AbstractParentClass implements SomeInterface {} class C...
Maybe composition instead of inheritance is what you want, i.e. have a "base class" object as a member and just implement the interfaces you need, forwarding any methods needed to the member.
Is it possible to unimplement an interface in derived class in Java?
[ "", "java", "oop", "" ]
I have a table named Info of this schema: ``` int objectId; int time; int x, y; ``` There is a lot of redundant data in the system - that is, `objectId` is not UNIQUE. For each `objectId` there can be multiple entries of `time, x, y`. I want to retrieve a list of the latest position of each object. I started out wit...
One way is using a subquery. ``` select distinct a.objectID, a.time, a.x, a.y from Info a, (select objectID, max(time) time from Info group by objectID) b where a.objectID = b.objectID and a.time = b.time ``` EDIT: Added DISTINCT to prevent duplicate rows if one objectId has multiple records with the same ...
``` SELECT A.time, A.objectID, B.X, B.Y FROM ( SELECT max(time) as time, objectID FROM table GROUP by objectID ) as A INNER JOIN table B ON A.objectID = b.objectID AND A.Time = b.Time ``` votenaders, solution won't work, if x & y decrement at anypoint in the time line.
Help write a query: Confusion over order of operations of GROUP BY and ORDER BY
[ "", "mysql", "sql", "database", "" ]
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", whi...
Python is actually behaving as defined. **Three separate functions** are created, but they each have the **closure of the environment they're defined in** - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in ...
The functions defined in the loop keep accessing the same variable `i` while its value changes. At the end of the loop, all the functions point to the same variable, which is holding the last value in the loop: the effect is what reported in the example. In order to evaluate `i` and use its value, a common pattern is ...
How do lexical closures work?
[ "", "python", "closures", "lazy-evaluation", "late-binding", "python-closures", "" ]
Can anyone provide a clear explanation / example of what these functions do, and when it's appropriate to use them?
Straight from [the manual](http://www.postgresql.org/docs/8.3/static/ddl-constraints.html#DDL-CONSTRAINTS-FK)... > We know that the foreign keys disallow creation of orders that do not relate to any products. But what if a product is removed after an order is created that references it? SQL allows you to handle that a...
I have a PostGreSQL database and I use On Delete when I have a user that I delete from the database and I need to delete it's information from other table. This ways I need to do only 1 delete and FK that has ON delete will delete information from other table. You can do the same with ON Update. If you update the tabl...
How do the Postgres foreign key 'on update' and 'on delete' options work?
[ "", "sql", "database-design", "postgresql", "foreign-keys", "cascade", "" ]
With the following file reading code: ``` using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None)) { using (TextReader tr = new StreamReader(fileStream)) { string fileContents = tr.ReadToEnd(); } } ``` And the following file write code: ``` using (T...
You can open a file for writing and only lock write access, thereby allowing others to still read the file. For example, ``` using (FileStream stream = new FileStream(@"C:\Myfile.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) { // Do your writing here. } ``` Other file access just opens the file for ...
If you create a named Mutex you can define the mutex in the writing application, and have the reading application wait until the mutex is released. So in the notification process that is currently working with the FileSystemWatcher, simply check to see if you need to wait for the mutex, if you do, it will wait, then p...
In C#, if 2 processes are reading and writing to the same file, what is the best way to avoid process locking exceptions?
[ "", "c#", "file-io", "distributed", "" ]
I take care of critical app in my project. It does stuff related to parsing business msgs (legacy standard), processing them and then storing some results in a DB (another apps picks that up). After more then a year of my work (I've other apps to look after as well) the app is finally stable. I've introduced strict TDD...
I would advise you **not** to inherit your specific message handling classes from base classes that contain the common code like this: ``` CommonHandler ^ ^ | | = inheritance MsgAHandler ^ ^ ...
I would suggest looking at the libraries provided by boost, for example `Tuple` or `mpl::vector`. These libraries allows you to create a list of unrelated types and then operate over them. The very rough idea is that you have sequences of types for each message kind: ``` Seq1 -> MSG_A_NEW, MSG_A_CNL Seq2 -> MSG_B_NEW,...
designing business msgs parser / rewriting from scratch
[ "", "c++", "design-patterns", "oop", "templates", "" ]
## Note The question below was asked in 2008 about some code from 2003. As the OP's **update** shows, this entire post has been obsoleted by vintage 2008 algorithms and persists here only as a historical curiosity. --- I need to do a fast case-insensitive substring search in C/C++. My requirements are as follows: *...
The code you posted is about half as fast as `strcasestr`. ``` $ gcc -Wall -o my_stristr my_stristr.c steve@solaris:~/code/tmp $ gcc -Wall -o strcasestr strcasestr.c steve@solaris:~/code/tmp $ ./bench ./my_stristr > my_stristr.result ; ./bench ./strcasestr > strcasestr.result; steve@solaris:~/code/tmp $ cat my_strist...
You can use StrStrI function which finds the first occurrence of a substring within a string. The comparison is not case-sensitive. Don't forget to include its header - Shlwapi.h. Check this out: <http://msdn.microsoft.com/en-us/library/windows/desktop/bb773439(v=vs.85).aspx>
Fastest way to do a case-insensitive substring search in C/C++?
[ "", "c++", "c", "optimization", "string", "glibc", "" ]
I have a problem applying the `DebuggerDisplay` attribute on a generic class: ``` [DebuggerDisplay("--foo--")] class Foo { } [DebuggerDisplay("Bar: {t}")] class Bar<T> { public T t; } ``` When inspecting an object of type `Bar<Foo>` I would expect it to show as `Bar: --foo--`, but I get `Bar: {Foo}` What am I d...
The DebuggerDisplay attribute is not recursive. The {} inside the string essentially say evaluate this expression and display the result inline. The string for the inner result is calculated as if there was no DebuggerDisplay attribute in play for type or member. That is why you see {Foo} instead of --foo--. The reaso...
You can use `[DebuggerDisplay("Bar<{typeof(T).Name,nq}>")]//nq - no quotes`. You also can use these practices: [DebuggerDisplay attribute best practices](http://blogs.msdn.com/b/jaredpar/archive/2011/03/18/debuggerdisplay-attribute-best-practices.aspx)
DebuggerDisplay on generic class
[ "", "c#", ".net", "visual-studio", "debugging", "" ]
I'm using Eclipse 3.4 and Tomcat 5.5 and I have a Dynamic Web Project set up. I can access it from <http://127.0.0.1:8080/project/> but by default it serves files from WebContent folder. The real files, that I want to serve, can be found under folder named "share". This folder comes from CVS so I'd like to use it with ...
In the project folder, there should be a file under the `.settings` folder named `org.eclipse.wst.common.component` that contains an XML fragment like this: ``` <wb-module deploy-name="WebProjectName"> <wb-resource deploy-path="/" source-path="/WebContent"/> <wb-resource deploy-path="/WEB-INF/classes" source-p...
Can be done through Eclipse, no need to manually edit .settings files. In Eclipse 3.6 (and possibly earlier releases), 1. right click on your project 2. click on properties 3. Click on 'Deployment Assembly' 4. Add... Folder -> Next 5. Navigate to source folder 6. Finish
Eclipse & Tomcat: How to specify which folder is served from the project?
[ "", "java", "eclipse", "tomcat", "eclipse-3.4", "" ]
I have a C# app which uses a System.Diagnostics.Process to run another exe. I ran into some example code where the process is started in a try block and closed in a finally block. I also saw example code where the process is not closed. What happens when the process is not closed? Are the resources used by the proces...
When the other process *exits*, all of *its* resources are freed up, but you will still be holding onto a process handle (which is a pointer to a block of information about the process) unless you call `Close()` on your `Process` reference. I doubt there would be much of an issue, but **you may as well**.`Process` impl...
They will continue to run as if you started them yourself.
What happens if I don't close a System.Diagnostics.Process in my C# console app?
[ "", "c#", "process", "" ]
I knew stackoverflow would help me for other than know what is the "favorite programming cartoon" :P This was the accepted answer by: [Bill Karwin](https://stackoverflow.com/questions/185327/oracle-joins-left-outer-right-etc-s#185439) Thanks to all for the help ( I would like to double vote you all ) My query ended ...
Try something like this (I haven't tested it): ``` SELECT p_new.identifier, COALESCE(p_inprog.activity, p_new.activity) AS activity, p_inprog.participant, COALESCE(p_inprog.closedate, p_new.closedate) AS closedate FROM performance p_new LEFT OUTER JOIN performance p_inprog ON (p_new.identifier = p_inprog.iden...
Typically the better way to write those is with EXISTS. The first one would be: ``` select * from performance p1 where not exists ( select * from performance p2 where p2.identifier = p1.identifier and p2.activity = 4 ) ``` This way lets you do a keyed lookup on performance.identifier, rather than potentia...
Oracle joins ( left outer, right, etc. :S )
[ "", "sql", "oracle", "join", "left-join", "" ]
I want to fade out an element and all its child elements after a delay of a few seconds. but I haven't found a way to specify that an effect should start after a specified time delay.
``` setTimeout(function() { $('#foo').fadeOut(); }, 5000); ``` The 5000 is five seconds in milliseconds.
I use this pause plugin I just wrote ``` $.fn.pause = function(duration) { $(this).animate({ dummy: 1 }, duration); return this; }; ``` Call it like this : ``` $("#mainImage").pause(5000).fadeOut(); ``` Note: you don't need a callback. --- **Edit: You should now use the [jQuery 1.4. built in delay()](http...
delay JQuery effects
[ "", "javascript", "jquery", "effects", "" ]
I'm wondering if there is a quick and easy function to clean get variables in my url, before I work with them.( or $\_POST come to think of it... ) I suppose I could use a regex to replace non-permitted characters, but I'm interested to hear what people use for this sort of thing?
I use the PHP [input filters](https://www.php.net/manual/en/function.filter-input.php) and the function [urlencode](http://php.net/urlencode).
The concept of cleaning input never made much sense to me. It's based on the assumption that some kinds of input are dangerous, but in reality there is no such thing as dangerous input; Just code that handles input wrongly. The culprit of it is that if you embed a variable inside some kind of string (code), which is t...
A tidy way to clean your URL variables?
[ "", "php", "security", "sanitization", "" ]
Multimap essentially has groups of data sorted by the key. I want a method by which I could access these individual groups and get their aggregate values. For example, in a `std::multimap< string, int >` I store ``` {"Group1", 1}, {"Group1", 2}, {"Group1", 3}, {"Group2", 10}, {"Group2", 11}, {"Group2", 12} ``` ...
``` pair<Iter, Iter> range = my_multimap.equal_range("Group1"); int total = accumulate(range.first, range.second, 0); ``` Is one way. **Edit:** If you don't know the group you are looking for, and are just going through each group, getting the next group's range can be done like so: ``` template <typename Pair> str...
``` // samekey.cpp -- Process groups with identical keys in a multimap #include <iostream> #include <string> #include <map> using namespace std; typedef multimap<string, int> StringToIntMap; typedef StringToIntMap::iterator mapIter; int main () { StringToIntMap mymap; mymap.insert(make_pair("Group2", 11)); ...
stl::multimap - how do i get groups of data?
[ "", "c++", "stl", "multimap", "" ]
Are there any other ways to avoid LazyInitializationExceptions in a Hibernate web application besides using the OpenSessionInView pattern? Are there any downsides to using OpenSessionInView?
When working on our web applications, we usually decide beforehand which objects/fields will be needed in the view pages and make sure that all the objecs are properly initialized from the model before dispatching to the view. This can be accomplished in (at least) three ways: 1. [fetching](http://www.hibernate.org/h...
Typically the best way to handle the problem, without making a global decision to do eager fetching; is to use the "fetch" keyword in conjuction with the hql query. From <http://www.hibernate.org/hib_docs/reference/en/html/queryhql-joins.html> In addition, a "fetch" join allows associations or collections of values t...
Strategies to avoid Hibernate LazyInitializationExceptions
[ "", "java", "database", "hibernate", "" ]
In XAML I can declare a DataTemplate so that the template is used whenever a specific type is displayed. For example, this DataTemplate will use a TextBlock to display the name of a customer: ``` <DataTemplate DataType="{x:Type my:Customer}"> <TextBlock Text="{Binding Name}" /> </DataTemplate> ``` I'm wondering i...
Not out of the box, no; but there are enterprising developers out there who have done so. Mike Hillberg at Microsoft played with it in [this post](https://learn.microsoft.com/en-us/archive/blogs/mikehillberg/limited-generics-support-in-xaml), for example. Google has others of course.
Not directly in XAML, however you could reference a `DataTemplateSelector` from XAML to choose the correct template. ``` public class CustomerTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container...
Can I specify a generic type in XAML (pre .NET 4 Framework)?
[ "", "c#", "wpf", "xaml", "generics", "" ]
On my busiest production installation, on occasion I get a single thread that seems to get stuck in an infinite loop. I've not managed to figure out who is the culprit, after much research and debugging, but it seems like it should be possible. Here are the gory details: ***Current debugging notes:*** 1) **ps -eL 189...
It looks like the **nid** in the jstack output is the Linux LWP id. ``` "http-342.877.573.944-8080-360" daemon prio=10 tid=0x0000002adaba9c00 nid=0x754c in Object.wait() [0x00000000595bc000..0x00000000595bccb0] ``` Convert the nid to decimal and you have the LWP id. In your case 0x754c is 30028. This process is not s...
You can use [JConsole](http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html) to view the thread's stack trace. If your using JDK 1.6.0\_07 or above, you can also use [visualvm](http://java.sun.com/javase/6/docs/technotes/guides/visualvm/index.html). Both tools provide a nice view of all the running thre...
Getting the Java thread id and stack trace of run-away Java thread
[ "", "java", "debugging", "jstack", "" ]
I am building an application where most of the HTML is built using javascript. The DOM structure is built using some JSON data structures that are sent from the server, and then the client-side code builds a UI for that data. My current approach is to walk the JSON data structures, and call script.aculo.us's Builder.n...
There are some template solutions out there, but they aren't doing much more than you're doing already. jQuery has been doing some [**work along these lines**](http://ejohn.org/blog/javascript-micro-templating/), and some jQuery [**plugins**](http://plugins.jquery.com/project/jTemplates) have emerged as solutions. Prot...
there are several 'template' plugins for jQuery: * [jsRepeater](http://plugins.jquery.com/project/jsrepeater) * [jTemplates](http://plugins.jquery.com/project/jTemplates) * [noTemplate](http://plugins.jquery.com/project/noTemplate) * [Template](http://plugins.jquery.com/project/Template) There are some XSLT extras th...
How to build the DOM using javascript and templates?
[ "", "javascript", "templates", "" ]
I'm trying to track down an issue in our system and the following code worries me. The following occurs in our doPost() method in the primary servlet (names have been changed to protect the guilty): ``` ... if(Single.getInstance().firstTime()){ doPreperations(); } normalResponse(); ... ``` The singleton 'Single' l...
I found this on Sun's site: > ### Multiple Singletons Simultaneously Loaded by Different Class Loaders > > When two class loaders load a class, > you actually have two copies of the > class, and each one can have its own > Singleton instance. That is > particularly relevant in servlets > running in certain servlet eng...
No it won't get built over and over again. It's static, so it'll only be constructed once, right when the class is touched for the first time by the Classloader. Only exception - if you happen to have multiple Classloaders. (from [GeekAndPoke](http://geekandpoke.typepad.com/.a/6a00d8341d3df553ef0147e0761e2f970b-800wi...
Can this Java singleton get rebuilt repeatedly in WebSphere 6?
[ "", "java", "singleton", "instance", "" ]
I am trying to convert all DateTime values in a DataTable to strings. Here is the method I use: ``` private static void ConvertDateTimesToStrings(DataTable dataTable) { if (dataTable == null) { return; } for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++ ) { for (in...
It may have determined that the column data type is date time and is reboxing the values to datetime when you save the value back in there. Try this... Create a new column on the datatable as a TypeOf(String), and save the string value into that column. When all the values have been copied, drop the date time column.
This simply won't work, because you haven't changed the underlaying data type. You have a DataTable, with a column which has data type DateTime. You can assign a String to it, but it will convert back to DateTime. Why do you want to change it to a formatted string? Can't you format only when you need to display it, ...
Setting value of an item in a DataRow does not work
[ "", "c#", "datarow", "" ]
Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a...
The simplest way is just to write a program with an infinite loop, and then hit control-C to stop it. Without more description it's hard to know if this works for you. If you do it time-based, you don't need a generator. You can just have it pause for user input, something like a "Continue? [y/n]", read from stdin, an...
You could use a generator for this: ``` def finished(): "Define your exit condition here" return ... def count(i=0): while not finished(): yield i i += 1 for i in count(): print i ``` If you want to change the exit condition you could pass a value back into the generator function and...
making a programme run indefinitely in python
[ "", "python", "time", "key", "indefinite", "" ]
I've created the following regex pattern in an attempt to match a string 6 characters in length ending in either "PRI" or "SEC", unless the string = "SIGSEC". For example, I want to match ABCPRI, XYZPRI, ABCSEC and XYZSEC, but not SIGSEC. ``` (\w{3}PRI$|[^SIG].*SEC$) ``` It is very close and sort of works (if I pass ...
Assuming your regex engine supports negative lookaheads, try this: ``` ((?!SIGSEC)\w{3}(?:SEC|PRI)) ``` Edit: A commenter pointed out that .NET does support negative lookaheads, so this should work fine (thanks, Charlie).
To help break down Dan's (correct) answer, here's how it works: ``` ( // outer capturing group to bind everything (?!SIGSEC) // negative lookahead: a match only works if "SIGSEC" does not appear next \w{3} // exactly three "word" characters (?: // non-capturing group - we don't care which of t...
How do I match part of a string only if it is not preceded by certain characters?
[ "", "c#", ".net", "regex", "negative-lookbehind", "" ]
Can someone please derive a concrete example from the following: <http://www.urdalen.com/blog/?p=210> ..that shows how to deal with `one-to-many` and `many-to-many` relationships? I've emailed the author some time ago but received no reply. I like his idea, but can't figure out how to implement it beyond simple sing...
The problem of ORM's (The impedance mismatch, as it's called) is precisely with relations. In an object graph (In-memory objects), relationships are pointers to other objects. In a relational database, relationships are reversed; This makes it impossible to do a simple mapping between the two models, and that is why OR...
If you're looking for a simple and portable DataMapper ORM, have a look at [phpDataMapper](http://phpdatamapper.com). It's only dependencies are PHP5 and PDO, and it's very small and lightweight. It supports table relations and some other very nice features as well.
How to extend this simple DataMapper?
[ "", "php", "design-patterns", "orm", "datamapper", "" ]
How is it possible that .NET is finding the wrong `MyType` in this scenario? I have a type `A.B.C.D.MyType` in a project that I'm working on, and I'm referencing a DLL that has a type `A.B.MyType`. I do not have any `using A.B;` statements anywhere in my code, and I do have `using A.B.C.D;`. When I compile, the compil...
Are you working in a namespace that is under A.B namespace? (for example A.B.X) if so the C# namespace resolutions ([ECMA-334 C# Language Specification : 10.8 10.8 Namespace and type names](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf)) says: > ... for each namespace N, starting > with the...
Is your code in namespace `A.B` or `A.B.C`? If so, that's probably the issue. Use a using directive like this: ``` using TheTypeIWant = A.B.C.D.MyType; ``` then just refer to `TheTypeIWant` in your code. EDIT: I've just tried the "`using MyType=A.B.C.D.MyType`" option, but that *doesn't* work. The above is fine thou...
Namespace collisions
[ "", "c#", ".net", "namespaces", "" ]
I have the following sql query for transforming data but is it possible to save the value of the int in some variable to avoid casting multiple times? ``` update prospekts set sni_kod = case when cast(sni_kod as int) >= 1000 and cast(sni_kod as int) <= 1499 or cast(sni_kod as int) >= 1600 and cast(sni_kod a...
Ok... here's my rewrite of your code... ``` UPDATE prospekts SET sni_kod = CASE WHEN ISNUMERIC(@sni_kod)=1 THEN CASE WHEN cast(@sni_kod as int) BETWEEN 1000 AND 1499 OR cast(@sni_kod as int) BETWEEN 1600 AND 2439 THEN '1' WHEN cast(@sni_kod as int) BETWEEN 7000...
Is this just a one-off script, as it appears? If so, and you are just trying to save on typing then write as: ``` update prospekts set sni_kod = case when xxx >= 1000 and xxx <= 1499 or xxx >= 1600 and xxx <= 2439 then '1' when xxx >= 7000 and xxx <= 7499 then 'W' else sni_kod end ``` ... and the...
How do I avoid multiple CASTs in sql query?
[ "", "sql", "t-sql", "" ]