Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I would like to monitor the following system information in Java: * Current CPU usage\*\* (percent) * Available memory\* (free/total) * Available disk space (free/total) \*Note that I mean overall memory available to the whole system, not just the JVM. I'm looking for a cross-platform solution (Linux, Mac, and Win...
Along the lines of what I mentioned [in this post](https://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information#25583). I recommend you use the [SIGAR API](https://github.com/hyperic/sigar). I use the SIGAR API in one of my own applications and it is great. You'll find it is stable, well supp...
The following supposedly gets you CPU and RAM. See [ManagementFactory](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ManagementFactory.html) for more details. ``` import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; import jav...
How do I monitor the computer's CPU, memory, and disk usage in Java?
[ "", "java", "memory", "cross-platform", "cpu", "diskspace", "" ]
If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system? I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current vers...
As python is in kind of an transition phase towards python 3 with breaking backward compatibility I don't think it is a good idea to go python 3 only. Based on the [time line](http://www.python.org/dev/peps/pep-3000/#timeline) there will be at least one or two following releases of the 2.x series after 2.6/3.0 in octob...
I've not seen a system with less than 2.3 installed for some time. Mostly 2.4+ is installed by default for most OS I use now. 2.3 is just on an older Solaris machine. Linux distros tend to have 2.4+, as does OS X. IIRC, 2.4 has a lot of the features 2.5 does, but usable only with ``` from __future__ import * ```
Which Version of Python to Use for Maximum Compatibility
[ "", "python", "compatibility", "" ]
Can i print out a url `/admin/manage/products/add` of a certain view in a template? Here is the rule i want to create a link for ``` (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), ``` I would like to have /manage/products/add in a template without hardcoding it. How can i d...
You can use `get_absolute_url`, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case. You want to use [named URL patterns](https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns). Here's a quick intro: Change the line in your urls....
If you use [named url patterns](https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns) you can do the follwing in your template ``` {% url create_object %} ```
Django: Print url of view without hardcoding the url
[ "", "python", "django", "" ]
I'm creating a .net custom control and it should be able to load multiple text files. I have a public property named ListFiles with those properties set : ``` [Browsable(true), Category("Configuration"), Description("List of Files to Load")] public string ListFiles { get { return m_oList; } set { m_oList =...
You can do this by adding a [UITypeEditor](http://msdn.microsoft.com/en-us/library/ms171839.aspx). [Here is an example](http://web.archive.org/web/20090218231316/http://www.winterdom.com/weblog/2006/08/23/ACustomUITypeEditorForActivityProperties.aspx) of a UITypeEditor that gives you the OpenFileDialog for chossing a ...
You can use built-in UITypeEditor. It is called [FileNameEditor](http://msdn.microsoft.com/en-us/library/system.windows.forms.design.filenameeditor.aspx) ``` [EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))] public string SomeFilePath { get; set; } ```
How can I get an OpenFileDialog in a custom control's property grid?
[ "", "c#", ".net", "controls", "propertygrid", "" ]
Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by han...
It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point: ``` using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace TableGenerator { class Program { static void ...
@Jonathan Holland Wow, I think that's the most raw work I've ever seen put into a StackOverflow post. Well done. **However**, instead of constructing DDL statements as strings, you should definitely use the [SQL Server Management Objects](http://msdn.microsoft.com/en-us/library/ms162169.aspx) classes introduced with S...
How can I generate database tables from C# classes?
[ "", "c#", "code-generation", "data-access", "" ]
I work in a Windows environment and would prefer to deploy code to IIS. At the same time I would like to code in Python. Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else. Does anyone have experience get...
There shouldn't be any need to use FastCGI. There exists a [ISAPI extension for WSGI](https://github.com/hexdump42/isapi-wsgi).
Microsoft itself develops [wfastcgi](https://pypi.python.org/pypi/wfastcgi) ([source code](https://github.com/Microsoft/PTVS/tree/master/Python/Product/WFastCgi)) to host Python code on IIS.
How do you set up a Python WSGI server under IIS?
[ "", "python", "iis", "deployment", "windows-server", "iis-modules", "" ]
I have a class to parse a matrix that keeps the result in an array member: ``` class Parser { ... double matrix_[4][4]; }; ``` The user of this class needs to call an API function (as in, a function I have no control over, so I can't just change its interface to make things work more easily) that looks like this:...
Here's a nice, clean way: ``` class Parser { public: typedef double matrix[4][4]; // ... const matrix& getMatrix() const { return matrix_; } // ... private: matrix matrix_; }; ``` Now you're working with a descriptive type name rather than an array, but since it's a `typedef` the compile...
Try this. It compiles cleanly on gcc 4.1.3: ``` typedef double FourSquare[4][4]; class Parser { private: double matrix_[4][4]; public: Parser() { for(int i=0; i<4; i++) for(int j=0; j<4; j++) matrix_[i][j] = i*j; } public: const FourSquare& GetMatrix() { ...
How to deal with arrays (declared on the stack) in C++?
[ "", "c++", "arrays", "" ]
Assuming I'm trying to automate the installation of something on windows and I want to try to test whether another installation is in progress before attempting install. I don't have control over the installer and have to do this in the automation framework. Is there a better way to do this, some win32 api?, than just ...
See the description of the [\_MSIExecute Mutex](http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx) on MSDN.
I was getting an unhandled exception using the code above. I cross referenced this article witt this [one](https://stackoverflow.com/questions/17070583/releasing-a-mutex) Here's my updated code: ``` /// <summary> /// Wait (up to a timeout) for the MSI installer service to become free. /// </summary> /// <returns> /...
How do I test if another installation is already in progress?
[ "", "c#", "windows", "windows-installer", "" ]
What is the command to list all triggers in a MySQL database?
The command for listing all triggers is: ``` show triggers; ``` or you can access the `INFORMATION_SCHEMA` table directly by: ``` select trigger_schema, trigger_name, action_statement from information_schema.triggers ``` * You can do this from version 5.0.10 onwards. * More information about the [`TRIGGERS` table i...
I hope following code will give you more information. ``` select * from information_schema.triggers where information_schema.triggers.trigger_schema like '%your_db_name%' ``` This will give you total 22 Columns in **MySQL version: 5.5.27** and Above ``` TRIGGER_CATALOG TRIGGER_SCHEMA TRIGGER_NAME EVENT_MANIPULATIO...
Show all triggers in a MySQL database
[ "", "sql", "mysql", "database", "triggers", "sqlcommand", "" ]
I have a Linq query that I want to call from multiple places: ``` var myData = from a in db.MyTable where a.MyValue == "A" select new { a.Key, a.MyValue }; ``` How can I create a method, put this code in it, a...
IQueryable and IEnumerable both work. But you want to use a type specific version, IQueryable`<`T`>` or IEnumerable `<`T`>`. So you'll want to create a type to keep the data. ``` var myData = from a in db.MyTable where a.MyValue == "A" select new MyType { Key = ...
[`IQueryable`](http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx) So your method declaration would look like ``` public IQueryable GetSomeData() ```
How can I return an anonymous type from a method?
[ "", "c#", "linq", "data-structures", "parameter-passing", "" ]
Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#: ``` SomeMethod { // Member of AClass{} DoSomething; Start WorkerMethod() from BClass in another thread; DoSomethingElse; } ``` Then, when WorkerMethod() is complete, run this: ``` void So...
The [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class was added to .NET 2.0 for this exact purpose. In a nutshell you do: ``` BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += delegate { myBClass.DoHardWork(); } worker.RunWorkerCompleted += ...
In .Net 2 the BackgroundWorker was introduced, this makes running async operations really easy: ``` BackgroundWorker bw = new BackgroundWorker { WorkerReportsProgress = true }; bw.DoWork += (sender, e) => { //what happens here must not touch the form //as it's in a different thread }; bw.Progres...
Delegating a task in and getting notified when it completes (in C#)
[ "", "c#", "delegates", "notifications", "" ]
I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?
``` string[] formats = {"yyyyMMdd", "MM/dd/yy"}; var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None); ``` or ``` DateTime result; string[] formats = {"yyyyMMdd", "MM/dd/yy"}; DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out resul...
[DateTime.TryParse](http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx) method
Convert a string to a date in .net
[ "", "c#", ".net", "" ]
**Edit**: Solved, there was a trigger with a loop on the table (read my own answer further below). --- We have a simple delete statement that looks like this: ``` DELETE FROM tablename WHERE pk = 12345 ``` This just hangs, no timeout, no nothing. We've looked at the execution plan, and it consists of many lookups ...
One piece of information missing is the number of indices on the table you are deleting the data from. As SQL Server uses the Primary Key as a pointer in every index, any change to the primary index requires updating every index. Though, unless we are talking a high number, this shouldn't be an issue. I am guessing, f...
Try recreating the index on that table, and try regenerating the statistics. [DBCC REINDEX](http://msdn.microsoft.com/en-us/library/aa258828(SQL.80).aspx) [UPDATE STATISTICS](http://msdn.microsoft.com/en-us/library/aa260645(SQL.80).aspx)
DELETE Statement hangs on SQL Server for no apparent reason
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I am attempting to devise a system for packing integer values greater than 65535 into a ushort. Let me explain. We have a system which generates Int32 values using an IDENTITY column from SQL Server and are limited by an in-production client API that overflows our Int32 IDs to ushorts. Fortunately the client only has ...
Regarding approach 2: Your second approach is pretty much how NAT works. Every TCP/UDP client on the local network has up to 65535 ports in use (except port 0) and a private IP. The router knows only a single public IP. Since two clients may both have source port 300, it cannot simply just replace the private IP with ...
I can think of a few other options: Are there globally fewer than 65536 entries in the database? If so, then you could maintain a mapping table that's not associated with session state, but is a persisted part of the application. Are the majority of entries at indexes less than, say 50,000? If that's the case you cou...
Translating Int32 into ushort and back again
[ "", "c#", "overflow", "int32", "ushort", "" ]
We are currently using Apache 2.2.3 and Tomcat 5 (Embedded in JBoss 4.2.2) using `mod_proxy_jk` as the connector. Can someone shed some light on the the correct way to calculate / configure the values below (as well as anything else that may be relevant). Both Apache and Tomcat are running on separate machines and hav...
You should consider the workload the servers might get. The most important factor might be the number of simultaneously connected clients at peak times. Try to determine it and tune your settings in a way where: * there are enough processing threads in both Apache and Tomcat that they don't need to spawn new threads ...
### MaxClients This is the fundamental cap of parallel client connections your apache should handle at once. With prefork, only one request can be handled per process. Therefore the whole apache can process *at most* $MaxClients requests in the time it takes to handle a *single* request. Of course, this ideal maximum...
Best practices for configuring Apache / Tomcat
[ "", "java", "apache", "tomcat", "jboss", "mod-proxy", "" ]
NOTE: I am not set on using VI, it is just the first thing that came to mind that might be able to do what I need. Feel free to suggest any other program. I have a form with nearly 100 fields that I would like to auto-fill with PHP. I know how to do the autofill, but I would like to avoid manually adding the needed te...
Taking some ideas from Zsolt Botykai and Mark Biek: ``` :%s:<input\(.* id="\([^"]*\)".*\) />:<input \1 value="<?php echo $data['\2']; ?> />:g ```
`:%s:\(<input name="\([^"]\+\)" id="[^"]\+" type="text" \)/>:\1value="<?php echo $data ['\2']; ?>" />:gci` That's one line. HTH.
Can I use RegEx and VI (or something similar) to autofill some text for me?
[ "", "php", "html", "vi", "" ]
what configuration needs to be tweaked, and where does it live, in order to increase the maximum allowed post size?
Apache Tomcat by default sets a limit on the maximum size of HTTP POST requests it accepts. In Tomcat 5, this limit is set to 2 MB. When you try to upload files larger than 2 MB, this error can occur. The solution is to reconfigure Tomcat to accept larger POST requests, either by increasing the limit, or by disabling ...
It will be for others persons, I see you are coupling Apache HTTP and Tomcat (tomcat / mod\_jk), in this case edit the Coyote/JK2 AJP 1.3 Connector the same way you do it for the standard connector (Coyote HTTP/1.1), because the AJP1.3 Connector is where Tomcat receive data. ``` <!-- Define a Coyote/JK2 AJP 1.3 Connec...
What causes java.lang.IllegalStateException: Post too large in tomcat / mod_jk
[ "", "java", "tomcat", "mod-jk", "" ]
How can you strip non-ASCII characters from a string? (in C#)
``` string s = "søme string"; s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty); ``` --- The `^` is the not operator. It tells the regex to find everything that doesn't match, instead of everything that does match. The `\u####-\u####` says which characters match.`\u0000-\u007F` is the equivalent of the first 1...
Here is a pure .NET solution that doesn't use regular expressions: ``` string inputString = "Räksmörgås"; string asAscii = Encoding.ASCII.GetString( Encoding.Convert( Encoding.UTF8, Encoding.GetEncoding( Encoding.ASCII.EncodingName, new EncoderReplacementFallback(string.Empt...
How can you strip non-ASCII characters from a string? (in C#)
[ "", "c#", "ascii", "" ]
Consider the following 2 queries: ``` select tblA.a,tblA.b,tblA.c,tblA.d from tblA where tblA.a not in (select tblB.a from tblB) select tblA.a,tblA.b,tblA.c,tblA.d from tblA left outer join tblB on tblA.a = tblB.a where tblB.a is null ``` Which will perform better? My assumption is that in general the join will be b...
RDBMSs "rewrite" queries to optimize them, so it depends on system you're using, and I would guess they end up giving the same performance on most "good" databases. I suggest picking the one that is clearer and easier to maintain, for my money, that's the first one. It's much easier to debug the subquery as it can be ...
non-correlated sub queries are fine. you should go with what describes the data you're wanting. as has been noted, this likely gets rewritten into the same plan, but isn't guaranteed to! what's more, if table A and B are not 1:1 you will get duplicate tuples from the join query (as the IN clause performs an implicit DI...
subselect vs outer join
[ "", "sql", "sql-server", "database", "performance", "" ]
I've got a c# assembly which I'm invoking via COM from a Delphi (win32 native) application. This works on all the machines I've tested it on, except one. The problem is that the Delphi application gets "Class not registered" when trying to create the COM object. Now, when I look in the registry under `HKEY_CLASSES_R...
The GUID in AssemblyInfo becomes the "Type-Library" GUID and usually is not what you'd be looking for. I'm going to assume you're trying to access a class, and you need to define a Guid attribute and ComVisible for the class. For example: ``` [Guid("00001111-2222-3333-4444-555566667777"), ComVisible(true)] public ...
Maybe you have an old version of the assembly somewhere? Maybe in the GAC? Regasm is probably picking that up and using it.
Why does regasm.exe register my c# assembly with the wrong GUID?
[ "", "c#", ".net", "delphi", "com", "regasm", "" ]
How can I extract the list of available SQL servers in an SQL server group? I'm planning to put that list in a combo box in VB.NET.
The only way I knew to do it was using the command line: ``` osql -L ``` But I found the below article which seems to solve your specific goal filling a combobox: <http://www.sqldbatips.com/showarticle.asp?ID=45>
If you didn't want to be tied to SQL SMO, which is what [Ben's article](https://stackoverflow.com/a/147680/7444103) uses, you can do something like this to discover all SQL servers on your network: ``` Private Sub cmbServer_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbServer.DropDown Di...
Get list of available servers in SQL server group
[ "", "sql", "vb.net", "" ]
I've been trying to implement unit testing and currently have some code that does the following: 1. query external database, loading into a feed table 2. query a view, which is a delta of my feed and data tables, updating data table to match feed table my unit testing strategy is this: I have a testing d...
Is it your intent to test the view which generates the deltas, or to test that your code correctly adds, deletes and updates in response to the view? If you want to test the view, you could use a tool like [DBUnit](http://dbunit.sourceforge.net/) to populate your feed and data tables with various data whose delta you'...
[DbUnit](http://dbunit.sourceforge.net) will meet your needs. One thing to watch out for is that they have switched to using SLF4J as their logging facade instead of JCL. You can configure SLF4J to forward the logging to JCL but be warned if you are using Maven DbUnit sucks in their Nop log provider by default so you w...
JUnit for database code
[ "", "java", "database", "unit-testing", "junit", "" ]
I'm writing a game in Java, and I want the user to be able to provide input from both the command line and my GUI. Currently, I use this method to get input: ``` static String getInput(){ System.out.println("Your move:"); Scanner sc = new Scanner(System.in); return sc.nextLine(); } ``` ...
This is possible - the easiest substitution for *System.in* would be a [PipedInputStream](http://java.sun.com/javase/6/docs/api/java/io/PipedInputStream.html). This must be hooked up to a [PipedOutputStream](http://java.sun.com/javase/6/docs/api/java/io/PipedOutputStream.html) that writes from another thread (in this c...
I made an application once that could run via the command line or using a GUI. The way I did this was to define an Interface (named IODevice) which defined the following methods:- public String getInput(); - public void showOutput(String output); I then had two classes which implemented this interface - One used th...
Emulating user input for java.util.Scanner
[ "", "java", "input", "java.util.scanner", "" ]
I'm writing a C# program that acts as a PowerPoint 2007 plugin. On some machines, some calls to the PowerPoint object model throw a `COMException` with the message `RPC_E_SYS_CALL_FAILED`. I couldn't find any specific advice on what to do regarding this error, or how to avoid it. From Googling it looks like something t...
I don't know it is related to your problem, but all your COM calls must come from within the same thread your add-in was created on. If you created new threads you must take special care. Details are described in these two articles: * [Implementing IMessageFilter in an Office add-in](http://blogs.msdn.com/andreww/arch...
are you making the call from a thread with its ApartmentState set? if not, that might be the culprit - COM interop is pretty finicky about that sort of thing
C# COM Office Automation - RPC_E_SYS_CALL_FAILED
[ "", "c#", "com", "ms-office", "" ]
I have 3 tables 1. **Links** Link ID Link Name GroupID (FK into Groups) SubGroupID (FK into Subgroups) 2. **Groups** GroupID GroupName 3. **SubGroup** SubGroupID SubGroupName GroupID (FK into Groups) Every link needs to have a GroupID but teh SubGroupID is optional. How do...
This assumes that there is at most only 1 subgroup per group. if there are more, then you have the potential to get additional records. ``` select links.linkname, groups.groupname, subgroup.subgroupname from links inner join groups on (links.groupid = groups.groupid) left outer join subgroup on (links.subgroupid =...
``` SELECT links.linkname , groups.groupname , subgroup.groupname FROM links JOIN groups ON links.groupid = groups.groupid LEFT OUTER JOIN subgroups ON links.subgroupid = subgroup.subgroupid ``` (re-added to address OP's question) incidentally, why not keep groups and subgroups in the same table, and use...
SQL Join question
[ "", "sql", "" ]
I want to ask how other programmers are producing Dynamic SQL strings for execution as the CommandText of a SQLCommand object. I am producing parameterized queries containing user-generated WHERE clauses and SELECT fields. Sometimes the queries are complex and I need a lot of control over how the different parts are b...
I had the need to do this on one of my recent projects. Here is the scheme that I am using for generating the SQL: * Each component of the query is represented by an Object (which in my case is a Linq-to-Sql entity that maps to a table in the DB). So I have the following classes: Query, SelectColumn, Join, WhereCondit...
We created our own FilterCriteria object that is kind of a *black-box* dynamic query builder. It has collection properties for SelectClause, WhereClause, GroupByClause and OrderByClause. It also contains a properties for CommandText, CommandType, and MaximumRecords. We then jut pass our FilterCriteria object to our da...
Is there a standard approach to generating sql dynamically?
[ "", ".net", "sql", "" ]
I usually use C++ stdlib map whenever I need to store some data associated with a specific type of value (a key value - e.g. a string or other object). The stdlib map implementation is based on trees which provides better performance (O(log n)) than the standard array or stdlib vector. My questions is, do you know of ...
If you're using C++11, you have access to the `<unordered_map>` and `<unordered_set>` headers. These provide classes [`std::unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map) and [`std::unordered_set`](http://en.cppreference.com/w/cpp/container/unordered_set). If you're using C++03 with TR1, you...
If you don't already have unordered\_map or unordered\_set, they are part of [boost](http://www.boost.org/). [Here's the documentation for both](http://www.boost.org/doc/libs/1_36_0/doc/html/unordered.html).
Hashtable in C++?
[ "", "c++", "performance", "dictionary", "hashtable", "complexity-theory", "" ]
Wanted to convert ``` <br/> <br/> <br/> <br/> <br/> ``` into ``` <br/> ```
You can do this with a regular expression: ``` preg_replace("/(<br\s*\/?>\s*)+/", "<br/>", $input); ``` This if you pass in your source HTML, this will return a string with a single <br/> replacing every run of them.
Mine is almost exactly the same as [levik](https://stackoverflow.com/questions/133571/how-to-convert-multiple-br-tag-to-a-single-br-tag-in-php#133600)'s (+1), just accounting for some different br formatting: ``` preg_replace('/(<br[^>]*>\s*){2,}/', '<br/>', $sInput); ```
How to convert multiple <br/> tag to a single <br/> tag in php
[ "", "php", "html", "regex", "" ]
> **Edit**: Now I need to solve this problem for real, I did a little more > investigation and came up with a > number of things to reduce duplicate > content. I posted detailed code > samples on my blog: [Reducing > Duplicate Content with ASP.NET MVC](http://blog.dantup.me.uk/2009/04/reducing-duplicate-content-with-as...
Bump! **MVC 5** Now Supports producing only lowercase URLs and common trailing slash policy. ``` public static void RegisterRoutes(RouteCollection routes) { routes.LowercaseUrls = true; routes.AppendTrailingSlash = false; } ``` Also on my application to avoid duplicate content on differe...
I was working on this as well. I will obviously defer to ScottGu on this. I humbly offer my solution to this problem as well though. Add the following code to **global.asax**: ``` protected void Application_BeginRequest(Object sender, EventArgs e) { // If upper case letters are found in the URL, redirect to lower...
How can I avoid duplicate content in ASP.NET MVC due to case-insensitive URLs and defaults?
[ "", "c#", "asp.net", "asp.net-mvc", "razor", "" ]
Is there a way to make a Radio Button enabled/disabled (not checked/unchecked) via CSS? I've need to toggle some radio buttons on the client so that the values can be read on the server, but setting the 'enabled' property to 'false' then changing this on the client via javascript seems to prevent me from posting back ...
To the best of my knowledge CSS cannot affect the functionality of the application. It can only affect the display. So while you can hide it with css (display:none) you can't disable it. What you could do would be to disable it on page load with javascript. There are a couple ways to do this but an easy way would be t...
Disabled is a html attribute, not a css attribute. Why can't you just use some jQuery ``` $('#radiobuttonname').attr('disabled', 'true'); ``` or plain old javascript ``` document.getElementById(id).disabled = true; ```
Setting Radio Button enabled/disabled via CSS
[ "", "asp.net", "javascript", "css", "" ]
I have seen a few mentions of this idiom (including [on SO](https://stackoverflow.com/questions/9033/hidden-features-of-c#9282)): ``` // Deliberately empty subscriber public event EventHandler AskQuestion = delegate {}; ``` The upside is clear - it avoids the need to check for null before raising the event. **Howeve...
The only downside is a very slight performance penalty as you are calling extra empty delegate. Other than that there is no maintenance penalty or other drawback.
Instead of inducing performance overhead, why not [use an extension method](https://stackoverflow.com/questions/248072/evil-use-of-extension-methods) to alleviate both problems: ``` public static void Raise(this EventHandler handler, object sender, EventArgs e) { if(handler != null) { handler(sender, e...
Is there a downside to adding an anonymous empty delegate on event declaration?
[ "", "c#", "coding-style", "delegates", "events", "idioms", "" ]
I need to get UTF-8 working in my Java webapp (servlets + JSP, no framework used) to support `äöå` etc. for regular Finnish text and Cyrillic alphabets like `ЦжФ` for special cases. My setup is the following: * Development environment: Windows XP * Production environment: Debian Database used: MySQL 5.x Users mainl...
*Answering myself as the FAQ of this site encourages it. This works for me:* Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters. To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql r...
I think you summed it up quite well in your own answer. In the process of UTF-8-ing(?) from end to end you might also want to make sure java itself is using UTF-8. Use -Dfile.encoding=utf-8 as parameter to the JVM (can be configured in catalina.bat).
How to get UTF-8 working in Java webapps?
[ "", "java", "mysql", "tomcat", "encoding", "utf-8", "" ]
Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas? This works fine ``` ALTER TABLE documents ADD COLUMN membersOnly NUMBER ``` I want this to work: ``` ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0 ``` Ha...
Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database. then you can execute your query: ``` ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0 ```
With ADO, you can execute a DDL statement to create a field and set its default value. ``` CurrentProject.Connection.Execute _ "ALTER TABLE discardme ADD COLUMN membersOnly SHORT DEFAULT 0" ```
SQL to add column with default value - Access 2003
[ "", "sql", "ms-access", "" ]
Does anyone know if there is a c# Console app, similar to the Python or Ruby console? I know the whole "Compiled versus Interpreted" difference, but with C#'s reflection power I think it could be done. **UPDATE** Well, it only took about 200 lines, but I wrote a simple one...It works a lot like osql. You enter command...
Given your mention of "C#'s reflection power", I am unsure whether you're looking for an interactive C# console for small code snippets of your own (à la Ruby's `irb`), or a means of interacting with an existing, compiled application currently running as a process. In the former case: * **Windows PowerShell** might b...
Found this on reddit: <http://tirania.org/blog/archive/2008/Sep-08.html> Quote from the site: > The idea was simple: create an interactive C# shell by altering the compiler to generate and execute code dynamically as opposed to merely generating static code.
C# Console?
[ "", "c#", ".net", "console", "interactive", "" ]
I got a Function that returns a `Collection<string>`, and that calls itself recursively to eventually return one big `Collection<string>`. Now, i just wonder what the best approach to merge the lists? `Collection.CopyTo()` only copies to string[], and using a `foreach()` loop feels like being inefficient. However, sin...
If you're using List<> you can use .AddRange to add one list to the other list. Or you can use yield return to combine lists on the fly like this: ``` public IEnumerable<string> Combine(IEnumerable<string> col1, IEnumerable<string> col2) { foreach(string item in col1) yield return item; foreach(strin...
I think [`HashSet<T>`](http://msdn.microsoft.com/en-us/library/bb359438.aspx) is a great help. > The `HashSet<T>` class provides > high performance set operations. A set > is a collection that contains no > duplicate elements, and whose elements > are in no particular order. Just add items to it and then use CopyTo. ...
Merging two Collection<T>
[ "", "c#", "collections", "" ]
I am coming from an Enterprise Java background which involves a fairly heavyweight software stack, and have recently discovered the [Stripes framework](http://www.stripesframework.org/); my initial impression is that this seems to do a good job of minimising the unpleasant parts of building a web application in Java. ...
We've been using Stripes for about 4 years now. Our stack is Stripes/EJB3/JPA. Many use Stripes plus Stripernate as a single, full stack solution. We don't because we want our business logic within the EJB tier, so we simply rely on JPA Entities as combined Model and DTO. Stripes does the binding to our Entities/DTO ...
We use stripes now on all our production sites, and have been for about a year now. It is an awesome product compared to struts, which we used to use before that. Just the fact that there are literally no XML config files and that you can set it all up with a minimal amount of classes and annotations is awesome. In te...
Practical Experience using Stripes?
[ "", "java", "stripes", "" ]
I am thinking about making a website with some fairly intense JavaScript/canvas usage and I have been looking at [Processing.js](http://ejohn.org/blog/processingjs/) and it seems to me that it would make manipulating the canvas significantly easier. Does anyone know any reasons why I **shouldn't** use Processing.js? I ...
As mentioned, IE is not supported by Processing.js (including IE8 beta). I've also found processing.js to be a bit slow in terms of performance, compared to just using canvas (especially if you're parsing a string with Processing language, instead of using the javascript API). I personally prefer the canvas API over t...
If you're OK with it not working in IE7, then go for it. I've had it working in Firefox 3. It's a slick way to bring Silverlight/Flash effects to your page. My hunch is that libraries like Processing.js will change or be upgraded on a fast track path, so get ready to run when they do and keep up with the new features.
Is it reasonable to use John Resig's Processing.js?
[ "", "javascript", "graphics", "canvas", "" ]
Consider: ``` int testfunc1 (const int a) { return a; } int testfunc2 (int const a) { return a; } ``` Are these two functions the same in every aspect or is there a difference? I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well.
`const T` and `T const` are identical. With pointer types it becomes more complicated: 1. `const char*` is a pointer to a constant `char` 2. `char const*` is a pointer to a constant `char` 3. `char* const` is a constant pointer to a (mutable) `char` In other words, (1) and (2) are identical. The only way of making th...
The trick is to read the declaration backwards (right-to-left): ``` const int a = 1; // read as "a is an integer which is constant" int const a = 1; // read as "a is a constant integer" ``` Both are the same thing. Therefore: ``` a = 2; // Can't do because a is constant ``` The reading backwards trick especially co...
'const int' vs. 'int const' as function parameters in C++ and C
[ "", "c++", "c", "constants", "" ]
I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning. I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ide...
For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question. Instead you're going to have to basically check every query you make on the database for warnings: ``` $warningCountResult = mysql_query("SELECT @@warning_count"); if ($w...
First, you should [turn warnings off](http://us.php.net/error_reporting) so that your visitors don't see your **MySQL** errors. Second, when you call [`mysql_query()`](http://us.php.net/mysql_query), you should check to see if it returned false. If it did, call [`mysql_errno()`](http://us.php.net/manual/en/function.mys...
Can I detect and handle MySQL Warnings with PHP?
[ "", "php", "mysql", "error-handling", "warnings", "" ]
I want to add a comma in the thousands place for a number. Would `String.Format()` be the correct path to take? What format would I use?
``` $"{1234:n}"; // Output: 1,234.00 $"{9876:n0}"; // No digits after the decimal point. Output: 9,876 ```
I found this to be the simplest way: ``` myInteger.ToString("N0") ```
.NET String.Format() to add commas in thousands place for a number
[ "", "c#", ".net", "string", "format", "" ]
I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine. I tried using MySQL Administrator, but I got the following error: > The selected file was generated by > mysqldump and cannot be restored by > this application. How do I get this working?
It should be as simple as running this: ``` mysql -u <user> -p < db_backup.dump ``` If the dump is of a single database you may have to add a line at the top of the file: ``` USE <database-name-here>; ``` If it was a dump of many databases, the use statements are already in there. To run these commands, open up a ...
If the database you want to restore doesn't already exist, you need to create it first. On the command-line, if you're in the same directory that contains the dumped file, use these commands (with appropriate substitutions): ``` C:\> mysql -u root -p mysql> create database mydb; mysql> use mydb; mysql> source db_bac...
How do I restore a dump file from mysqldump?
[ "", "mysql", "sql", "database", "" ]
I want to insert say 50,000 records into sql server database 2000 at a time. How to accomplish this?
You can use the SELECT TOP clause: in MSSQL 2005 it was extended allowing you to use a variable to specify the number of records (older version allowed only a numeric constant) You can try something like this: (untested, because I have no access to a MSSQL2005 at the moment) ``` begin declare @n int, @rows int s...
Do you mean for a test of some kind? ``` declare @index integer set @index = 0 while @index < 50000 begin insert into table values (x,y,z) set @index = @index + 1 end ``` But I expect this is not what you mean. If you mean the best way to do a bulk insert, use `BULK INSERT` or something like `bcp`
Insert a fixed number of rows 2000 at a time in sql server
[ "", "sql", "sql-server", "" ]
In my free time I started writing a small multiplayer game with a database backend. I was looking to separate player login information from other in game information (inventory, stats, and status) and a friend brought up this might not be the best idea. Would it be better to lump everything together in one table?
Start by ignoring performance, and just create the most logical and easy-to-understand database design that you can. If players and game objects (swords? chess pieces?) are separate things conceptually, then put them in separate tables. If a player can carry things, you put a foreign key in the "things" table that refe...
Relational databases work on sets, a database query is there to deliver none ("not found") or more results. A relational database is not intended to deliver always exactly one result by executing a query (on relations). Said that I want to mention that there is real life, too ;-) . A one-to-one relation *might* make s...
One to One database relation?
[ "", "sql", "mysql", "database", "one-to-one", "" ]
What is the best method for adding options to a `<select>` from a JavaScript object using jQuery? I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there. This is what I did: ``` selectValues = { "1": "test 1", "2": "test 2" }; for (key in selectV...
The same as other answers, in a jQuery fashion: ``` $.each(selectValues, function(key, value) { $('#mySelect') .append($("<option></option>") .attr("value", key) .text(value)); }); ```
``` var output = []; $.each(selectValues, function(key, value) { output.push('<option value="'+ key +'">'+ value +'</option>'); }); $('#mySelect').html(output.join('')); ``` In this way you "touch the DOM" only one time. I'm not sure if the latest line can be converted into $('#mySelect').html(output.join('')) be...
What is the best way to add options to a select from a JavaScript object with jQuery?
[ "", "javascript", "jquery", "html-select", "" ]
We all know what virtual functions are in C++, but how are they implemented at a deep level? Can the vtable be modified or even directly accessed at runtime? Does the vtable exist for all classes, or only those that have at least one virtual function? Do abstract classes simply have a NULL for the function pointer o...
## How are virtual functions implemented at a deep level? From ["Virtual Functions in C++"](http://wayback.archive.org/web/20100209040010/http://www.codersource.net/published/view/325/virtual_functions_in.aspx): > Whenever a program has a virtual function declared, a v - table is constructed for the class. The v-tabl...
* Can the vtable be modified or even directly accessed at runtime? Not portably, but if you don't mind dirty tricks, sure! > **WARNING**: This technique is not recommended for use by children, adults under the age of [969](https://en.wikipedia.org/wiki/Methuselah), or small furry creatures from Alpha Centauri. Side e...
How are virtual functions and vtable implemented?
[ "", "c++", "polymorphism", "virtual-functions", "vtable", "" ]
In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so: ``` unsigned long value = 0xdeadbeef; value &= ~(1<<10); ``` How do I do that in Python ?
Bitwise operations on Python ints work much like in C. The `&`, `|` and `^` operators in Python work just like in C. The `~` operator works as for a signed integer in C; that is, `~x` computes `-x-1`. You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain th...
``` value = 0xdeadbeef value &= ~(1<<10) ```
How do I manipulate bits in Python?
[ "", "python", "" ]
What is the best method for removing a table row with jQuery?
You're right: ``` $('#myTableRow').remove(); ``` This works fine if your row has an `id`, such as: ``` <tr id="myTableRow"><td>blah</td></tr> ``` If you don't have an `id`, you can use any of jQuery's [plethora of selectors](http://docs.jquery.com/Selectors).
``` $('#myTable tr').click(function(){ $(this).remove(); return false; }); ``` Even a better one ``` $("#MyTable").on("click", "#DeleteButton", function() { $(this).closest("tr").remove(); }); ```
What is the best way to remove a table row with jQuery?
[ "", "javascript", "jquery", "html-table", "" ]
Assuming String a and b: ``` a += b a = a.concat(b) ``` Under the hood, are they the same thing? Here is concat decompiled as reference. I'd like to be able to decompile the `+` operator as well to see what that does. ``` public String concat(String s) { int i = s.length(); if (i == 0) { return thi...
No, not quite. Firstly, there's a slight difference in semantics. If `a` is `null`, then `a.concat(b)` throws a `NullPointerException` but `a+=b` will treat the original value of `a` as if it were `null`. Furthermore, the `concat()` method only accepts `String` values while the `+` operator will silently convert the a...
[Niyaz](https://stackoverflow.com/a/47615/662581) is correct, but it's also worth noting that the special + operator can be converted into something more efficient by the Java compiler. Java has a StringBuilder class which represents a non-thread-safe, mutable String. When performing a bunch of String concatenations, t...
String concatenation: concat() vs "+" operator
[ "", "java", "string", "concatenation", "" ]
In a text file, there is a string "I don't like this". However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use ``` f1 = open (file1, "r") text = f1.read() ``` command to do the reading. Now, is it possible to read the str...
Ref: <http://docs.python.org/howto/unicode> *Reading Unicode from a file is therefore simple:* ``` import codecs with codecs.open('unicode.rst', encoding='utf-8') as f: for line in f: print repr(line) ``` *It's also possible to open files in update mode, allowing both reading and writing:* ``` with code...
It is also possible to read an encoded text file using the python 3 read method: ``` f = open (file.txt, 'r', encoding='utf-8') text = f.read() f.close() ``` With this variation, there is no need to import any additional libraries
Character reading from file in Python
[ "", "python", "unicode", "encoding", "ascii", "" ]
Take the following two lines of code: ``` for (int i = 0; i < some_vector.size(); i++) { //do stuff } ``` And this: ``` for (some_iterator = some_vector.begin(); some_iterator != some_vector.end(); some_iterator++) { //do stuff } ``` I'm told that the second way is preferred. Why exactly is this?
The first form is efficient only if vector.size() is a fast operation. This is true for vectors, but not for lists, for example. Also, what are you planning to do within the body of the loop? If you plan on accessing the elements as in ``` T elem = some_vector[i]; ``` then you're making the assumption that the contai...
It's part of the modern C++ indoctrination process. Iterators are the only way to iterate most containers, so you use it even with vectors just to get yourself into the proper mindset. Seriously, that's the only reason I do it - I don't think I've ever replaced a vector with a different kind of container. --- Wow, th...
Why use iterators instead of array indices?
[ "", "c++", "for-loop", "stl", "iterator", "containers", "" ]
I've got a C# class with a `Dispose` function via `IDisposable`. It's intended to be used inside a `using` block so the expensive resource it handles can be released right away. The problem is that a bug occurred when an exception was thrown before `Dispose` was called, and the programmer neglected to use `using` or `...
Unfortunately there isn't any way to do this directly in the code. If this is an issue in house, there are various code analysis solutions that could catch these sort of problems. Have you looked into FxCop? I think that this will catch these situations and in all cases where IDisposable objects might be left hanging. ...
Where I work we use the following guidelines: * Each IDisposable class **must** have a finalizer * Whenever using an IDisposable object, it must be used inside a "using" block. The only exception is if the object is a member of another class, in which case the containing class must be IDisposable and must call the mem...
How to do C++ style destructors in C#?
[ "", "c#", "dispose", "idisposable", "using", "" ]
I'm using jQuery to add an additional row to a table as the last row. I have done it this way: ``` $('#myTable').append('<tr><td>my data</td><td>more data</td></tr>'); ``` Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?
The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a `tbody` for example: ``` <table id="myTable"> <tbody> <tr>...</tr> <tr>...</tr> </tbody> </table> ``` You would end up with the following: ``` <table id="myTable"> <tbody> <tr>...</tr> <tr>....
jQuery has a built-in facility to manipulate DOM elements on the fly. **You can add anything to your table like this:** ``` $("#tableID").find('tbody') .append($('<tr>') .append($('<td>') .append($('<img>') .attr('src', 'img.png') .text('Image cell') ...
Adding a table row in jQuery
[ "", "javascript", "jquery", "html-table", "" ]
## Question Can I build a image database/library that has an e-commerce style checkout system and a powerful search in Oracle/Java? Are there existing elements out there I should be aware of? Or, is this better in another dev environment like PHP/MySQL? ## Overview I am working on an image database/library dev team ...
Seems your question is really a struggle between Oracle/Java and PHP/MySQL. The details you state are none too difficult to implement using either of these tools sets or using a dozen others that I could think of. If I am correct (only you could know), then this is a fabulous opportunity for you. You seem to have expe...
Thanks **David** and **dacracot** for your insights. Upon further review and consultation (plus some leveraging) of our IT department, considering that this app and DB would run on their own server, and apparently other areas of the corporation have approved the use of open server technologies like PHP, SQL and Apache...
Image database build in Oracle - Is an e-commerce style interface workable?
[ "", "java", "oracle", "" ]
I'd like to find a way to determine how long each function in PHP, and each file in PHP is taking to run. I've got an old legacy PHP application that I'm trying to find the "rough spots" in and so I'd like to locate which routines and pages are taking a very long time to load, objectively. Are there any pre-made tools...
I have actually done some optimisation work last week. XDebug is indeed the way to go. Just enable it as an extension (for some reason it wouldn't work with ze\_extension on my windows machine) , setup your php.ini with xdebug.profiler\_enable\_trigger=On and call your normal urls with XDEBUG\_PROFILE=1 as either a ge...
**Here is a nice tip.** When you use XDebug to profile your PHP, set up the profiler\_trigger and use this in a bookmarklet to trigger the XDebug profiler ;) ``` javascript:if(document.URL.indexOf('XDEBUG_PROFILE')<1){var%20sep=document.URL.indexOf('?');sep%20=%20(sep<1)?'?':'&';window.location.href=document.URL+sep+...
Profiling PHP code
[ "", "php", "performance", "profiling", "" ]
When I use the task, the property is only set to TRUE if the resource (say file) is available. If not, the property is undefined. When I print the value of the property, it gives true if the resource was available, but otherwise just prints the property name. Is there a way to set the property to some value if the re...
You can use a condition in combination with not: <http://ant.apache.org/manual/Tasks/condition.html> ``` <condition property="fooDoesNotExist"> <not> <available filepath="path/to/foo"/> </not> </condition> ```
``` <available filepath="/path/to/foo" property="foosThere" value="true"/> <property name="foosThere" value="false"/> ``` The assignment of foosThere will only be successful if it has not already been set to true by your availability check.
Ant and the available task - what if something is not available?
[ "", "java", "ant", "build", "" ]
I'm running a SQL query on SQL Server 2005, and in addition to 2 columns being queried from the database, I'd also like to return 1 column of random numbers along with them. I tried this: ``` select column1, column2, floor(rand() * 10000) as column3 from table1 ``` Which kinda works, but the problem is that this que...
I realize this is an older post... but you don't need a view. ``` select column1, column2, ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 10000 as column3 from table1 ```
**WARNING** [Adam's answer](https://stackoverflow.com/questions/94906/how-do-i-return-random-numbers-as-a-column-in-sql-server-2005/94951#94951) involving the view is very inefficient and for very large sets can take out your database for quite a while, I would strongly recommend against using it on a regular basis or...
How do I return random numbers as a column in SQL Server 2005?
[ "", "sql", "sql-server", "sql-server-2005", "random", "" ]
What tools do you use to find unused/dead code in large java projects? Our product has been in development for some years, and it is getting very hard to manually detect code that is no longer in use. We do however try to delete as much unused code as possible. Suggestions for general strategies/techniques (other than...
I would instrument the running system to keep logs of code usage, and then start inspecting code that is not used for months or years. For example if you are interested in unused classes, all classes could be instrumented to log when instances are created. And then a small script could compare these logs against the c...
An Eclipse plugin that works reasonably well is [Unused Code Detector](http://www.ucdetector.org/). It processes an entire project, or a specific file and shows various unused/dead code methods, as well as suggesting visibility changes (i.e. a public method that could be protected or private).
How to find unused/dead code in java projects
[ "", "java", "refactoring", "dead-code", "" ]
I have a table with game scores, allowing multiple rows per account id: `scores (id, score, accountid)`. I want a list of the top 10 scorer ids and their scores. Can you provide an sql statement to select the top 10 scores, but only one score per account id? Thanks!
First limit the selection to the highest score for each account id. Then take the top ten scores. ``` SELECT TOP 10 AccountId, Score FROM Scores s1 WHERE AccountId NOT IN (SELECT AccountId s2 FROM Scores WHERE s1.AccountId = s2.AccountId and s1.Score > s2.Score) ORDER BY Score DESC ```
``` select username, max(score) from usertable group by username order by max(score) desc limit 10; ```
Fetch one row per account id from list
[ "", "sql", "mysql", "database", "" ]
The Weblogic servers we are using have been configured to allow JNDI datasource names like "appds". For development (localhost), we might be running Tomcat and when declared in the <context> section of server.xml, Tomcat will hang JNDI datasources on "java:comp/env/jdbc/\*" in the JNDI tree. **Problem:** in Weblogic,...
`JndiLocatorSupport` has a property `resourceRef`. When setting this true, "java:comp/env/" prefix will be prepended automatically. So I believe it would be correct to differentiate this parameter when moving from Tomcat to Weblogic.
**How to use a single JNDI name in your web app** I've struggled with this for a few months myself. The best solution is to make your application portable so you have the same JNDI name in both Tomcat and Weblogic. In order to do that, you change your `web.xml` and `spring-beans.xml` to point to a single jndi name, a...
Tomcat vs Weblogic JNDI Lookup
[ "", "java", "tomcat", "jakarta-ee", "weblogic", "jndi", "" ]
I'm looking for a standard way to connect to databases in PHP. We've all been there - first start with some rudimentary code to connect/query/iterate/insert/disconnect, then the code grew as the program grew, and it ended up with a mess that's hardly reusable. I know there are many PEAR, PECL, and other PHP libraries/...
I'm supprised *Zend\_Db* hasn't been mentioned yet... * PEAR's **MDB2**: very stable, also provides a layer that implements all *MDB2*-supported features in all databases where it can at least be simulated. I've used this one for years with much success. * Zend Framework's **Zend\_Db**: I've just started using the hig...
if you're using PHP 5 [try out PDO](http://php.net/pdo)
Standard connection libraries for MySQL, MSSQL, and Oracle in PHP
[ "", "php", "database", "" ]
I've been writing PHP web applications for some time, and have come across very nice Javascript frameworks, such as JQuery, ExtJS, Scriptaculous, etc. I can't say the same about the PHP side - I always coded that part of the client-server dialog from scratch. I've used CodeIgniter (<http://codeigniter.com/>) and it is...
The [Zend Framework](http://framework.zend.com/) is integrated with [Dojo Toolkit](http://dojotoolkit.org/). I haven't used the latest Zend Framework yet, but I do know that in the past, it has proven to be reliable.
There might be one but I can't imagine why. An AJAX request looks and acts just like an HTTP request from the perspective of the server. You can get and set cookies. All the environment variables that you would expect from an HTTP request are there. All of the HTTP verbs work as do any of the header fields.
Integrating AJAX and PHP
[ "", "php", "ajax", "frameworks", "integration", "" ]
I've got a class that I'm using as a settings class that is serialized into an XML file that administrators can then edit to change settings in the application. (The settings are a little more complex than the `App.config` allows for.) I'm using the `XmlSerializer` class to deserialize the XML file, and I want it to b...
You have to use a mutable list type, like ArrayList (or IList IIRC).
I dont think you can use the automatic serialization since the property is read only. My course of action would be to implement the [ISerializable](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx) interface and do it manually. You will be able to set the internal values from her...
How do I deserialize an XML file into a class with a read only property?
[ "", "c#", ".net", "xml", "xml-serialization", "" ]
I'm trying to perform a bitwise NOT in SQL Server. I'd like to do something like this: ``` update foo set Sync = NOT @IsNew ``` Note: I started writing this and found out the answer to my own question before I finished. I still wanted to share with the community, since this piece of documentation was lacking on MSDN ...
Yes, the ~ operator will work. ``` update foo set Sync = ~@IsNew ```
**Bitwise NOT: ~** Bitwise AND: & Bitwise OR: | Bitwise XOR: ^
How do I flip a bit in SQL Server?
[ "", "sql", "sql-server", "bit-manipulation", "" ]
Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature. After a little digging, I found that I could do something like the following: ``` class MyClass { protected: bool...
What you have there is a pointer-to-member-function. It will solve your problem. I am surprised that your "TestSwitch" function compiles, as the calling syntax is slightly different to what you might expect. It should be: ``` bool res = (this->*CaseMethod)( 999, "hello world" ); ``` However, you might find a combinat...
You could also build a lookup (if your key range is reasonable) so that you end up writing: ``` this->*Methods[num]( 999, "hello world" ); ``` This removes the switch as well, and makes the cleanup a bit more worthwhile.
Pointers to C++ class methods
[ "", "c++", "" ]
I am using RRDTool (<http://oss.oetiker.ch/rrdtool/>) as a graphing back-end for storing performance metrics. This is done via the RRDTool CLI from a Python script. My problem is that the script is multithreaded and each thread updates the RRD at a pretty rapid pace. Sometimes an update fails because one thread is acc...
An exclusive lock ought to be enough for this problem : * [Python doc page](http://docs.python.org/lib/lock-objects.html) * [Use example](http://effbot.org/zone/thread-synchronization.htm) Define your lock object at the main level, not at the thread level, and you're done. Edit in Response to comment : if you defin...
You could also try using rrdcached to do the updates. Then all write updates will be serialised through rrdcached. When you want to read the RRD to generate graphs you tell the daemon to flush it and the on-disk RRD will then represent the latest state. All the RRD tools will do this transparently if pointed at the ca...
Concurrent Access to RRD (RRDTool)
[ "", "python", "rrdtool", "" ]
I've implemented a basic search for a research project. I'm trying to make the search more efficient by building a [suffix tree](http://en.wikipedia.org/wiki/Suffix_tree). I'm interested in a C# implementation of the [Ukkonen](http://en.wikipedia.org/wiki/Ukkonen%27s_algorithm) algorith. I don't want to waste time roll...
Hei, just finished implementing .NET (c#) library containing different trie implementations. Among them: * Classical trie * Patricia trie * Suffix trie * A trie using **Ukkonen's** algorithm I tried to make source code easy readable. Usage is also very straight forward: ``` using Gma.DataStructures.StringSearch; .....
Hard question. Here's the closest to match I could find: <http://www.codeproject.com/KB/recipes/ahocorasick.aspx>, which is an implementation of the Aho-Corasick string matching algorithm. Now, the algorithm uses a suffix-tree-like structure per: <http://en.wikipedia.org/wiki/Aho-Corasick_algorithm> Now, if you want a...
Looking for the suffix tree implementation in C#?
[ "", "c#", "data-structures", "suffix-tree", "" ]
I am trying to implement position-sensitive zooming inside a `JScrollPane`. The `JScrollPane` contains a component with a customized `paint` that will draw itself inside whatever space it is allocated - so zooming is as easy as using a `MouseWheelListener` that resizes the inner component as required. But I also want ...
Tested this, seems to work... ``` private void updatePreferredSize(int n, Point p) { double d = (double) n * 1.08; d = (n > 0) ? 1 / d : -d; int w = (int) (getWidth() * d); int h = (int) (getHeight() * d); preferredSize.setSize(w, h); int offX = (int)(p.x * d) - p.x; int offY = (int)(p.y ...
Here's a minor refactoring of @Kevin K's solution: ``` private void updatePreferredSize(int wheelRotation, Point stablePoint) { double scaleFactor = findScaleFactor(wheelRotation); scaleBy(scaleFactor); Point offset = findOffset(stablePoint, scaleFactor); offsetBy(offset); getParent().doLayout(); }...
How do you implement position-sensitive zooming inside a JScrollPane?
[ "", "java", "swing", "user-interface", "zooming", "" ]
I've always been able to allocate 1400 megabytes for Java SE running on 32-bit Windows XP (Java 1.4, 1.5 and 1.6). ``` java -Xmx1400m ... ``` Today I tried the same option on a new Windows XP machine using Java 1.5\_16 and 1.6.0\_07 and got the error: ``` Error occurred during initialization of VM Could not reserve ...
Keep in mind that Windows has virtual memory management and the JVM only needs memory that is contiguous *in its address space*. So, other programs running on the system shouldn't necessarily impact your heap size. What will get in your way are DLL's that get loaded in to your address space. Unfortunately optimizations...
This has to do with contiguous memory. [Here's some info I found online](http://www.unixville.com/~moazam/) for somebody asking that before, supposedly from a "VM god": > The reason we need a contiguous memory > region for the heap is that we have a > bunch of side data structures that are > indexed by (scaled) offse...
Java maximum memory on Windows XP
[ "", "java", "windows", "memory", "" ]
I need to make sure that user can run only one instance of my program at a time. Which means, that I have to check programatically, whether the same program is already running, and quit in such case. The first thing that came to my mind was to create a file somewhere, when the program starts. Then, each other instan...
There are several methods you can use to accomplish only allowing one instance of your application: **Method 1: Global synchronization object or memory** It's usually done by creating a named global mutex or event. If it is already created, then you know the program is already running. For example in windows you cou...
Your method of writing the process pid to a file is a common one that is used in many different established applications. In fact, if you look in your `/var/run` directory right now I bet you'll find several `*.pid` files already. As you say, it's not 100% robust because there is chance of the pids getting confused. I...
How to block running two instances of the same program?
[ "", "c++", "" ]
I'm writing a log file viewer for a web application and I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom. So I need a `tail()` method that can read `n` lines from the bottom and support an offset. This is what I came up with: ``` def tail(f,...
The code I ended up using. I think this is the best so far: ``` def tail(f, n, offset=None): """Reads a n lines from f with an offset of offset lines. The return value is a tuple in the form ``(lines, has_more)`` where `has_more` is an indicator that is `True` if there are more lines in the file. """ ...
This may be quicker than yours. Makes no assumptions about line length. Backs through the file one block at a time till it's found the right number of '\n' characters. ``` def tail( f, lines=20 ): total_lines_wanted = lines BLOCK_SIZE = 1024 f.seek(0, 2) block_end_byte = f.tell() lines_to_go = tot...
Get last n lines of a file, similar to tail
[ "", "python", "file", "file-io", "tail", "logfile", "" ]
What might be the best way to start programming using boost lambda libraries.
Remaining within the boundaries of the C++ language and libraries, I would suggest first getting used to programming using STL algorithm function templates, as one the most common use you will have for boost::lambda is to replace functor classes with inlined expressions inlined. The library documentation itself gives ...
Depends. Are you already well versed in functional programming concepts? If not, I'd suggest that you start in a language that is designed for functional programming instead of a procedural language with functional features stapled on. If you aren't used to coding in a functional style (it's not *harder* necessarily, b...
c++ boost lambda libraries
[ "", "c++", "functional-programming", "boost-lambda", "" ]
I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance? I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers.
You're going to have to do this as a separate query, for example: ``` SELECT COUNT(1) FROM table_name ``` Some JDBC drivers might tell you but this is optional behaviour and, more to the point, the driver may not know yet. This can be due to how the query is optimised eg two example execution strategies in Oracle are...
``` ResultSet rs = stmt.executeQuery(sql); int rowCount = rs.last() ? rs.getRow() : 0; // Number of rows in result set. Don't forget to set cyrsor to beforeFirst() row! :) ```
How do I get the row count in JDBC?
[ "", "java", "jdbc", "resultset", "" ]
I've been battling PHP's email reading functions for the better part of two days. I'm writing a script to read emails from a mailbox and save any attachments onto the server. If you've ever done something similar, you might understand my pain: **PHP doesn't play well with email!** I've connected to the POP3 server and...
I found a quick guide how to treat emails with PHP: [here](http://www.linuxscope.net/articles/mailAttachmentsPHP.html). At the bottom of that page there's a attachment-body `echo`: ``` if (substr($ContentType,0,4) == "text") { echo imap_qprint($fileContent); } else { echo imap_base64($fileContent); } ``` I guess thi...
MIME data is base-64 encoded, so I think you should be able to decode it using base64\_decode
How can I save email attachments to the server in PHP?
[ "", "php", "email", "mime", "" ]
Yesterday, I asked [this](https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby) question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby withou...
In Ruby: ``` a = (0..100).entries.sort_by {rand}.slice! 0, 5 ``` **Update**: Here is a slightly different way: a = (0...100).entries.sort\_by{rand}[0...5] **EDIT:** and In Ruby 1.9 you can do this: ``` Array(0..100).sample(5) ```
``` >>> import random >>> print random.sample(xrange(100), 5) [61, 54, 91, 72, 85] ``` This should yield 5 unique values in the range `0 — 99`. The `xrange` object generates values as requested so no memory is used for values that aren't sampled.
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python?
[ "", "python", "ruby", "linq", "functional-programming", "" ]
I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to: ``` var obj1 = { food: 'pizza', car: 'ford' } var obj2 = { animal: 'dog' } obj1.merge(obj2); //obj1 now has three properties: food, car, and animal ``` Is there a built in way to do this? I do not need recursion, an...
**ECMAScript 2018 Standard Method** You would use [object spread](https://github.com/tc39/proposal-object-rest-spread): ``` let merged = {...obj1, ...obj2}; ``` `merged` is now the union of `obj1` and `obj2`. Properties in `obj2` will overwrite those in `obj1`. ``` /** There's no limit to the number of objects you ...
jQuery also has a utility for this: <http://api.jquery.com/jQuery.extend/>. Taken from the jQuery documentation: ``` // Merge options object into settings object var settings = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; jQuery.extend(settings, options); // Now the con...
How can I merge properties of two JavaScript objects?
[ "", "javascript", "javascript-objects", "" ]
Does anyone have experience using makefiles for Visual Studio C++ builds (under VS 2005) as opposed to using the project/solution setup. For us, the way that the project/solutions work is not intuitive and leads to configuruation explosion when you are trying to tweak builds with specific compile time flags. Under Uni...
I've found some benefits to makefiles with large projects, mainly related to unifying the location of the project settings. It's somewhat easier to manage the list of source files, include paths, preprocessor defines and so on, if they're all in a makefile or other build config file. With multiple configurations, addin...
Visual studio is being built on top of the [MSBuild](http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx) configurations files. You can consider \*proj and \*sln files as makefiles. They allow you to fully customize build process.
Using Makefile instead of Solution/Project files under Visual Studio (2005)
[ "", "c++", "visual-studio", "makefile", "" ]
Has anyone ever heard of a UNIX shell written in a reasonable language, like Python?
* [Eshell](http://www.gnu.org/software/emacs/manual/html_node/eshell/index.html) is a Bash-like shell in Emacs Lisp. * IPython can be [used as a system shell](http://ipython.org/ipython-doc/stable/interactive/shell.html), though the syntax is a bit weird (supporting all of Python plus basic sh constructs). * [fish](htt...
[iPython](http://ipython.scipy.org/moin/) (Python) and [Rush](http://rush.heroku.com/) (Ruby) are shells that are designed for more advanced languages. There's also Hotwire, which is sort of a weird integrated shell/terminal emulator.
UNIX shell written in a reasonable language?
[ "", "python", "unix", "shell", "" ]
Is there an easy way to marshal a PHP associative array to and from XML? For example, I have the following array: ``` $items = array("1", "2", array( "item3.1" => "3.1", "item3.2" => "3.2" "isawesome" => true ) ); ``` How would I turn it into something similar to the following XML in a...
For those of you not using the PEAR packages, but you've got PHP5 installed. This worked for me: ``` /** * Build A XML Data Set * * @param array $data Associative Array containing values to be parsed into an XML Data Set(s) * @param string $startElement Root Opening Tag, default fx_request * @param string $xml_ve...
[SimpleXML](http://php.net/simplexml) works great for your use.
Passing PHP associative arrays to and from XML
[ "", "php", "xml", "xml-serialization", "" ]
My app keeps track of the state of about 1000 objects. Those objects are read from and written to a persistent store (serialized) in no particular order. Right now the app uses the registry to store each object's state. This is nice because: * It is simple * It is very fast * Individual object's state can be read/wri...
If you do begin to experiment with SQLite, you should know that "out of the box" it might not seem as fast as you would like, but it can quickly be made to be much faster by applying some established optimization tips: [SQLite optimization](http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html "sqlite speed t...
If what you mean by 'multiple-reader/multiple-writer' is that you keep a lot of threads writing to the store concurrently, SQLite is threadsafe (you can have concurrent SELECTs and concurrent writes are handled transparently). See the [FAQ [1]] and grep for 'threadsafe' [1]: <http://www.sqlite.org/faq.html/> FAQ
Fastest small datastore on Windows
[ "", "c++", "windows", "data-structures", "caching", "registry", "" ]
We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossM...
You should implement in your client code javax.jms.ExceptionListener. You will need a method called onException. When the client's connection is lost, you should get a JMSException, and this method will be called automatically. The only thing you have to look out for is if you are intentionally disconnecting from JBoss...
I'd highly recommend you use the [Spring abstractions for JMS such as the MessageListenerContainer](http://static.springframework.org/spring/docs/2.5.x/reference/jms.html#jms-mdp) to deal with reconnection, transactions and pooling for you. You just need to supply a MessageListener and configure the MessageListenerCont...
Reconnecting JMS listener to JBossMQ
[ "", "java", "jboss", "jms", "jbossmq", "" ]
I'm generating a ton of XML that is to be passed to an API as a post variable when a user click on a form button. I also want to be able to show the user the XML before hand. The code is sorta like the following in structure: ``` <?php $lots of = "php"; ?> <xml> <morexml> <?php while(){ ?> <somegene...
``` <?php ob_start(); ?> <xml/> <?php $xml = ob_get_clean(); ?> <input value="<?php echo $xml ?>" />͏͏͏͏͏͏ ```
Put this at your start: ``` ob_start(); ``` And to get the buffer back: ``` $value = ob_get_contents(); ob_end_clean(); ``` See <https://www.php.net/manual/en/ref.outcontrol.php> and the individual functions for more information.
How do I capture PHP output into a variable?
[ "", "php", "xml", "" ]
I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)
Yeah, gdb is good for lower level debugging. You can change threads with the *thread* command. e.g ``` (gdb) thr 2 [Switching to thread 2 (process 6159 thread 0x3f1b)] (gdb) backtrace .... ``` You could also check out Python specific debuggers like [Winpdb](http://winpdb.org/about/), or [pydb](http://bashdb.sourcef...
Use [Winpdb](http://winpdb.org/). It is a **platform independent** graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb. Features: * GPL license. Winpdb is Free Softwa...
Is there a way to attach a debugger to a multi-threaded Python process?
[ "", "python", "debugging", "" ]
Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about ``` for i in range(0, 20): for i in xrange(0, 20): ```
**In Python 2.x:** * `range` creates a list, so if you do `range(1, 10000000)` it creates a list in memory with `9999999` elements. * `xrange` is a sequence object that evaluates lazily. **In Python 3:** * `range` does the equivalent of Python 2's `xrange`. To get the list, you have to explicitly use `list(range(......
> range creates a list, so if you do `range(1, 10000000)` it creates a list in memory with `9999999` elements. > > `xrange` ~~is a generator, so it~~ is a sequence object ~~is a~~ that evaluates lazily. This is true, but in Python 3, `range()` will be implemented by the Python 2 `xrange()`. If you need to actually gen...
What is the difference between range and xrange functions in Python 2.X?
[ "", "python", "loops", "range", "python-2.x", "xrange", "" ]
I'm trying to Unit Test a class that has many internal functions. These obviously need testing too, but my Tests project is seperate, mainly because it covers many small, related projects. What I have so far is: ``` FieldInfo[] _fields = typeof(ButtonedForm.TitleButton).GetFields( BindingFlags.NonPublic |...
It would be more appropriate to use the [`InternalsVisibleTo`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) attribute to grant access to the internal members of the assembly to your unit test assembly. Here is a link with some helpful additional info and a w...
Adding the [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) assembly level attribute to your main project, with the Assembly name of thre test project should make internal members visible. For example add the following to your assembly outsi...
Accessing internal members via System.Reflection?
[ "", "c#", ".net", "reflection", "internal", "" ]
Is there an easy method to store a person's user settings in a sql 2000 database. Ideally all settings in one field so I don't keep having to edit the table every time I add a setting. I am thinking along the lines of serialize a settings class if anyone has an example. The reason I don't want to use the built in .NET...
The VS designer keeps property settings in the [ApplicationSettingsBase](http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx) class. By default, these properties are serialized/deserialized into a per user XML file. You can override this behavior by using a custom [SettingsProvider...
you can easily serialize classes in C#: <http://www.google.com/search?q=c%23+serializer>. You can either store the XML in a varchar field, or if you want to use the binary serializer, you can store it in an "Image" datatype, which is really just binary.
c# store user settings in database
[ "", "c#", ".net", "database", "repost", "" ]
Anyone have a quick method for de-duplicating a generic List in C#?
Perhaps you should consider using a [HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx). From the MSDN link: ``` using System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> evenNumbers = new HashSet<int>(); HashSet<int> oddNumbers = new HashS...
If you're using .Net 3+, you can use Linq. ``` List<T> withDupes = LoadSomeData(); List<T> noDupes = withDupes.Distinct().ToList(); ```
Remove duplicates from a List<T> in C#
[ "", "c#", "list", "generics", "duplicates", "" ]
Using the Python Documentation I found the [HTML parser](http://docs.python.org/lib/module-HTMLParser.html) but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).
Try: ``` import HTMLParser ``` In Python 3.0, the HTMLParser module has been renamed to html.parser you can check about this [here](http://docs.python.org/library/htmlparser.html) Python 3.0 ``` import html.parser ``` Python 2.2 and above ``` import HTMLParser ```
You probably really want [BeautifulSoup](https://stackoverflow.com/questions/55391/python-regular-expression-for-html-parsing-beautifulsoup#55424), check the link for an example. But in any case ``` >>> import HTMLParser >>> h = HTMLParser.HTMLParser() >>> h.feed('<html></html>') >>> h.get_starttag_text() '<html>' >>...
HTML parser in Python
[ "", "python", "import", "" ]
I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing. problem statement: * a user enters several keywords/tokens * the application searches for matches to the tokens * need one result for each token + ie,...
you could achive this in one query using 'UNION ALL' in MySQL. Just loop through the tokens in PHP creating a UNION ALL for each token: e.g if the tokens are 'x', 'y' and 'z' your query may look something like this ``` SELECT * FROM `entries` WHERE token like "%x%" union all SELECT * FROM `entries` WHERE ...
I know this isn't strictly an answer to the question you're asking **but if your table is thousands rather than millions of rows**, then a FULLTEXT solution might be the best way to go here. In MySQL when you use MATCH on your indexed column, each keyword you supply will be given a relevance score (calculated roughly ...
How-to: Ranking Search Results
[ "", "php", "mysql", "search", "" ]
When should you use generator expressions and when should you use list comprehensions in Python? ``` # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ```
[John's answer](https://stackoverflow.com/a/47792/4518341) is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work: ``` def gen...
Iterating over the *generator expression* or the *list comprehension* will do the same thing. However, the *list comprehension* will create the entire list in memory first while the *generator expression* will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.
Generator expressions vs. list comprehensions
[ "", "python", "list-comprehension", "generator-expression", "" ]
Using C# How do you remove a specific node from an XMLDocument using XPATH?
XPath can only select nodes from a document, not modify the document.
If you want to delete nodes, that are not direct children of the documents root, you can do this: ``` XmlDocument doc = new XmlDocument(); // ... fill or load the XML Document XmlNode childNode = doc.SelectSingleNode("/rootnode/childnode/etc"); // apply your xpath here childNode.ParentNode.RemoveChild(childNode); ```
.NET : How do you remove a specific node from an XMLDocument using XPATH?
[ "", "c#", ".net", "xpath", "" ]
I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I'm not sure the "best practice" in this case. **Simple Example** This class is defined in Assembly1: ``` public class Class2Test { private readonly string _StringProperty; ...
Nothing, unless you are using that field. You don't want over-specification via tests. In other words, there is no need to test that the assignment operator works. If you are using that field in a method or something, call that method and assert on that. Edit: > assume the constructor has some more complex logic Yo...
I have properly enabled `[InternalsVisibleTo]` on Assembly1 (code) so that there is a trust relationship with Assembly2 (tests). ``` public class Class2Test { private readonly string _StringProperty; internal string StringProperty { get { return _StringProperty; } } public Class2Test(string stringProperty...
How to unit test immutable class constructors?
[ "", "c#", "unit-testing", "" ]
I basically have an xml column, and I need to find and replace one tag value in each record.
For anything real, I'd go with xpaths, but sometimes you just need a quick and dirty solution: You can use CAST to turn that xml column into a regular varchar, and then do your normal replace. `UPDATE xmlTable SET xmlCol = REPLACE( CAST( xmlCol as varchar(max) ), '[search]', '[replace]')` That same technique also ma...
To find a content in an XML column, look into the exist() method, as described in MSDN [here](http://msdn.microsoft.com/en-us/library/ms189869(SQL.90).aspx). ``` SELECT * FROM Table WHERE XMLColumn.exist('/Root/MyElement') = 1 ``` ...to replace, use the modify() method, as described [here](http://msdn.microsoft.com/e...
Can I do a find/replace in t-sql?
[ "", "sql", "xml", "t-sql", "" ]
What tools and techniques do you use to find dead code in .NET? In the past, I've decorated methods with the Obsolete attribute (passing true so the compiler will issue an error, as described in [MSDN](http://msdn.microsoft.com/en-us/library/aa664623.aspx)). I'd be interested in seeing the suggestions of others (beyo...
TDD + NCover
Why do you need other answers? FxCop and Resharper do the trick, especially seeing as FxCop is now integrated into VS through "Code Analysis".
What tools and techniques do you use to find dead code?
[ "", "c#", ".net", "refactoring", "code-analysis", "" ]
Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own `ClassLoader`, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR ...
The reason it's hard is security. Classloaders are meant to be immutable; you shouldn't be able to willy-nilly add classes to it at runtime. I'm actually very surprised that works with the system classloader. Here's how you do it making your own child classloader: ``` URLClassLoader child = new URLClassLoader( ...
The following solution is hackish, as it uses reflection to bypass encapsulation, but it works flawlessly: ``` File file = ... URL url = file.toURI().toURL(); URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); m...
How to load JAR files dynamically at Runtime?
[ "", "java", "jar", "classloader", "" ]
I know that the #warning directive is not standard **C**/C++, but several compilers support it, including gcc/g++. But for those that don't support it, will they silently ignore it or will it result in a compile failure? In other words, can I safely use it in my project without breaking the build for compilers that don...
It is likely that if a compiler doesn't support #warning, then it will issue an error. Unlike #pragma, there is no recommendation that the preprocessor ignore directives it doesn't understand. Having said that, I've used compilers on various different (reasonably common) platforms and they have all supported #warning.
It should be noted that MSVC uses the syntax: ``` #pragma message ( "your warning text here" ) ``` The usual #warning syntax generates a fatal error ``` C1021: invalid preprocessor command 'warning' ``` so it is not portable to those compilers.
Portability of #warning preprocessor directive
[ "", "c++", "compiler-construction", "warnings", "c-preprocessor", "portability", "" ]
Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with: ``` import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val...
You can merge all your regexes into one using the "|" operator and let the regex library do the work of discerning between tokens. Some care should be taken to ensure the preference of tokens (for example to avoid matching a keyword as an identifier).
I suggest using the re.Scanner class, it's not documented in the standard library, but it's well worth using. Here's an example: ``` import re scanner = re.Scanner([ (r"-?[0-9]+\.[0-9]+([eE]-?[0-9]+)?", lambda scanner, token: float(token)), (r"-?[0-9]+", lambda scanner, token: int(token)), (r" +", lambda ...
Efficiently match multiple regexes in Python
[ "", "python", "regex", "lexical-analysis", "" ]
I am using REPLACE in an SQL view to remove the spaces from a property number. The function is setup like this REPLACE(pin, ' ', ''). On the green-screen the query looked fine. In anything else we get the hex values of the characters in the field. I am sure it is an encoding thing, but how do I fix it? Here is the sta...
We ended up using concat and substring to get the results we wanted. ``` CREATE VIEW RLIC2GIS AS SELECT CONCAT(SUBSTR(RCAPIN,1,3),CONCAT(SUBSTR(RCAPIN,5,2), CONCAT(SUBSTR(RCAPIN,8,2), CONCAT(SUBSTR(RCAPIN,11,3), SUBSTR(RCAPIN, 15,3))))) AS CAPIN13, RLICNO, RONAME, ROA...
The problem here might be that what you think is the blank character in that field is actually some other unprintable character. You can use the following SQL to see what ASCII character is at the 4th position: ``` SELECT ascii(substr(RCAPIN,4,1)) FROM YOUR-TABLE ``` Then you would be able to use a replace for that...
Weird Output on SQL REPLACE
[ "", "sql", "ibm-midrange", "" ]
In the Java collections framework, the Collection interface declares the following method: > [`<T> T[] toArray(T[] a)`](http://java.sun.com/javase/6/docs/api/java/util/Collection.html#toArray(T%5B%5D)) > > Returns an array containing all of the elements in this collection; the runtime type of the returned array is tha...
Use the static method ``` java.lang.reflect.Array.newInstance(Class<?> componentType, int length) ``` A tutorial on its use can be found here: <http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html>
By looking at how ArrayList does it: ``` public <T> T[] toArray(T[] a) { if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } ```
How to instantiate a Java array given an array type at runtime?
[ "", "java", "arrays", "collections", "" ]
I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with `e.preventDefault()` and runs an AJAX command. This works fine when the submit button is clicked but when a link with `onclick='document.formName.submit();'` is clicked, the event is not ca...
A couple of suggestions: * Overwrite the submit function to do your evil bidding ``` var oldSubmit = form.submit; form.submit = function() { $(form).trigger("submit"); oldSubmit.call(form, arguments); } ``` * Why not bind to all the <a> tags? Then you don't have to do any monkey patching,...
If you are using jQuery, you should be attaching events via it's own [event mechanism](http://docs.jquery.com/Events) and not by using "on" properties (onclick etc.). It also has its own event triggering method, aptly named '[trigger](http://docs.jquery.com/Events/trigger#typedata)', which you should use to activate th...
jQuery override form submit not working when submit called by javascript on a element
[ "", "javascript", "jquery", "" ]
I'm trying to direct a browser to a different page. If I wanted a GET request, I might say ``` document.location.href = 'http://example.com/q=a'; ``` But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML ``` <form action...
## Dynamically create `<input>`s in a form and submit it ``` /** * sends a request to the specified url from a form. this will change the window location. * @param {string} path the path to send the post request to * @param {object} params the parameters to add to the url * @param {string} [method=post] the method...
This would be a version of the selected answer using [jQuery](http://en.wikipedia.org/wiki/JQuery). ``` // Post to the provided URL with the specified parameters. function post(path, parameters) { var form = $('<form></form>'); form.attr("method", "post"); form.attr("action", path); $.each(parameters...
JavaScript post request like a form submit
[ "", "javascript", "forms", "post", "submit", "" ]