Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am currently developing an approval routing WCF service that will allow an user to create "rules" which determine how an request is routed. The route is determined by comparing the "ObjectToEvaluate" property of the Request class against the "ObjectToEvaluate" property of the "Rule" class. The "UnitOfMeasurement" enu...
Use an implicit type operator that checks the value of the enum. That way callers can transparently assign the objects to the types you want to represent them. Eg: ``` public class CastableObject { private UnitOfMeasurement eUnit; // Assign this somehow public static implicit operator int(CastableObject obj)...
Where are you getting the unit of measurement from? I can see the enum, but I don't see any reference to it elsewhere in the API. Assuming you do get it from somewhere, the easiest solution may well be a switch statement. It's a bit ugly, but: * It'll work * It's easy to understand * It'll be fast I'm still not enti...
Best way to determine how to cast an object to an appropriate type in C#?
[ "", "c#", "casting", "" ]
Is there any way to take a Class and determine if it represents a primitive type (is there a solution that doesn't require specifically enumerating all the primitive types)? NOTE: I've seen [this question](https://stackoverflow.com/questions/180097/dynamically-find-the-class-that-represents-a-primitive-java-type). I'm...
There is a method on the Class object called [isPrimitive](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isPrimitive()).
[Class.isPrimitive()](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#isPrimitive()) will tell you the answer.
How can I generically tell if a Java Class is a primitive type?
[ "", "java", "" ]
I have a generic class in C# with 2 constructors: ``` public Houses(params T[] InitialiseElements) {} public Houses(int Num, T DefaultValue) {} ``` Constructing an object using int as the generic type and passing in two ints as arguments causes the 'incorrect' constructor to be called (from my point of view). E.g. `...
A clearer solution would be to have two static factory methods. If you put these into a nongeneric class, you can also benefit from type inference: ``` public static class Houses { public static Houses<T> CreateFromElements<T>(params T[] initialElements) { return new Houses<T>(initialElements); } ...
Perhaps instead of Params you could pass in IEnumerable ``` public Houses(IEnumerable<T> InitialiseElements){} ```
Using C# params keyword in a constructor of generic types
[ "", "c#", ".net", "c#-3.0", "" ]
When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?
Two possibilities I can think of. 1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation). ``` public class MyApp { public static String[] ARGS; public static void main(String[] args) { ARGS = args; // crea...
Have a look at my Spring-CLI library - at <http://github.com/sazzer/spring-cli> - as one way of doing this. It gives you a main class that automatically loads spring contexts and has the ability to use Commons-CLI for parsing command line arguments automatically and injecting them into your beans.
Dealing with command line arguments and Spring
[ "", "java", "spring", "command-line", "" ]
Consider this case: ``` dll = LoadDLL() dll->do() ... void do() { char *a = malloc(1024); } ... UnloadDLL(dll); ``` At this point, will the 1k allocated in the call to malloc() be available to the host process again? The DLL is statically linking to the CRT.
No, you do not leak. If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe) This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT. If you'd linked wit...
1. Memory used by a process as tracked by the OS is applicable to the full process and not specific to a DLL. 2. Memory is given to the program in chunks by the OS, called heaps 3. The heap managers (malloc / new etc) further divide up the chunks and hands it out to requesting code. 4. Only when a new heap is allocated...
Does a memory leak at unload of a DLL cause a leak in the host process?
[ "", "c++", "winapi", "dll", "memory-management", "crt", "" ]
The simple demo below captures what I am trying to do. In the real program, I have to use the object initialiser block since it is reading a list in a LINQ to SQL select expression, and there is a value that that I want to read off the database and store on the object, but the object doesn't have a simple property that...
Even better: ``` public static T SetBarValue<T>(this T dataObject, int barValue) where T : BaseDataObject { dataObject.SetData("bar", barValue); return dataObject; } ``` and you can use this extension method for derived types of BaseDataObject to chain methods without casts and preser...
Object Initializers are just syntactic sugar that requires a clever compiler, and as of the current implementation you can't call methods in the initializer. ``` var x = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }; ``` Will get compiler to something like this: ``` BaseDataObject tempObject = new BaseDat...
Is there any way to use an extension method in an object initializer block in C#
[ "", "c#", "linq", "extension-methods", "initializer", "" ]
I'm trying to build a proxy module for .NET, but I'm having trouble copying the Headers from the current request to the new request. I am setting the headers of the new request, because I want the proxy to support SOAP requests. Here is a portion of my code. I can post everything if need, but this is the only part that...
Some of the headers are actually exposed as properties directly on the HttpWebRequest object. These headers you are not allowed to set directly. e.g HttpWebRequest,ContentType and HttpWebRequest.UserAgent You will need to update these properties directly and avoid setting them via the Headers property.
So I am understanding your response as "It's not possible to set the collection explicitly." I was hoping there was a way to add names and values to the NameValueDictionary, but I guess I'll need to just determine which fields I need to set and use the properties to access specific name/value objects. I guess I could u...
Need Help With HttpWebRequest object
[ "", "c#", "asp.net", "" ]
When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static? Example: ``` foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample")) { ...
From the [FxCop rule page](http://msdn.microsoft.com/en-us/library/ms245046.aspx) on this: > After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer i...
When I'm writing a class, most methods fall into two categories: * Methods that use/change the current instance's state. * Helper methods that don't use/change the current object's state, but help me compute values I need elsewhere. Static methods are useful, because just by looking at its signature, you know that th...
Advantages to Using Private Static Methods
[ "", "c#", "performance", "" ]
I have these two pieces of code, wich one is more readable? 1. foreach ``` decimal technicalPremium = 0; foreach (Risk risk in risks) { technicalPremium = technicalPremium + risk.TechnicalPremium; } return technicalPremium; ``` 2. linq ``` return risks.Sum(risk => risk.TechnicalPre...
If the team that works on the code knows what the Linq version does and knows its inner workings, then it is more readable.
Use whichever you prefer but hide it in a method: ``` return risks.SumTechnicalPremium(); ```
What is more readable?
[ "", "c#", "linq", "lambda", "readability", "" ]
I have stfw but I cannot find a simple / standalone way to create a webservice client in java. Does anyone have a link/sample into this?
How about using [Axis2](http://ws.apache.org/axis2/)? Just follow the [quickstart guide](http://ws.apache.org/axis2/1_4_1/quickstartguide.html) and you should be on your way. Here is another more descriptive [guide](http://ws.apache.org/axis2/1_0/userguide3.html#Writing_Web_Service_Clients_using_Code_Generation_with_...
[soapUI](http://www.soapui.org/) is a great tool to test a Web Service. It is really simple to either create a server stub to test your client or just send client request to any Web Service.
java webservice client
[ "", "java", "webservice-client", "" ]
I'm working on what I think is a pretty standard django site, but am having trouble getting my admin section to display the proper fields. Here's my models.py: ``` class Tech(models.Model): name = models.CharField(max_length = 30) class Project(models.Model): title = models.CharField(max_length = 50) tec...
> I've tried adding the TechInline class to the inlines list, but that causes a > > 'TechInLine' not defined Is that a straight copy-paste? It looks like you just made a typo -- try `TechInline` instead of `TechInLine`. If your syncdb didn't create the proper table, you can do it manually. Execute this command: ``` ...
@John Millikin - Thanks for the sqlreset tip, that put me on the right path. The sqlreset generated code that showed me that the `projects_project_techs` was never actually created. I ended up just deleting my deb.db database and regenerating it. `techs` then showed up as it should. And just as a sidenote, I had to do...
Django admin site not displaying ManyToManyField relationship
[ "", "python", "django", "" ]
If I have a string (010) and i want to add 1 to it (011) what value type should i use to convert this string into a number for adding and at the same time preserve the whole number and not 10 + 1 = 11.
You could use something like this: ``` string initialValue = "010"; int tempValue = Int.Parse(initialValue) + 1; string newValue = tempValue.ToString("000"); ``` You do your math as normal and then just return your string to its previous format using the number formatting feature of the `.ToString()`
``` if (int.TryParse(str, out i)) str = (i + 1).ToString("000"); ``` HTH. (**edit**: fixed the problems pointed out by BoltBait and steffenj)
What value to use? C# (Adding numbers represented as strings)
[ "", "c#", "algorithm", "" ]
I develop a number of desktop Java applications using Swing, and while Swing is quite powerful (once you get the hang of it), there are still a lot of cases where I wish some advanced component was available right out of the box. For example, I'd really like to see easy-to-use components (without writing them myself, ...
The following are worth a look: * [swingX](https://swingx.dev.java.net/) * [Glazed lists](http://publicobject.com/glazedlists/) * [Substance look'n'feel](https://substance.dev.java.net/) * [Flamingo components](https://flamingo.dev.java.net/) * [Ken Orr's Mac Widgets](http://code.google.com/p/macwidgets/) * [Jide's op...
As for: "Windows File Explorer-like Icons or Thumbnails view" They are built in in swing. File explorer icons are accessed through FileSystemView class ( it is used by JFileChooser ) when the L&F is Windows of course. ``` FileSystemView.getFileSystemView(); Icon driveIcon = fsv.getSystemIcon( new File("C:\\")); ``` ...
Open-source improvements or replacements for Swing components
[ "", "java", "swing", "components", "" ]
Is it currently possible to translate C# code into an Abstract Syntax Tree? Edit: some clarification; I don't necessarily expect the compiler to generate the AST for me - a parser would be fine, although I'd like to use something "official." Lambda expressions are unfortunately not going to be sufficient given they do...
The [Roslyn](http://msdn.microsoft.com/en-us/roslyn) project is in Visual Studio 2010 and gives you programmatic access to the [Syntax Tree](https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/work-with-syntax#syntax-trees), among other things. ``` SyntaxTree tree = SyntaxTree.ParseCompilationUnit( @" C# co...
> Is it currently possible to translate C# code into an Abstract Syntax Tree? Yes, trivially in special circumstances (= using the new [Expressions framework](http://msdn.microsoft.com/en-us/library/bb397951.aspx)): ``` // Requires 'using System.Linq.Expressions;' Expression<Func<int, int>> f = x => x * 2; ``` This ...
Translate C# code into AST?
[ "", "c#", "compiler-construction", "abstract-syntax-tree", "" ]
I'm having trouble dynamically adding controls inside an update panel with partial postbacks. I've read many articles on dynamic controls and I understand how to add and maintain them with postbacks but most of that information doesn't apply and won't work for partial postbacks. I can't find any useful information abou...
This is, I think, one of the common pitfalls for asp.net programmers but isn't actually that hard to get it right when you know what is going on (always remember your viewstate!). the following piece of code explains how things can be done. It's a simple page where a user can click on a menu which will trigger an acti...
I encountered the problem that using the method mentioned above, LoadUserControl() is called twice when handling an event. I've read through some other articles and would like to show you my modification: 1) Use LoadViewstate instead of Page\_Load to load the user control: ``` protected override void LoadViewState(ob...
Programmatically Adding User Controls Inside An UpdatePanel
[ "", "c#", "asp.net", "asp.net-ajax", "" ]
Some text before the code so that the question summary isn't mangled. ``` class Tree { public event EventHandler MadeSound; public void Fall() { MadeSound(this, new EventArgs()); } static void Main(string[] args) { Tree oaky = new Tree(); oaky.Fall(); } } ``` I haven't used event...
You need to understand what your event declaration is actually doing. It's declaring both an event and a variable, When you refer to it within the class, you're just referring to the variable, which will be null when there are no subscribers.
Well, the canonical form is: ``` void OnMadeSound() { if (MadeSound != null) { MadeSound(this, new EventArgs()); } } public void Fall() { OnMadeSound(); } ``` which is *very slightly* faster that calling an empty delegate, so speed won out over programming convenience.
Why must someone be subscribed for an event to occur?
[ "", "c#", "events", "" ]
My main JavaScript framework is [jQuery](http://jquery.com/), so I would like my unit test and mocking frameworks to be compatible with that. I'd rather not have to introduce another JavaScript framework. I am currently using [QUnit](http://docs.jquery.com/QUnit) for unit testing and [Jack](https://github.com/keronsen...
[QUnit](http://docs.jquery.com/QUnit) [jqUnit](http://code.google.com/p/jqunit/) [Writing JavaScript tests with QUnit and jqUnit](http://wiki.fluidproject.org/display/fluid/Writing+JavaScript+Unit+Tests) QUnit is the unit testing framework for the jQuery JavaScript framework. The testing framework itself uses th...
I think that Jack is the best mocking framework for JavaScript as of the time of this writing. The main reason is that what's right for JavaScript is not likely what is right for a strongly typed language such as Java. Many JavaScript mocking frameworks are inspired by Java mock frameworks (such as the excellent JsMoc...
What are some JavaScript unit testing and mocking frameworks you have used?
[ "", "javascript", "jquery", "unit-testing", "mocking", "qunit", "" ]
I'm working on a Java library and would like to remove some functions from it. My reasons for this is public API and design cleanup. Some objects have setters, but should be immutable, some functionality has been implemented better/cleaner in different methods, etc. I have marked these methods 'deprecated', and would ...
Set a date and publicize it in the @deprecated tag. The amount of time given to the removal depends on the amount of users your code has, how well connected you are with them and the the reason for the change. If you have thousands of users and you barely talk to them, the time frame should probably be in the decades ...
Consider it this way, customer A downloads the latest version of you library file or frame work. He hits compile on this machine and suddenly he see thousands of errors because the member file or function does no longer exist. From this point on, you've given the customer a reason why not to upgrade to your new version...
How to handle functions deprecation in library?
[ "", "java", "" ]
Boost range library (<http://www.boost.org/doc/libs/1_35_0/libs/range/index.html>) allows us to abstract a pair of iterators into a range. Now I want to combine two ranges into one, viz: given two ranges r1 and r2, define r which traverses [r1.begin(), r1.end()[ and then [r2.begin(), r2.end()[. Is there some way to de...
I needed this again so I had a second look. There is a way to concat two ranges using boost/range/join.hpp. Unluckily the output range type is not included in the interface: ``` #include "boost/range/join.hpp" #include "boost/foreach.hpp" #include <iostream> int main() { int a[] = {1, 2, 3, 4}; int b[...
* Can't you call the function twice, once for both ranges? Or are there problems with this approach? * Copy the two ranges into one container and pass that. * Write your own range class, so it iterates through r1 first and and through r2 second.
Boost Range Library: Traversing Two Ranges Sequentially
[ "", "c++", "" ]
I need to find occurrences of ~ 25 000 words within a text. What is the most suitable algorithm/library for this purpose? target language is C++
build a hashtable with the words, and scan throuhgt the text, for each word lookup in the wordtable and stuff the needed info (increment count, add to a position list, whatever).
> I once used the Boyer-Moore algorithm and it was quite fast. Boyer-Moore isn't apt for efficiently searching many words. There is actually a very efficient algorithm for doing just that, called the Wu-Manber algorithm. I'll post a reference implementation. Notice, however, that I did this some time ago for education...
search 25 000 words within a text
[ "", "c++", "full-text-search", "" ]
Is there a standard idiom for comparing version numbers? I can't just use a straight String compareTo because I don't know yet what the maximum number of point releases there will be. I need to compare the versions and have the following hold true: ``` 1.0 < 1.1 1.0.1 < 1.1 1.9 < 1.10 ```
Tokenize the strings with the dot as delimiter and then compare the integer translation side by side, beginning from the left.
Another solution for this old post (for those that it might help) : ``` public class Version implements Comparable<Version> { private String version; public final String get() { return this.version; } public Version(String version) { if(version == null) throw new IllegalA...
How do you compare two version Strings in Java?
[ "", "java", "comparison", "versioning", "" ]
Is there an efficient way of detecting if a jpeg file is corrupted? Background info:   solutions needs to work from within a php script   the jpeg files are on disk   manual checking is no option (user uploaded data) I know that `imagecreatefromjpeg(string $filename);` can do it. But it is quite slow at doing s...
From the command line you can use jpeginfo to find out if a jpeg file is OK or not. > $ jpeginfo -c test.jpeg > > test.jpeg 260 x 264 24bit JFIF N 15332 [OK] It should be trivial to call jpeginfo from php.
My simplest (and fastest) solution: ``` function jpeg_file_is_complete($path) { if (!is_resource($file = fopen($path, 'rb'))) { return FALSE; } // check for the existence of the EOI segment header at the end of the file if (0 !== fseek($file, -2, SEEK_END) || "\xFF\xD9" !== fread($file, 2)) { ...
Efficiently detect corrupted jpeg file?
[ "", "php", "jpeg", "corruption", "" ]
How have you used the Exception.Data property in C# projects that you've worked on? I'd like answers that suggest a pattern, rather than those that are very specific to your app.
The exception logger I use has been tweaked to write out all the items in the Data collection. Then for every exception we encounter that we cannot diagnose from the exception stack, we add in all the data in that function's scope, send out a new build, and wait for it to reoccur. I guess we're optimists in that we do...
Since none of the answers include any code. Something that might useful as an addition to this question is how to actually look at the `.Data` dictionary. Since it is not a generic dictionary and only returns `IDictionary` `foreach(var kvp in exception.Data)` the type of kvp will actually be `object` unhelpfully. Howe...
Using Exception.Data
[ "", "c#", "exception", "" ]
<http://developer.yahoo.com/javascript/howto-proxy.html> Are there disadvantages to this technique? The advantage is obvious, that you can use a proxy to get XML or JavaScript on another domain with XMLHttpRequest without running into same-origin restrictions. However, I do not hear about disadvantages over other meth...
Overhead - things are going to be a bit slower because you're going through an intermediary. There are security issues if you allow access to any external site via the proxy - be sure to lock it down to the specific site (and probably specific URL) of the resource you're proxying.
Overhead -- both for the user (who know hsa to wait for you server to make and receive data from the proxied source) and you (as you're now taking on all the traffic for the other server in addition to your own). Also security concerns -- if you are using a proxy to bypass browser security checks for displaying untrus...
What are the disadvantages to using a PHP proxy to bypass the same-origin policy for XMLHttpRequest?
[ "", "javascript", "security", "xmlhttprequest", "" ]
I have the following code fragment that starts a [Google Earth](http://en.wikipedia.org/wiki/Google_Earth) process using a hardcoded path: ``` var process = new Process { StartInfo = { //TODO: Get location of google earth executable from registry ...
Obviously if you're opening a specific file associated with the program then launching it via the file is preferable (for instance, the user might have a program associated with the file type they prefer to use). Here is a method I've used in the past to launch an application associated with a particular file type, bu...
From the example given you can gauge that I'm actually trying to pass a KML file to Google Earth. Because of this, the simplest way of resolving this problem is relying on the file association of KML with Google Earth and using the following as a replacement for the entire example: ``` Process.Start(kmlPath); ``` Thi...
How to find the installation directory of a third-party application, such as Google Earth, using C#?
[ "", "c#", "google-earth", "" ]
I have implemented a python webserver. Each http request spawns a new thread. I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following <http://freshmeat.net/projects/...
Well a lot of operations in Python are thread-safe by default, so a standard dictionary should be ok (at least in certain respects). This is mostly due to the GIL, which will help avoid some of the more serious threading issues. There's a list here: <http://coreygoldberg.blogspot.com/2008/09/python-thread-synchronizat...
Thread per request is often a bad idea. If your server experiences huge spikes in load it will take the box to its knees. Consider using a thread pool that can grow to a limited size during peak usage and shrink to a smaller size when load is light.
python threadsafe object cache
[ "", "python", "multithreading", "caching", "" ]
I want to record user states and then be able to report historically based on the record of changes we've kept. I'm trying to do this in SQL (using PostgreSQL) and I have a proposed structure for recording user changes like the following. ``` CREATE TABLE users ( userid SERIAL NOT NULL PRIMARY KEY, name VARCHAR(4...
This can be done, but would be a lot more efficient if you stored the end date of each log. With your model you have to do something like: ``` select l1.userid from status_log l1 where l1.status='s' and l1.logcreated = (select max(l2.logcreated) from status_log l2 where l2.use...
Does Postgres support analytic queries? This would give the active users on 2008-02-15 ``` select userid from ( select logid, userid, status, logcreated, max(logcreated) over (partition by userid) max_logcreated_by_user from status_log where logcreated <= date '2008-02-15' ) where lo...
SQL - state machine - reporting on historical data based on changeset
[ "", "sql", "postgresql", "" ]
HTML (or maybe just XHTML?) is relatively strict when it comes to non-standard attributes on tags. If they aren't part of the spec, then your code is considered non-compliant. Non-standard attributes can be fairly useful for passing along meta-data to Javascript however. For instance, if a link is suppose to show a po...
I am a big fan of the proposed HTML 5 solution (`data-` prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on somethin...
Custom attributes provide a convenient way to carry extra data to the client side. Dojo Toolkit is doing this regularly and it has been pointed ([Debunking Dojo Toolkit Myths](http://www.sitepen.com/blog/2008/10/27/debunking-dojo-toolkit-myths/)) out that: > Custom attributes have always been > valid HTML, they just d...
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
[ "", "javascript", "html", "standards", "" ]
I have a client who is still using Visual Studio 6 for building production systems. They write multi-threaded systems that use STL and run on mutli-processor machines. Occasionally when they change the spec of or increase the load on one of their server machines they get 'weird' difficult to reproduce errors... I kno...
Not supported on 64-bit systems, compatibility issues with Vista, and it was moved out of extended support by Microsoft on April 8, 2008 <http://msdn.microsoft.com/en-us/vbrun/ms788708.aspx>
Unpatched VC6 STL is not thread safe. See here [<http://www.amanjit-gill.de/articles/vc6_stl.html>](http://www.amanjit-gill.de/articles/vc6_stl.html), the patches aren't included in the service packs and you have to get them from Dinkumware directly (from here [<http://www.dinkumware.com/vc_fixes.html>](http://web.arch...
What are some convincing arguments to upgrade from Visual Studio 6?
[ "", "c++", "visual-studio", "visual-c++", "stl", "visual-c++-6", "" ]
Is there a maximum length when using window.returnValue (variant) in a modal? I am calling a modal window using showModalDialog() and returning a comma delimited string. After selecting a group of users, I am putting them into a stringbuilder to display in a literal. ``` Dim strReturn As New StringBuilder strReturn.A...
First, in what browser are you having problems? `window.returnValue` isn't even supported in Firefox, maybe not even other browsers. Second, have you looked the value of `strUsers` after building it to make sure there are no single or double quotes in that string? I would guess that the maximum size/length of that pr...
JasonBunting has a good suggestion. You can have the modal dialog update the parent before you close it. This way you can pass objects back and forth between your windows without worrying about the limitation of the return value. For example, you could have a hidden field on the parent that you update with your return ...
What is the maximum length allowed for window.returnValue property? (JavaScript)
[ "", "asp.net", "javascript", "vb.net", "" ]
Before you answer, this question is complicated: 1. We are developing in asp.net / asp.net mvc / jQuery but I'm open to solutions on any platform using any framework 2. I think logic like sorting / hiding columns / re-arranging columns / validation (where it makes sense) should be on the client-side 3. I think logic l...
On two; you should always have server side validation as well as client side validation On three; if you can find a way to manipulate the DB on the client side that would be impressive ;) I don't know how ASP.net works though, so I am solely speaking from my PHP experience. I would write controls that are paired by ...
I just googled this so take it with a grain of salt. [JavascriptMVC](http://javascriptmvc.com/) claims to be a MVC framework. Again, I have no experience with it but it may be worth a look.
Separating client side logic from server side logic in a reusable way using MVC
[ "", "javascript", "asp.net-mvc", "model-view-controller", "" ]
I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data. Here is the code : ``` if (region != null) { .... } ``` This is working but when looping and looping sometime the region object is NOT null (I can see data inside it in debug mode). In step-by-step when ...
Is the == and/or != operator overloaded for the region object's class? Now that you've posted the code for the overloads: The overloads should probably look like the following (code taken from postings made by [Jon Skeet](https://stackoverflow.com/questions/155458/c-object-is-not-null-but-myobject-null-still-return-f...
Those operator overloads are broken. Firstly, it makes life a lot easier if != is implemented by just calling == and inverting the result. Secondly, before the nullity checks in == there should be: ``` if (object.ReferenceEquals(r1, r2)) { return true; } ```
C# object is not null but (myObject != null) still return false
[ "", "c#", "null", "compare", "" ]
I'm working on trying to generate a report from a couple of database tables. The simplified version looks like this ``` Campaign ---------- CampaignID Source ----------------------- Source_ID | Campaign_ID Content --------------------------------------------------------- Content_ID | Campaign_ID | Content_Row_ID | C...
This is my first stab at it. Refinement coming once I know more about the contents of the Content table. First, you need a temporary table: ``` CREATE TABLE pivot (count integer); INSERT INTO pivot VALUES (1); INSERT INTO pivot VALUES (2); ``` Now we're ready to query. ``` SELECT campaignid, sourceid, a.contentvalu...
Bill Karwin mentions this, but I think this deserves to be pointed out very clearly: **SQL doesn't do what you're asking for, so any "solution" you get is going to be a kludge.** If you *know*, for sure, it's always going to run on an Oracle 10, then sure, Walter Mitty's crosstabulation might do it. The right way to ...
"Pivoting" a Table in SQL (i.e. Cross tabulation / crosstabulation)
[ "", "sql", "database", "oracle", "pivot", "" ]
How can I bring a console application window to front in C# (especially when running the Visual Studio debugger)?
It's hacky, it's horrible, but it works for me (thanks, [pinvoke.net](http://pinvoke.net/)!): ``` using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; public class Test { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool...
This is what I would do. ``` [DllImport("kernel32.dll", ExactSpelling = true)] public static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); public void BringConsoleToFront() { SetForegroundWindow(GetC...
bring a console window to front in c#
[ "", "c#", "console", "window", "" ]
I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod\_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large a...
[CherryPy](http://cherrypy.org/). Features, as listed from the website: * A fast, HTTP/1.1-compliant, WSGI thread-pooled webserver. Typically, CherryPy itself takes only 1-2ms per page! * Support for any other WSGI-enabled webserver or adapter, including Apache, IIS, lighttpd, mod\_python, FastCGI, SCGI, and mod\_wsgi...
Consider reconsidering your design. Maintaining that much state in your webserver is probably a bad idea. Multi-process is a much better way to go for stability. Is there another way to share state between separate processes? What about a service? Database? Index? It seems unlikely that maintaining a huge array of da...
A good multithreaded python webserver?
[ "", "python", "apache", "webserver", "mod-python", "" ]
I have a CSV file that holds about 200,000 - 300,000 records. Most of the records can be separated and inserted into a MySQL database with a simple ``` $line = explode("\n", $fileData); ``` and then the values separated with ``` $lineValues = explode(',', $line); ``` and then inserted into the database using the pr...
If the csv data is in a file, you can just use fgetcsv() as others have pointed out. fgetcsv handles embedded newlines correctly. However if your csv data is in a string (like $fileData in your example) the following method may be useful as str\_getcsv() only works on a row at a time and cannot split a whole file into...
The other advice here is, of course, valid, especially if you aim to write your own CSV parser, however, if you just want to get the data out, use [fgetcsv()](http://php.net/fgetcsv) function and don't worry about implementation details.
Replacing or Removing a new line with something else but only between single or double quotes using PHP on a CSV file
[ "", "php", "csv", "" ]
I'm trying to save some XML-Data in my UserSettings (Properties.Settings.Default.UserSettings) in a .NET Winforms Project. Is there a Possibility to do that or would it be better to save this Data in a seperated File? Thanks for your Answers!
You can store an XML document's string representation in a setting of type String. To save the document, load it into an XmlDocument and set the setting to the value of the XmlDocument.OuterXml property. To retrieve it, create a new XmlDocument and use its LoadXml method to parse the string into an XML document. This ...
In a previous project I had a similar idea but decided to keep the xml files separate. The xml files can be embedded resources, and their file names can be referenced in the Settings file. I think this is a cleaner solution.
Saving XML-Data in UserSettings
[ "", "c#", ".net", "xml", "app-config", "" ]
I'm trying to call the SQL statement below but get the following error: > System.Data.SqlClient.SqlException: Conversion failed when converting > the varchar value '+@buildingIDs+' to data type int. ``` @"SELECT id, startDateTime, endDateTime FROM tb_bookings WHERE buildingID IN ('+@buildingIDs+') AND ...
Bravax's way is a bit dangerous. I'd go with the following so you don't get attacked with SQL Injections: ``` int[] buildingIDs = new int[] { 1, 2, 3 }; /***/ @"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (" + string.Join(", ", buildingIDs.Select(id => id.ToString()).ToArray()) ...
Note that LINQ can do this via Contains (which maps to IN). With regular TSQL, another option is to pass down the list as a CSV (etc) varchar, and use a table-valued UDF to split the varchar into pieces. This allows you to use a single TSQL query (doing an INNER JOIN to the UDF result).
sqlParameter conversion
[ "", ".net", "sql", "sql-server", "" ]
What are the basic differences between a semaphore & spin-lock? When would we use a semaphore over a spin-lock?
Spinlock and semaphore differ mainly in four things: **1. What they are** A *spinlock* is one possible implementation of a lock, namely one that is implemented by busy waiting ("spinning"). A semaphore is a generalization of a lock (or, the other way around, a lock is a special case of a semaphore). Usually, *but no...
very simply, a semaphore is a "yielding" synchronisation object, a spinlock is a 'busywait' one. (there's a little more to semaphores in that they synchronise several threads, unlike a mutex or guard or monitor or critical section that protects a code region from a single thread) You'd use a semaphore in more circumst...
Spinlock versus Semaphore
[ "", "c++", "c", "linux", "unix", "operating-system", "" ]
We are currently researching ways of enhancing image quality prior to submission to OCR. The OCR engine we are currently utilizing is the Scansoft API from Nuance (v15). We were researching the [Lead Tools](http://leadtools.com/) but have since decided to look elsewhere. The licensing costs associated with Lead Tools i...
Kofax is good for pre-processing, but for the types of cleanup you are talking about may be overkill unless the images are really bad. Unless your specialty is in image processing, I'd recommend working with a provider that does the image cleanup and the OCR so you can focus on the value you actually add. We license t...
*Disclaimer: I work for Atalasoft* We have those functions and run-time royalty-free licensing for .NET. <http://www.atalasoft.com/products/dotimage/> We also have OCR components including a .NET wrapper for Abbyy, Tesseract and others and Searchable PDF generation (image on top of text in a PDF)
What software would you recommend for image enhancement prior to OCR (Optical Character Recognition)?
[ "", "java", ".net", "image-processing", "ocr", "image-enhancement", "" ]
I get the following warning when using `java.net.URLEncoder.encode`: ``` warning: [deprecation] encode(java.lang.String) in java.net.URLEncoder has been deprecated ``` What should I be using instead?
Use the other `encode` method in [URLEncoder](http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String-): ``` URLEncoder.encode(String, String) ``` The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., `UTF-8`). For ...
You should use: ``` URLEncoder.encode("NAME", "UTF-8"); ```
java.net.URLEncoder.encode(String) is deprecated, what should I use instead?
[ "", "java", "url", "network-programming", "deprecated", "" ]
Is it possible to pass a App setting "string" in the web.config to a Common C# class?
Of course it's possible - but the thing to keep in mind is that a properly designed class (unless it's explicitly designed for ASP.NET) shouldn't know or care where the information comes from. There should be a property (or method, but properties are the more '.NET way' of doing things) that you set with the string val...
In any class you can use `ConfigurationManager.AppSettings["KeyToSetting"]` to access any value in the element of web.config (or app.config)
Is it possible to pass a App setting in the web.config to a Common C# class
[ "", "c#", "asp.net", "web-config", "" ]
I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl. I've seen mentioned a few places that python is good for this kind of thing. How can I use Python to replace shell scripting, AWK, sed and friends?
Any shell has several sets of features. * The Essential Linux/Unix commands. All of these are available through the [subprocess](https://docs.python.org/3/library/subprocess.html) library. This isn't always the best first choice for doing *all* external commands. Look also at [shutil](https://docs.python.org/3/library...
Yes, of course :) Take a look at these libraries which help you ***Never write shell scripts again*** (Plumbum's motto). * [Plumbum](http://plumbum.readthedocs.org/en/latest/) * [Sarge](https://bitbucket.org/vinay.sajip/sarge/) * [sh](http://amoffat.github.com/sh/) Also, if you want to replace awk, sed and grep with...
How to implement common bash idioms in Python?
[ "", "python", "bash", "shell", "" ]
Whenever I use the signal/slot editor dialog box, I have to choose from the existing list of slots. So the question is how do I create a custom named slot?
Unfortunately this is not possible in Qt4. In Qt3 you could create custom slots which where then implemented in the ui.h file. However, Qt4 does not use this file so custom slots are not supported. There is some discussion of this issue over on [QtForum](http://www.qtforum.org/article/11096/qt4-custom-slots.html)
This does seem to be possible in the version of Qt Designer 4.5.2, but it *can't* be done from the Signal/Slot Editor dock-widget in the main window. This is what worked for me 1. Switch to [Edit Signals/Slots](http://doc.qt.io/qt-4.8/designer-connection-mode.html) mode (F4) 2. Drag and drop from the widget which is ...
How do I create a custom slot in qt4 designer?
[ "", "c++", "qt", "qt4", "qt-creator", "qt-designer", "" ]
I have a Python application in a strange state. I don't want to do live debugging of the process. Can I dump it to a file and examine its state later? I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb. (This is a variation on my que...
There is no builtin way other than aborting (with os.abort(), causing the coredump if resource limits allow it) -- although you can certainly build your own 'dump' function that dumps relevant information about the data you care about. There are no ready-made tools for it. As for handling the corefile of a Python proc...
If you only care about storing the traceback object (which is all you need to start a debugging session), you can use [debuglater](https://github.com/ploomber/debuglater) (a fork of [pydump](https://github.com/elifiner/pydump)). It works with recent versions of Python and has a IPython/Jupyter integration. If you want...
How do I dump an entire Python process for later debugging inspection?
[ "", "python", "debugging", "coredump", "" ]
There are some updates with .NET 3.0 concerning how to create and use add-ins for your own applications. I read about some "*pipeline*" you have to create for the communication between add-in and host-application but couldn't find further information about it. How would you made an add-in functionality in an applicati...
Definitely check out the Managed Extensibility Framework at [www.codeplex.com/mef](http://www.codeplex.com/mef). It's a framework that helps with creating extensible applications. It takes care of all the plumbing when creating a pluggable app. I'm currently writing a series of articles that show the basic functionalit...
In addition to [Daniels](https://stackoverflow.com/questions/179680/how-can-you-make-use-of-the-add-in-framework-in-net-30#179727) codeplex link, Jason He also has a nice wee series on using the System.AddIn namespace when developing Paint.NET starting here - <http://blogs.msdn.com/zifengh/archive/2007/01/04/addin-mod...
How can you make use of the add-in framework in .NET 3.0?
[ "", "c#", "add-in", ".net-3.0", "" ]
Would a C++ [CLI](http://en.wikipedia.org/wiki/Common_Language_Infrastructure) compiler be able to compile some large sets of C++ classes without modifications? Is C++ CLI a superset of C++?
technically no, but depending how standard the C++ code is, you'll probably be just fine. when you get into windows stuff you may run into issues. I compiled the whole game engine we use at work in C++/CLI once and it worked just fine. A colleague did the same for all of mozilla and no such luck.
According to [Wikipedia](http://en.wikipedia.org/wiki/C%2B%2B/CLI "Wikipedia"): > C++/CLI should be thought of as a language of its own (with a new set of keywords, for example), instead of the C++ superset-oriented Managed C++
Is C++ CLI a superset of C++?
[ "", "c++", "c++-cli", "clr", "" ]
I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now: 1. It is now October 2008. I want to start writing an application for January 2009. I am w...
it depends. php - symfony is a great framework. downsides: php, wordy and directory heavy. propel gets annoying to use. upsides: php is everywhere and labor is cheap. well done framework, and good support. lots of plugins to make your life easier python - django is also a great framework. downsides: python programmer...
**Django!** Look up the DjangoCon talks on Google/Youtube - Especially "Reusable Apps" (www.youtube.com/watch?v=A-S0tqpPga4) I've been using Django for some time, after starting with Ruby/Rails. I found the Django Community easier to get into (nicer), the language documented with *excellent* examples, and it's modula...
Framework/Language for new web 2.0 sites (2008 and 2009)
[ "", "python", "ruby-on-rails", "django", "merb", "" ]
**Note:** This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4). We're building a web API that's programmatically generated from a C# class. The class has method `GetFooBar(int a, int b)` and the API has a method `GetFooBar` taking query params like `&a=foo &b=bar`. The ...
With C# 4.0 you can use optional parameters that work like this: ``` public void SomeMethod(int a, int b = 0) { //some code } ```
Another option is to use the params keyword ``` public void DoSomething(params object[] theObjects) { foreach(object o in theObjects) { // Something with the Objects… } } ``` Called like... ``` DoSomething(this, that, theOther); ```
How can you use optional parameters in C#?
[ "", "c#", "optional-parameters", "" ]
I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?
Import your settings module too ``` import os os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" from mysite.polls.models import Poll, Choice ``` should do the trick.
This is what I have at the top of one my data loading scripts. ``` import string import sys try: import settings # Assumed to be in the same directory. #settings.DISABLE_TRANSACTION_MANAGEMENT = True except ImportError: sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing ...
What do I need to import to gain access to my models?
[ "", "python", "django", "" ]
I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me. I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windo...
If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux) ``` >>> import ntpath >>> filepath = r"c:\ttemp\FILEPA~1.EXE" >>> print ntpath.basename(filepath) FILEPA~1.EXE >>> print ntpath.split...
From a `os.path` documentation: **os.path.splitdrive(path)** Split the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path....
Os.path : can you explain this behavior?
[ "", "python", "path", "" ]
How do I convert a hex string to an integer? ``` "0xffff" ⟶ 65535 "ffff" ⟶ 65535 ```
**Without** the `0x` prefix, you need to specify the base explicitly, otherwise there's no way to tell: ``` x = int("deadbeef", 16) ``` **With** the `0x` prefix, Python can distinguish hex and decimal automatically: ``` >>> print(int("0xdeadbeef", 0)) 3735928559 >>> print(int("10", 0)) 10 ``` (You *must* specify `0...
`int(hexstring, 16)` does the trick, and works with and without the 0x prefix: ``` >>> int("a", 16) 10 >>> int("0xa", 16) 10 ```
Convert hex string to integer in Python
[ "", "python", "string", "hex", "" ]
I inherited this gigantic legacy Java web app using Struts 1.2.4. I have a specific question regarding Actions. Most of the pages have exactly one Action, and the processExecute() methods are hideous monsters (very long and tons of nested if statements based on request parameters). Given that Actions are an implementa...
My way of dealing with this would be: * dont do 'everything at once' * whenever you change anything, leave it better than you found it + replacing conditionals with separate Action implementations is one step. + Better yet: Make your implementations separate from the Action classes so that you can use it when you ...
Struts Actions, in my mind, shouldn't have very much code in them at all. They should just interact directly with the request and response - take some data from a form or a request parameter, hand that info off to the Service Layer, and then put some stuff in a Response object or maybe save some data in the user's sess...
How to deal with monstrous Struts Actions?
[ "", "java", "struts", "design-patterns", "anti-patterns", "" ]
I have embedded a Python interpreter in a C program. Suppose the C program reads some bytes from a file into a char array and learns (somehow) that the bytes represent text with a certain encoding (e.g., ISO 8859-1, Windows-1252, or UTF-8). How do I decode the contents of this char array into a Python string? The Pyth...
PyString\_Decode does this: ``` PyObject *PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) { PyObject *v, *str; str = PyString_FromStringAndSize(s, size); if (str == NULL) return NULL; v = PyString_AsDecodedString(s...
You don't want to decode the string into a Unicode representation, you just want to treat it as an array of bytes, right? Just use `PyString_FromString`: ``` char *cstring; PyObject *pystring = PyString_FromString(cstring); ``` That's all. Now you have a Python `str()` object. See docs here: <https://docs.python.org...
How to convert a C string (char array) into a Python string when there are non-ASCII characters in the string?
[ "", "python", "c", "character-encoding", "embedding", "" ]
Is there a way to take a class name and convert it to a string in C#? As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be...
[Include requires a property name](http://msdn.microsoft.com/en-us/library/bb738708.aspx), not a class name. Hence, it's the name of the property you want, not the name of its type. [You can get that with reflection](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx).
You can't use `.GetType()` without an instance because `GetType` is a method. You can get the name from the type though like this: ``` typeof(Foo).Name ``` And as pointed out by Chris, if you need the assembly qualified name you can use ``` typeof(Foo).AssemblyQualifiedName ```
Get the name of a class as a string in C#
[ "", "c#", "entity-framework", "" ]
Sometimes I find myself in the situation where I want to execute several sequential commands like such: ``` try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... ``` This same pattern occurs when exceptions simply need to be ignored. This feels redundant and the ex...
You could use the [`with` statement](https://www.python.org/dev/peps/pep-0343/) if you have python 2.5 or above: ``` from __future__ import with_statement import contextlib @contextlib.contextmanager def handler(): try: yield except Exception, e: baz(e) ``` Your example now becomes: ``` with...
If this is always, *always* the behaviour you want when a particular function raises an exception, you could use a decorator: ``` def handle_exception(handler): def decorate(func): def call_function(*args, **kwargs): try: func(*args, **kwargs) except Exception, e: ...
Generic Exception Handling in Python the "Right Way"
[ "", "python", "exception", "readability", "" ]
Out style: ``` bool result; if(something.TryParse(val, out result)) { DoSomething(result); } ``` Nullable style: ``` bool? result = something.TryParse2(val); if(result.HasValue) { DoSomething(result.Value); } ```
TryParse(val, out result) is a idiom established by the .NET framework in int.TryParse, DateTime.TryParse, etc. It is likely that people that read the code will be familiar with this idiom, so you should stick to it, unless you find a very good reason not to.
I don't mean to be unkind. But when you propose a change to a well-established idiom, it undermines confidence if your sample code isn't right. Your first example should either be: ``` something result; if (something.TryParse(val, out result)) { DoSomething(result); } ``` or: ``` bool result; if (bool.TryParse(v...
TryParse: What is more readable?
[ "", "c#", "" ]
In ruby the library path is provided in `$:`, in perl it's in `@INC` - how do you get the list of paths that Python searches for modules when you do an import?
I think you're looking for [sys.path](https://docs.python.org/3/library/sys.html#sys.path) ``` import sys print (sys.path) ```
You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to: ``` import sys sys.path.append('/home/user/python-libs') ```
Python Library Path
[ "", "python", "" ]
Why or why not?
For performance, especially when you're iterating over a large range, `xrange()` is usually better. However, there are still a few cases why you might prefer `range()`: * In python 3, `range()` does what `xrange()` used to do and `xrange()` does not exist. If you want to write code that will run on both Python 2 and P...
No, they both have their uses: Use `xrange()` when iterating, as it saves memory. Say: ``` for x in xrange(1, one_zillion): ``` rather than: ``` for x in range(1, one_zillion): ``` On the other hand, use `range()` if you actually want a list of numbers. ``` multiples_of_seven = range(7,100,7) print "Multiples of ...
Should you always favor xrange() over range()?
[ "", "python", "range", "xrange", "" ]
I have a template in word (.docx) format and want to replace some placeholders in this template with my own data, do you know where I can find the right classes for this project? It would be nice for me to know the namespace. Are there any newer classes for handling word documents in the docx format (xml) than the com ...
The new office formats (docx, xlsx, etc) are zip files that contain a collection of xml files. With that in mind you have a couple of approaches. 1. You can use the Open XML SDK located at <http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&displaylang=en> 2. You can unzip th...
Eric White has touched on exactly this subject in a [blog article detailing a program meant to validate source snippets embedded in DocX files](http://blogs.msdn.com/ericwhite/archive/2008/09/08/openxmlcodetester-validating-code-in-open-xml-documents.aspx). Beyond just that article I highly recommend reading his series...
Replace Placeholders in word document with c#
[ "", "c#", ".net", "ms-word", "placeholder", "" ]
Why can't I pass the table name to a prepared PDO statement? ``` $stmt = $dbh->prepare('SELECT * FROM :table WHERE 1'); if ($stmt->execute(array(':table' => 'users'))) { var_dump($stmt->fetchAll()); } ``` Is there another safe way to insert a table name into a SQL query? With safe, I mean that I don't want to do ...
**Table and Column names CANNOT be replaced by parameters in PDO.** In that case you will simply want to filter and sanitize the data manually. One way to do this is to pass in shorthand parameters to the function that will execute the query dynamically and then use a `switch()` statement to create a white list of val...
To understand *why* binding a table (or column) name doesn't work, you have to understand how the placeholders in prepared statements work: they are not simply substituted in as (suitably escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to "prepare" a statement comes up with a complete query plan...
Can PHP PDO Statements accept the table or column name as parameter?
[ "", "php", "pdo", "" ]
Does anyone know the full list of C# compiler number literal modifiers? By default declaring '0' makes it an Int32 and '0.0' makes it a 'Double'. I can use the literal modifier 'f' at the end to ensure something is treated as a 'Single' instead. For example like this... ``` var x = 0; // x is Int32 var y = 0f; /...
``` var y = 0f; // y is single var z = 0d; // z is double var r = 0m; // r is decimal var i = 0U; // i is unsigned int var j = 0L; // j is long (note capital L for clarity) var k = 0UL; // k is unsigned long (note capital L for clarity) ``` From the [C# specification](https://stackoverflow.com/questions/127776/where-c...
If you don't want to have to remember them, then the compiler also accepts a cast for the same purpose (you can check the IL that the effect is the same - i.e. the compiler, not the runtime, does the cast). To borrow the earlier example: ``` var y = (float)0; // y is single var z = (double)0; // z is double ...
C# compiler number literals
[ "", "c#", "compiler-construction", "" ]
I'm not looking for java-web-start, I'm looking for a thick-client application installation toolkit. I've got a stand-alone application that consists of several files (jar files, data files, etc) and would need to do some pretty standard installation tasks, like asking the user for target directories, have them locate ...
Not an MSI-Installer but crossplatform: [izPack](http://izpack.org/) It's xml-file based with it's own GUI or ant task (whtaever you prefer)
Launch4j -- open source -- <http://launch4j.sourceforge.net/> InstallJammer -- <http://www.installjammer.com/>
Java Application Installers
[ "", "java", "installation", "toolkit", "" ]
I had a look in the reference doc, and Spring seems to have pretty good support for sending mail. However, I need to login to a mail account, read the messages, and download any attachments. Is downloading mail attachments supported by the Spring mail API? I know you can do this with the Java Mail API, but in the past...
Here's the class that I use for downloading e-mails (with attachment handling). You'll have to glance by some of the stuff it's doing (like ignore the logging classes and database writes). I've also re-named some of the packages for ease of reading. The general idea is that all attachments are saved as individual file...
I worked Steven's example a little bit and removed the parts of the code specific to Steven. My code won't read the body of an email if it has attachments. That is fine for my case but you may want to refine it further for yours. ``` package utils; import java.io.BufferedOutputStream; import java.io.File; import java...
download mail attachment with Java
[ "", "java", "spring", "email", "attachment", "" ]
I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform su...
``` #include <stdio.h> #include <stdlib.h> int main(void) { char * ptr; long parsed = strtol("11110111", & ptr, 2); printf("%lX\n", parsed); return EXIT_SUCCESS; } ``` For larger numbers, there as a `long long` version, `strtoll`.
You can use std::bitset (if then length of your bits is known at compile time) Though with some program you could break it up into chunks and combine. ``` #include <bitset> #include <iostream> int main() { std::bitset<5> x(std::string("01011")); std::cout << x << ":" << x.to_ulong() << std::endl; } ```
Converting string of 1s and 0s into binary value
[ "", "c++", "c", "binary", "" ]
For example if I'm working on Visual Studio 2008, I want the values devenv and 2008 or 9. The version number is very important...
This is going to be PInvoke city... You'll need to PInvoke the following API's in User32.dll Win32::GetForegroundWindow() in returns the HWND of the currently active window. ``` /// <summary> /// The GetForegroundWindow function returns a handle to the foreground window. /// </summary> [DllImport("user32.dll")] stat...
This [project](http://www.codeproject.com/KB/cs/windowhider.aspx) demonstrates the two functions you need: [EnumWindows](http://msdn.microsoft.com/en-us/library/ms633497(VS.85).aspx) and [GetWindowtext](http://msdn.microsoft.com/en-us/library/ms633520(VS.85).aspx)
How can I determine the current focused process name and version in C#
[ "", "c#", "process", "pinvoke", "user32", "" ]
I am writing a dhtml application that creates an interactive simulation of a system. The data for the simulation is generated from another tool, and there is already a very large amount of legacy data. Some steps in the simulation require that we play "voice-over" clips of audio. I've been unable to find an easy way t...
You will have to include a plug-in like Real Audio or QuickTime to handle the .wav file, but this should work... ``` //====================================================================== var soundEmbed = null; //====================================================================== function soundPlay(which) { ...
If you're using Prototype, the Scriptaculous library [has a sound API](http://github.com/madrobby/scriptaculous/wikis/sound). jQuery [appears to have a plugin](http://dev.jquery.com/browser/trunk/plugins/sound/jquery.sound.js?rev=5750), too.
Cross-platform, cross-browser way to play sound from Javascript?
[ "", "javascript", "audio", "cross-browser", "cross-platform", "dhtml", "" ]
I have an object that needs a test if the object data is valid. The validation itself would be called from the thread that instatiated the object, it looks like this: ``` { if (_step.Equals(string.Empty)) return false; if (_type.Equals(string.Empty)) return false; if (_setup.Equals(string.Empty)) return false; ...
My personal opinion here would be: * If the "validate" method mutates the object in any way (which your example doesn't) then make it a method. * If the object remains un-changed after validation, make it a property.
I would say as a Property. ``` if(something.IsValid) { ... ``` looks better then ``` if(something.IsValid()) { ... ``` Also an example from MSDN: <http://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid(VS.71).aspx>
Implement validation as a method or as a property?
[ "", "c#", "" ]
As it was made clear in my [recent question](https://stackoverflow.com/questions/212009/do-i-have-to-explicitly-call-systemexit-in-a-webstart-application), Swing applications need to explicitly call System.exit() when they are ran using the Sun Webstart launcher (at least as of Java SE 6). I want to restrict this hack...
When your code is launched via javaws, javaws.jar is loaded and the JNLP API classes that you don't want to depend on are available. Instead of testing for a system property that is not guaranteed to exist, you could instead see if a JNLP API class exists: ``` private boolean isRunningJavaWebStart() { boolean hasJ...
Use the javax.jnlp.ServiceManager to retrieve a webstart service. If it is availabe, you are running under Webstart. See <http://download.java.net/jdk7/docs/jre/api/javaws/jnlp/index.html>
What is the best way to detect whether an application is launched by Webstart
[ "", "java", "java-web-start", "" ]
Basically the question is how to get from this: ``` foo_id foo_name 1 A 1 B 2 C ``` to this: ``` foo_id foo_name 1 A B 2 C ```
``` SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id; ``` <https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat> From the link above, `GROUP_CONCAT`: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there a...
``` SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id ``` More details [here](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat). From the link above, `GROUP_CONCAT`: This function returns a string result with the concatenated non-NULL values from a group. It ret...
How to use GROUP BY to concatenate strings in MySQL?
[ "", "sql", "mysql", "string", "aggregate", "concatenation", "" ]
I have a modal popup that initially shows some content but expands a div if a checkbox is selected. The modal expands correctly but doesn't recenter unless you scroll up or down. Is there a javascript event I can tack on to my javascript function to recenter the entire modal?
Here is what it is: ``` $find('ModalPopupExtenderClientID')._layout(); ``` For example: ``` $find('detailsPopUpExtenderId')._layout(); ``` and in aspx: ``` <ccl:ModalPopupExtender runat="server" ID="MyPopUpExtender" TargetControlID="pop" PopupControlID="PopUp" BehaviorID="detailsPopUpExtenderId" BackgroundCssClass...
Be careful that this isn't tied to the resize event of the window. If it is, your recentering could trigger a resize event in IE, which would cause an infinte loop. If it is tied to the resize event, allow 1 or 2 resize events to occur, but then ignore the rest. (I say 2, because in IE, a "restore" event on the window...
Re-center Modal Popup with Javascript
[ "", "asp.net", "javascript", "" ]
In a PHP project I'm working on we need to create some DAL extensions to support multiple database platforms. The main pitfall we have with this is that different platforms have different syntaxes - notable MySQL and MSSQL are quite different. ## What would be the best solution to this? Here are a couple we've discus...
I'd recommend class-based SQL building and recommend [Doctrine](http://phpdoctrine.org/), [Zend\_Db](http://framework.zend.com/manual/en/zend.db.html) or [MDB2](http://pear.php.net/package/MDB2). And yeah, if it requires more lines to write simple selects but at least you get to rely on a parser and don't need to re-in...
A solution could be to have different sets of queries for different platforms with ID's something like MySql: GET\_USERS = "SELECT \* FROM users" MsSql: GET\_USERS = ... PgSql: GET\_USERS = ... Then on startup you load the needed set of queries and refers then Db::loadQueries(platform): $users = $db->query(GET\_U...
Database Abstraction - supporting multiple syntaxes
[ "", "sql", "database", "data-access-layer", "database-abstraction", "" ]
I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this?
Three options: * You can return it from `Main` if you declare your `Main` method to return `int`. * You can call [`Environment.Exit(code)`](https://learn.microsoft.com/en-us/dotnet/api/system.environment.exit). * You can set the [exit code](https://learn.microsoft.com/en-us/dotnet/api/system.environment.exitcode) usin...
In addition to the answers covering the return int's... a plea for sanity. Please, please define your exit codes in an enum, with Flags if appropriate. It makes debugging and maintenance so much easier (and, as a bonus, you can easily print out the exit codes on your help screen - you do have one of those, right?). ``...
How do I specify the exit code of a console application in .NET?
[ "", "c#", ".net", "exit-code", "" ]
I understand that server-side validation is an absolute must to prevent malicious users (or simply users who choose to disable javascript) from bypassing client-side validation. But that's mainly to protect your application, not to provide value for those who are running browsers with javascript disabled. Is it reasona...
I browse with NoScript in Firefox, and it always annoys me when I get pages that don't work. That said - know your audience. If you're trying to cater to paranoid computer security professionals - assume they might not have JavaScript enabled. If you're going for a general audience, JavaScript is probably on.
Totally depends on who you're aiming at. If your site or app is for an Intranet, you can make lots of assumptions. If your target audience is bleeding-edge social-networking types, you can assume JavaScript will work. If you anticipate a lot of paranoia sysadmin types, you can assume a bunch of them will be trying to ...
Is it reasonable to assume my visitors have javascript enabled?
[ "", "javascript", "" ]
How can you change the `href` attribute (link target) for a hyperlink using jQuery?
Using ``` $("a").attr("href", "http://www.google.com/") ``` will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags: ``` <a name="MyLinks"></a> <a hre...
With jQuery 1.6 and above you should use: ``` $("a").prop("href", "http://www.jakcms.com") ``` The difference between `prop` and `attr` is that `attr` grabs the HTML attribute whereas `prop` grabs the DOM property. You can find more details in this post: [.prop() vs .attr()](https://stackoverflow.com/questions/58746...
How to change the href attribute for a hyperlink using jQuery
[ "", "javascript", "html", "jquery", "hyperlink", "" ]
I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this. Thanks ...
With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version: First, install 2.6rc2. You can download the source from the [Python website](http://www.python.org/download/releases/2.6/). Standard `./configure && make && sudo make install` installation style. ...
I have the same issue, and apparently pre-built binaries can be found here: ``` # Python 2.6 deb http://ppa.launchpad.net/doko/ubuntu intrepid main deb-src http://ppa.launchpad.net/doko/ubuntu intrepid main ```
How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04?
[ "", "python", "linux", "ubuntu", "installation", "" ]
What's the best way to add the coordinates of a circle to an array in JavaScript? So far I've only been able to do a half circle, but I need a formula that returns the whole circle to two different arrays: `xValues` and `yValues`. (I'm trying to get the coordinates so I can animate an object along a path.) **Here's wh...
Your loop should be set up like this instead: ``` for (var i = 0; i < steps; i++) { xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps)); yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps)); } ``` * Start your loop at 0 * Step through the entire 2 \* PI range, not just PI. * You...
Bresenham's algorithm is way faster. You hear of it in relation to drawing straight lines, but there's a form of the algorithm for circles. Whether you use that or continue with the trig calculations (which are blazingly fast these days) - you only need to draw 1/8th of the circle. By swapping x,y you can get another ...
Circle coordinates to array in Javascript
[ "", "javascript", "arrays", "geometry", "formula", "" ]
I was just wondering, if by moving complex if else statements and the resulting html markup to the code behind violates some 'MVC' law? It seems like a great option when faced with inline if else statements that can become extremely unreadable.
I prefer not to use the code behind class in my views. This is not because it violates MVC by default, but because I found that the "natural" way (at least for me) is different. When I face complex HTML markup that relates to purely view concerns, I usually write an extension method for `HtmlHelper` class in order to ...
It's not horrible to have conditionals in your view. I would keep them in the ASPX not the code behind. However, a conditional often indicates controlling behavior. Consider the following ASPX code: ``` <%if (ViewData["something"] == "foo") {%> <%=Html.ActionLink("Save", "Save") %> <%}%> <%if (ViewData["somethin...
Moving complex conditional statements to code behind
[ "", "c#", "asp.net-mvc", "code-behind", "" ]
I have a very strange problem, when I try to `var_dump` (or `print_r`) a Doctrine Object, my Apache responses with an empty blank page (200 OK header). I can `var_dump` a normal php var like: ``` $dummy = array("a" => 1, "b" =>2); ``` And it works fine. But I can't with any object from any Doctrine class, (like a res...
I've had that sometimes when trying to `print_r()` a self-referencing object - it gets into a loop and runs out of memory. Possibly that's what's happening to you. Try increasing the memory limit (`ini_set('memory_limit', '256M');`) and see if that fixes it. Edit: I don't think there's an actual fix for this - it's P...
Lazy load proxies always contain an instance of Doctrine’s EntityManager and all its dependencies. Therefore a `var_dump` will possibly dump a very large recursive structure which is impossible to render and read. You have to use `\Doctrine\Common\Util\Debug::dump()` to restrict the dumping to a human readable level. ...
Why var_dump a Doctrine Objects kill my Apache?
[ "", "php", "doctrine", "" ]
I have a series of datetime objects and would like to calculate the average delta between them. For example, if the input was `(2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00)`, then the average delta would be exactly 00:10:00, or 10 minutes. Any suggestions on how to calculate this using Python?
You can subtract each successive date from the one prior (resulting in a timedelta object which represents the difference in days, seconds). You can then average the timedelta objects to find your answer.
As far as algorithms go, that's an easy one. Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at. If you have an array a of datetimes, you can do: ``` mx = max(a) mn = min(a) avg = (mx-mn)/(len(a)-1) ``` to get back the average difference. EDIT: fixed the of...
Average difference between dates in Python
[ "", "python", "algorithm", "datetime", "" ]
This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter... Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following: ``` //---- SomeSourceFile.cpp ---- #define DEB...
My initial reaction was *`#ifdef`, of course*, but I think `#if` actually has some significant advantages for this - here's why: First, you can use `DEBUG_ENABLED` in preprocessor *and* compiled tests. Example - Often, I want longer timeouts when debug is enabled, so using `#if`, I can write this ``` DoSomethingSlo...
They're both hideous. Instead, do this: ``` #ifdef DEBUG #define D(x) do { x } while(0) #else #define D(x) do { } while(0) #endif ``` Then whenever you need debug code, put it inside `D();`. And your program isn't polluted with hideous mazes of `#ifdef`.
#ifdef vs #if - which is better/safer as a method for enabling/disabling compilation of particular sections of code?
[ "", "c++", "c", "if-statement", "coding-style", "c-preprocessor", "" ]
Here's the problem: ``` split=re.compile('\\W*') ``` This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like `k&amp;auml;ytt&amp;auml;j&aml;auml;`. What should I add to the regex to include the `&` and `;` characters?
You probably want to take the problem reverse, i.e. finding all the character without the spaces: ``` [^ \t\n]* ``` Or you want to add the extra characters: ``` [a-zA-Z0-9&;]* ``` In case you want to match HTML entities, you should try something like: ``` (\w+|&\w+;)* ```
I would treat the entities as a unit (since they also can contain numerical character codes), resulting in the following regular expression: ``` (\w|&(#(x[0-9a-fA-F]+|[0-9]+)|[a-z]+);)+ ``` This matches * either a word character (including “`_`”), or * an HTML entity consisting of + the character “`&`”, - the ...
Looking for a regular expression including alphanumeric + "&" and ";"
[ "", "python", "regex", "encoding", "" ]
I have saved input from a textarea element to a TEXT column in MySQL. I'm using PHP to pull that data out of the database and want to display it in a p element while still showing the whitespace that the user entered (e.g. multiple spaces and newlines). I've tried a pre tag but it doesn't obey the width set in the cont...
You can cause the text inside the `pre` to wrap by using the following CSS ``` pre { white-space: pre-wrap; /* css-3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Expl...
You could just use PHP's [nl2br function](https://www.php.net/nl2br).
Displaying whitespace in HTML when pulling from MySQL TEXT column
[ "", "php", "mysql", "html", "" ]
I'm attempting to put together some basic report screens. I've got some fairly complicated SQL queries that I'm feeding into ActiveRecord's find\_by\_sql method. The problem I am having here is that I am losing the order of the columns as given in the original query. I'm assuming that this is because the Hash class doe...
You're correct in that the Ruby Hash does not preserve order. That's part of the point, really - you access it using the key. I assume your query is written to deliver the columns in the order that you want to output them and you were hoping to output the values via a loop? Seems like a decent enough idea, but I can't...
I like to use [Ruport](https://ruport.github.io/) for reporting. It has good ActiveRecord integration and it enables you to control column order and pretty much anything else. And it's sufficiently simple to use that I don't consider it overkill even for "basic" reports.
Column order of results from rails ActiveRecord find_by_sql call
[ "", "sql", "ruby-on-rails", "ruby", "activerecord", "" ]
I've got a web application that is running against Windows Authentication using our Active Directory. I've got a new requirement to pull some personal information through from the Active Directory entry. What would be the easiest way to get access to this information?
Accessing the user directly through a DirectoryEntry seems like the most straightforward approach. Here are some AD-related tidbits I learned from my first AD-related project: * In a URI, write LDAP in lowercase. Otherwise you'll get a mystery error. I spent more than a day on this depressing issue... * To clear a sin...
You might find the following snippet useful as a starter. ``` public static bool IsUserInGroup(string lanid, string group) { DirectoryEntry entry = new DirectoryEntry("LDAP://" + LDAPPATH); if(entry != null) { entry.Username=@"LDAPUSER"; entry.Password="LDAPPASSWORD"; DirectorySearc...
Active Directory: Retrieve User information
[ "", "c#", "active-directory", "" ]
By that I mean, what do I need to do to have useful assertions in my code? MFC is quite easy, i just use ASSERT(something). What's the non-MFC way? **Edit:** Is it possible to stop assert breaking in assert.c rather than than my file which called assert()? **Edit:** What's the difference between `<assert.h>` & `<ca...
``` #include <cassert> assert(something); ``` and for compile-time checking, Boost's static asserts are pretty useful: ``` #include <boost/static_assert.hpp> BOOST_STATIC_ASSERT(sizeof(int) == 4); // compile fails if ints aren't 32-bit ```
It depends on whether or not you are looking for something that works outside of Visual C++. It also depends on what type of assertion you are looking for. There are a few types of assertions: 1. **Preprocessor** These assertions are done using the preprocessor directive `#error` Preprocessor assertions are...
What is the best way of implementing assertion checking in C++?
[ "", "c++", "debugging", "assert", "debugbreak", "" ]
I've often heard criticism of the lack of thread safety in the Swing libraries. Yet, I am not sure as to what I would be doing in my own code with could cause issues: In what situations does the fact Swing is not thread safe come into play ? What should I actively avoid doing ?
1. Never do long running tasks in response to a button, event, etc as these are on the event thread. If you block the event thread, the ENTIRE GUI will be completely unresponsive resulting in REALLY pissed off users. This is why Swing seems slow and crusty. 2. Use Threads, Executors, and SwingWorker to run tasks NOT ON...
This is one of those questions that makes me glad I purchased [Robinson & Vorobiev's book on Swing](http://www.manning.com/robinson2/). **Anything that accesses the state of a `java.awt.Component` should be run inside the EDT, with three exceptions:** anything specifically documented as thread-safe, such as `repaint()...
Java: Swing Libraries & Thread Safety
[ "", "java", "multithreading", "swing", "" ]
I'm a total newbie, but I was writing a little program that worked on strings in C# and I noticed that if I did a few things differently, the code executed significantly faster. So it had me wondering, how do you go about clocking your code's execution speed? Are there any (free)utilities? Do you go about it the old-f...
What you are describing is known as performance profiling. There are many programs you can get to do this such as [Jetbrains profiler](http://www.jetbrains.com/profiler/) or [Ants profiler](http://www.red-gate.com/products/ants_profiler/index.htm), although most will slow down your application whilst in the process of ...
[ANTS Profiler from RedGate](http://www.red-gate.com/products/ants_profiler/index.htm) is a really nice performance profiler. [dotTrace Profiler from JetBrains](http://www.jetbrains.com/profiler/) is also great. These tools will allow you to see performance metrics that can be drilled down the each individual line. Sc...
Testing your code for speed?
[ "", "c#", "performance", "profiling", "timing", "" ]
We're getting ready to translate our PHP website into various languages, and the gettext support in PHP looks like the way to go. All the tutorials I see recommend using the english text as the message ID, i.e. gettext("Hi there!") But is that really a good idea? Let's say someone in marketing wants to change the te...
I use meaningful IDs such as "`welcome_back_1`" which would be "`welcome back, %1`" etc. I always have English as my "base" language so in the worst case scenario when a specific language doesn't have a message ID, I fall-back on English. I don't like to use actual English phrases as message ID's because if the Englis...
Wow, I'm surprised that no one is advocating using the English as a key. I used this style in a couple of software projects, and IMHO it worked out pretty well. The code readability is great, and if you change an English string it becomes obvious that the message needs to be considered for re-translation (which is a go...
Gettext: Is it a good idea for the message ID to be the english text?
[ "", "php", "internationalization", "gettext", "" ]
Most python frameworks will have a development webserver of some kind that will have a warning that it isn't for use as production servers. How much different do they tend to be from their production equivalents? I haven't quite decided which framework to go with, much less what production server to use, so it's kinda...
The lower environments should try to match the production environment as closely as possible given the resources available. This applies to all development efforts regardless of whether they are python-based or even web-based. In practical terms, most organizations are not willing to spend that type of money. In this c...
Generally, they are same in terms of the settings which are required to run the applications which include the environment setting. However, the clients genereally have dev systems which are less powerful in terms of the processing power and other h/w resources. I have seen using them virtual servers in dev evironme...
How close are development webservers to production webservers?
[ "", "python", "webserver", "web-frameworks", "" ]
I have been looking at a few options for enabling localization and internationalization of a dynamic php application. There appears to be a variety of tools available such as gettext and Yahoo's R3 and I am interested in hearing from both developers and translators about which tools are good to use and what functionali...
PHP gettext implementation works very smoothly. And po files with po edit and gettext are about as good a way as you can get to deal with localization bearing in mind that no solution of this kind can completely handle the complexities of the various languages. For example, the gettext method is very good on plural for...
We've been tinkering with[Zend\_Translate](http://framework.zend.com/manual/en/zend.translate.html), since we use the Zend Framework anyway. It's very well documented and so far extremly solid. In the past, I've pretty much used my own *home-grown* solution mostly. Which involves language files with constants or varia...
What are good tools/frameworks for i18n of a php codebase?
[ "", "php", "internationalization", "" ]
Trying to create a user account in a test. But getting a Object reference is not set to an instanve of an object error when running it. Here's my MemberShip provider class, it's in a class library MyCompany.MyApp.Domain.dll: ``` using System; using System.Collections.Generic; using System.Web.Security; namespace MyC...
I'm quite sure you should call provider.Initialize(...) in your test code before calling CreateUser.
Well not quite anyone had the answer. csgero was on the right track though initialize was the problem. But just calling that directly was not a solution. This works: ``` public class MemberTest { public static void CreateAdminMemberIfNotExists() { MembershipCreateStatus status; ...
Unit test Custom membership provider with NUnit throws null reference error
[ "", "c#", ".net", "unit-testing", "nunit", "membership", "" ]
Can I run the python interpreter without generating the compiled .pyc files?
From ["What’s New in Python 2.6 - Interpreter Changes"](http://docs.python.org/dev/whatsnew/2.6.html#interpreter-changes): > Python can now be prevented from > writing .pyc or .pyo files by > supplying the [-B](http://docs.python.org/using/cmdline.html#cmdoption-B) switch to the Python > interpreter, or by setting the...
``` import sys sys.dont_write_bytecode = True ```
How to avoid .pyc files?
[ "", "python", "" ]
[This question](https://stackoverflow.com/questions/57168/how-to-copy-a-row-from-one-sql-server-table-to-another) comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this: ``` insert into MyT...
Try this: ``` insert into MyTable(field1, field2, id_backup) select field1, field2, uniqueId from MyTable where uniqueId = @Id; ``` Any fields not specified should receive their default value (which is usually NULL when not defined).
I like this solution. I only have to specify the identity column(s). ``` SELECT * INTO TempTable FROM MyTable_T WHERE id = 1; ALTER TABLE TempTable DROP COLUMN id; INSERT INTO MyTable_T SELECT * FROM TempTable; DROP TABLE TempTable; ``` The "id"-column is the identity column and that's the only column I have to speci...
How do you copy a record in a SQL table but swap out the unique id of the new row?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I'm trying to serialize objects from a database that have been retrieved with Hibernate, and I'm only interested in the objects' actual data in its entirety (cycles included). Now I've been working with [XStream](http://xstream.codehaus.org/), which seems powerful. The problem with XStream is that it looks all too bli...
solution described here worked well for me: <http://jira.codehaus.org/browse/XSTR-226> the idea is to have custom XStream converter/mapper for hibernate collections, which will extract actual collection from hibernate one and will call corresponding standard converter (for ArrayList, HashMap etc.)
I recommend a simpler approach: user dozer: <http://dozer.sf.net>. Dozer is a bean mapper, you can use it to convert, say, a PersonEJB to an object of the same class. Dozer will recursively trigger all proxy fecthes through getter() calls, and will also convert src types to dest types (let's say java.sql.date to java.u...
How to Serialize Hibernate Collections Properly?
[ "", "java", "hibernate", "serialization", "collections", "" ]
I am trying to save data to a database on a button push, but the variables seem to be private by the nature of where they are defined. I have tried to move where they are defined, but this seems to produce other errors. Given a fix, why was it fixed that way? The code follows. ``` namespace enable { public parti...
You're declaring `dTable` and `adapter` in the constructor, so it goes out of scope as soon as the constructor is completed. You want to move the variable declarations out into the main class, like: ``` public partial class Form1 : Form { private DataTable dTable; private OleDbDataAdapter adapter; Public...
``` namespace enable { public partial class Form1 : Form { OleDbDataAdapter adapter; DataTable dTable = new DataTable(); public Form1() { InitializeComponent(); OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.J...
Help someone new to C# variables
[ "", "c#", "variables", "" ]
What are the easiest steps to make a small circuit with an LED flash from a C/C++ program? I would prefer the least number of dependencies and packages needed. * What port would I connect something into? * Which compiler would I use? * How do I send data to that port? * Do I need to have a micro-processor? If not I d...
Here's a tutorial on doing it with a [parallel port](http://ashishrd.blogspot.com/2006/11/controlling-leds-with-parallel-port.html). Though I would recommend an [Arduino](http://www.arduino.cc) which can be purchased very cheaply and would only involve the following code: ``` /* Blinking LED * ------------ * * tur...
**Which port?** Parallel port is my favorite choice since it outputs +5V (TTL logic level) and is very straightforward to program. Most parallel ports have enough power to drive an LED. It's important to remember that computer ports in general are designed to only output signaling voltages, and not to produce enough cu...
Steps to make a LED blink from a C/C++ program?
[ "", "c++", "c", "circuit", "" ]
I'd like to have comments in my code, but I want them to be removed before deploying. Yes, it's not hard to write such a thing, but if it already exists… And how about comments in ASP pages?
Sounds like you are looking for a JSMin tool or similar. There are many tools which you can purchase, but there are also some online tools you can use: <http://www.askapache.com/tools/online-compression-tool-compares-packer-jsmin-dojo-and-yui-compressor.html> <http://www.askapache.com/online-tools/js-compress/> Goo...
[YUI Compressor](http://developer.yahoo.com/yui/compressor/) in addition to removing comments and white-spaces, obfuscates local variables using the smallest possible variable name... Besides the utility, there is the [YUI Compressor Library for .NET](http://www.codeplex.com/YUICompressor), this library allows you to ...
Is there any tools for automatic removal of comments from JavaScript code?
[ "", "asp.net", "javascript", "comments", "" ]
This is my query: ``` $query = $this->db->query(' SELECT archives.id, archives.signature, type_of_source.description, media_type.description, origin.description FROM archives, type_of_source, media_type, origin WHERE archives.type_of_source_id =...
This actually has very little to do with CodeIgniter and a lot with how mysql\_fetch\_assoc provides the query results. The solution is that you should rename the columns inside the query using `"AS"`, e.g. ``` select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion...
Just alias the columns in the SELECT statement. Do not modify your database. The standard practice is to use aliasing in your SQL statements. From PostgreSQL's docs for `"SELECT"`: "Using the clause AS output\_name, another name can be specified for an output column." [PostgreSQL SELECT](http://www.postgresql.org/do...
How to output data from tables with same column names in CodeIgniter?
[ "", "sql", "database", "codeigniter", "" ]
I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The promp...
Using jQuery: ``` var _isDirty = false; $("input[type='text']").change(function(){ _isDirty = true; }); // replicate for other input types and selects ``` Combine with `onunload`/`onbeforeunload` methods as required. From the comments, the following references all input fields, without duplicating code: ``` $(':i...
One piece of the puzzle: ``` /** * Determines if a form is dirty by comparing the current value of each element * with its default value. * * @param {Form} form the form to be checked. * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code> * otherwise. */ function formI...
Detecting Unsaved Changes
[ "", "javascript", "asp.net", "prompt", "" ]