Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
What are some good resources to learn best practices for Javascript? I'm mainly concerned about when something should be an object vs. when it should just be tracked in the DOM. Also I would like to better learn how to organize my code so it's easy to unit test. | Seconding [Javascript: The Good Parts](http://oreilly.com/catalog/9780596517748/) and Resig's book [Secrets of the Javascript Ninja](http://jsninja.com/).
Here are some tips for Javascript:
* Don't pollute the global namespace (put all functions into objects/closures)
+ Take a look at [YUI](http://developer.yahoo.c... | I disagree to the "use a framework" statement to some degree. Too many people use frameworks blindly and have little or no understanding of what's going on behind the curtains. | Javascript Best Practices | [
"",
"javascript",
"unit-testing",
""
] |
I want to open a file for reading, the C++ way. I need to be able to do it for:
* text files, which would involve some sort of read line function.
* binary files, which would provide a way to read raw data into a `char*` buffer. | There are three ways to do this, depending on your needs. You could use the old-school C way and call `fopen`/`fread`/`fclose`, or you could use the C++ fstream facilities (`ifstream`/`ofstream`), or if you're using MFC, use the `CFile` class, which provides functions to accomplish actual file operations.
All of these... | You need to use an [`ifstream`](http://en.cppreference.com/w/cpp/io/basic_ifstream) if you just want to read (use an `ofstream` to write, or an `fstream` for both).
To open a file in text mode, do the following:
```
ifstream in("filename.ext", ios_base::in); // the in flag is optional
```
To open a file in binary mo... | How do you open a file in C++? | [
"",
"c++",
"file",
"io",
""
] |
If so how?
Did you roll your own with jQuery or use the Microsoft AJAX toolkit?
Did you create a webservice or call an action?
---
**EDIT** : Please note that this question was asked before Microsoft announced that they were going to bundle jQuery in with VS/ASP.NET MVC. I think there is less of a discussion around... | jQuery, action, return JSON.
<http://devlicio.us/blogs/mike_nichols/archive/2008/05/25/jquery-cascade-cascading-values-from-forms.aspx> | I've spent the past day or two getting @[Matt Hinze's answer](https://stackoverflow.com/questions/39735/have-you-got-a-cascadingdropdown-working-with-aspnet-mvc#40120) to work. It works well. jQuery is the prefferred method of doing AJAX in the forthcoming [ASP.NET MVC In Action](http://www.manning.com/palermo/) book f... | Have you got a CascadingDropDown working with ASP.NET MVC? | [
"",
"c#",
"asp.net-mvc",
"ajax",
"controls",
""
] |
I've got a situation where I have a main form that pops up an advanced configuration form that just has half a dozen matched check boxes and combo boxes to select some advanced options (the check boxes to enable/disable, the combo to select a media if enabled).
If I just pass the individual settings for the check and ... | I personally would create a carrier object to store the values. You then get the nice intellisense for it, and changes to it would be quite straightforward. It would also be faster than dictionary lookups for parameter values. And of course, you get type safety. :) | You could go with Rob's solution; that's the prettiest for development. Your "carrier object" could contain the entire IDictionary and have typed properties to help intellisense. The properties could update the IDictionary. When you're done, you can pass the carrier object back and fetch the IDictionary directly from i... | Best way to pass a large number of arguments into a configuration dialog | [
"",
"c#",
""
] |
For certain types of sql queries, an auxiliary table of numbers can be very useful. It may be created as a table with as many rows as you need for a particular task or as a user defined function that returns the number of rows required in each query.
What is the optimal way to create such a function? | Heh... sorry I'm so late responding to an old post. And, yeah, I had to respond because the most popular answer (at the time, the Recursive CTE answer with the link to 14 different methods) on this thread is, ummm... performance challenged at best.
First, the article with the 14 different solutions is fine for seeing ... | The most optimal function would be to use a table instead of a function. Using a function causes extra CPU load to create the values for the data being returned, especially if the values being returned cover a very large range. | SQL, Auxiliary table of numbers | [
"",
"sql",
"sql-server",
""
] |
I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:
```
var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
```
This is not allowed. How do I get something like this wo... | You can't query against the `DataTable`'s *Rows* collection, since `DataRowCollection` doesn't implement `IEnumerable<T>`. You need to use the `AsEnumerable()` extension for `DataTable`. Like so:
```
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;
```
And as [... | ```
var results = from DataRow myRow in myDataTable.Rows
where (int)myRow["RowNo"] == 1
select myRow
``` | LINQ query on a DataTable | [
"",
"c#",
".net",
"linq",
"datatable",
".net-3.5",
""
] |
I'm looking for a good article on using emacs as C/C++ IDE.
Something like Steve Yegge's ["Effective emacs"](http://steve.yegge.googlepages.com/effective-emacs). | No specific article, really, but I've found [EmacsWiki](http://www.emacswiki.org/cgi-bin/wiki) to be full of useful information. Consider checking out these entries:
* [CPlusPlus](http://www.emacswiki.org/cgi-bin/wiki/CPlusPlus) as a starting point for many C++-related articles, and
* [CppTemplate](http://www.emacswik... | I've recently stumbled upon this [article](http://www.physics.ucsb.edu/~taro/comp/tips/emacs/emacs-c-dev.html) which is quite good.
EDIT: Yep the link is no longer valid. It seems like they've changed their url recently and it doesn't redirect properly. Hopefully it will be back soon. Anyway the article was called "Be... | Any good advice on using emacs for C++ project? | [
"",
"c++",
"emacs",
""
] |
I'm trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances. For example, I have this string:
```
12||34||56
```
I want to replace the second set of pipes with ampersands to get this string:
```
12||34&&56
```
The regex funct... | here's something that works:
```
"23||45||45||56||67".replace(/^((?:[0-9]+\|\|){n})([0-9]+)\|\|/,"$1$2&&")
```
where n is the one less than the nth pipe, (of course you don't need that first subexpression if n = 0)
And if you'd like a function to do this:
```
function pipe_replace(str,n) {
var RE = new RegExp("^... | # A more general-purpose function
I came across this question and, although the title is very general, the accepted answer handles only the question's specific use case.
I needed a more general-purpose solution, so I wrote one and thought I'd share it here.
## Usage
This function requires that you pass it the follo... | Replacing the nth instance of a regex match in Javascript | [
"",
"javascript",
"regex",
""
] |
I remember first learning about vectors in the STL and after some time, I wanted to use a vector of bools for one of my projects. After seeing some strange behavior and doing some research, I learned that [a vector of bools is not really a vector of bools](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=... | A short list might be:
* Avoid memory leaks through use shared pointers to manage memory allocation and cleanup
* Use the [Resource Acquisition Is Initialization](https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) (RAII) idiom to manage resource cleanup - especially in the presence of exceptions
* A... | ## Pitfalls in decreasing order of their importance
First of all, you should visit the award winning [C++ FAQ](https://isocpp.org/faq). It has many good answers to pitfalls. If you have further questions, visit `##c++` on `irc.freenode.org` in [IRC](http://en.wikipedia.org/wiki/Internet_Relay_Chat). We are glad to hel... | What C++ pitfalls should I avoid? | [
"",
"c++",
"stl",
""
] |
You should be able to create a generic form:
```
public partial class MyGenericForm<T> :
Form where T : class
{
/* form code */
public List<T> TypedList { get; set; }
}
```
Is valid C#, and compiles. However the designer won't work and the form will throw a runtime exception if you have any images stating... | Yes you can! Here's a blog post I made a while ago with the trick:
[Designing Generic Forms](http://www.madprops.org/blog/designing-generic-forms/)
Edit: Looks like you're already doing it this way. This method works fine so I wouldn't consider it too hacky. | I have a hack to workaround this, which works but isn't ideal:
Add a new class to the project that inherits the form with its simple name.
```
internal class MyGenericForm:
MyGenericForm<object> { }
```
This means that although the designer is still wrong the expected simple type (i.e without `<>`) is still foun... | Can you use generic forms in C#? | [
"",
"c#",
".net",
"winforms",
""
] |
Warning - I am very new to NHibernate. I know this question seems simple - and I'm sure there's a simple answer, but I've been spinning my wheels for some time on this one. I am dealing with a legacy db which really can't be altered structurally. I have a details table which lists payment plans that have been accepted ... | I'd steer away from having child object containing their logical parent, it can get very messy and very recursive pretty quickly when you do that. I'd take a look at how you're intending to use the domain model before you do that sort of thing. You can easily still have the ID references in the tables and just leave th... | Didn't see your database diagram whilst I was writing.
```
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping default-cascade="save-update" xmlns="urn:nhibernate-mapping-2.2">
<class lazy="false" name="Namespace.Customer, Namespace" table="Customer">
<id name="Id" type="Int32" unsaved-value="0">
... | Best way to model Many-To-One Relationships in NHibernate When Dealing With a Legacy DB? | [
"",
"c#",
"nhibernate",
""
] |
I have been looking into IKVMing Apache's FOP project to use with our .NET app. It's a commercial product, and looking into licensing, IKVM runs into some sticky areas because of its use of GNU Classpath. From what I've seen, no one can say for sure if this stuff can be used in a commercial product. Has anyone used IKV... | There are multiple issues here as ikvm is currently being transitioned away from the GNU classpath system to Sun's OpenJDK. Both are licensed as GPL+Exceptions to state explicitly that applications which merely use the OpenJDK libraries will not be considered derived works.
Generally speaking, applications which rely ... | Just a quick update on this after noticing the question, for anyone browsing by.
IKVM seem to have updated to use the OpenJDK and not the GNU Classpath, infact IKVM.net have removed the comment from their license page. | IKVM and Licensing | [
"",
"java",
".net",
"ikvm",
"gnu-classpath",
""
] |
Does anyone know how I can, in platform-independent C++ code prevent an object from being created on the heap? That is, for a class "Foo", I want to prevent users from doing this:
```
Foo *ptr = new Foo;
```
and only allow them to do this:
```
Foo myfooObject;
```
Does anyone have any ideas?
Cheers, | [Nick's answer](https://stackoverflow.com/questions/10985/how-to-prevent-an-object-being-created-on-the-heap#11003) is a good starting point, but incomplete, as you actually need to overload:
```
private:
void* operator new(size_t); // standard new
void* operator new(size_t, void*); // placement new... | You could overload new for Foo and make it private. This would mean that the compiler would moan... unless you're creating an instance of Foo on the heap from within Foo. To catch this case, you could simply not write Foo's new method and then the linker would moan about undefined symbols.
```
class Foo {
private:
v... | How to prevent an object being created on the heap? | [
"",
"c++",
"stack",
"heap-memory",
""
] |
Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.
I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions... | You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them. | I would go with Ryan's answer if you really want to do this.
In general on a \*nix environment, you always want to err on giving away as little permissions as possible.
9 times out of 10, 755 is the ideal permission for this - as the only user with the ability to modify the files will be the webserver. Change this to... | What are the proper permissions for an upload folder with PHP/Apache? | [
"",
"php",
"apache",
"upload",
""
] |
Following on from my recent question on [Large, Complex Objects as a Web Service Result](https://stackoverflow.com/questions/17725/large-complex-objects-as-a-web-service-result). I have been thinking about how I can ensure all future child classes are serializable to XML.
Now, obviously I could implement the [IXmlSeri... | I'd write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is decorated appropriately. If you set up your build to run with tests, you can have the build fail when this test fails.
UPDATE: You said, "Looks like I will just have to roll my sleeves up and make sure tha... | You can write unit tests to check for this kind of thing - it basically uses reflection.
Given the fact this is possible I guess it would also be possible to write a FxCop rule, but I've never done such a thing. | Enforce Attribute Decoration of Classes/Methods | [
"",
"c#",
"xml",
"serialization",
"coding-style",
".net-attributes",
""
] |
Is there an existing application or library in *Java* which will allow me to convert a `CSV` data file to `XML` file?
The `XML` tags would be provided through possibly the first row containing column headings. | Maybe this might help: [JSefa](http://jsefa.sourceforge.net/quick-tutorial.html)
You can read CSV file with this tool and serialize it to XML. | As the others above, I don't know any one-step way to do that, but if you are ready to use very simple external libraries, I would suggest:
[OpenCsv](http://opencsv.sourceforge.net/) for parsing CSV (small, simple, reliable and easy to use)
**Xstream** to parse/serialize XML (very very easy to use, and creating fully... | Java lib or app to convert CSV to XML file? | [
"",
"java",
"xml",
"csv",
"data-conversion",
""
] |
Let's say that you want to output or concat strings. Which of the following styles do you prefer?
* `var p = new { FirstName = "Bill", LastName = "Gates" };`
* `Console.WriteLine("{0} {1}", p.FirstName, p.LastName);`
* `Console.WriteLine(p.FirstName + " " + p.LastName);`
Do you rather use format or do you simply conc... | Try this code.
It's a slightly modified version of your code.
1. I removed Console.WriteLine as it's probably a few orders of magnitude slower than what I'm trying to measure.
2. I'm starting the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example... | I'm amazed that so many people immediately want to find the code that executes the fastest. *If ONE MILLION iterations STILL take less than a second to process, is this going to be in ANY WAY noticeable to the end user? Not very likely.*
> Premature optimization = FAIL.
I'd go with the `String.Format` option, only be... | String output: format or concat in C#? | [
"",
"c#",
"string",
"coding-style",
"string.format",
""
] |
I'm currently using VS2005 Profesional and .NET 2.0, and since our project is rather large (25 projects in the solution), I'd like to try VS 2008, since its theoretically faster with larger projects.
Before doing such thing, i'd like to know if what I've read is true: can I use VS2008 in ".net 2.0" mode? I don't want ... | yes, vs2008 can "[target](http://weblogs.asp.net/scottgu/archive/2007/06/20/vs-2008-multi-targeting-support.aspx)" a framework, but i think by default, if converting from vs2005 - vs2008 it just keeps it at framework 2.0 | Yes it's possible. In the project properties you can target different versions of the .Net Framework going back to .NET 2.0.
Upgrading to VS 2008 will upgrade your Solution file and you won't be able to go back to VS 2005 unless you have backed up your solution | Moving from Visual Studio 2005 to 2008 and .NET 2.0 | [
"",
"c#",
".net",
"visual-studio",
".net-3.5",
".net-2.0",
""
] |
I am trying to generate a report by querying 2 databases (Sybase) in classic ASP.
I have created 2 connection strings:
> connA for databaseA
> connB for databaseB
Both databases are present on the same server (don't know if this matters)
Queries:
`q1 = SELECT column1 INTO #temp FROM databaseA..table1 WHERE xyz="... | With both queries, it looks like you are trying to insert into #temp. #temp is located on one of the databases (for arguments sake, databaseA). So when you try to insert into #temp from databaseB, it reports that it does not exist.
Try changing it from *Into **#temp** From* to *Into **databaseA.dbo.#temp** From* in bo... | your temp table is out of scope, it is only 'alive' during the first connection and will not be available in the 2nd connection
Just move all of it in one block of code and execute it inside one conection | Select Query on 2 tables, on different database servers | [
"",
"sql",
"asp-classic",
"vbscript",
"sybase",
""
] |
I need to call a web service written in .NET from Java. The web service implements the WS-Security stack (either WSE 2 or WSE 3, it's not clear from the information I have).
The information that I received from the service provider included WSDL, a policyCache.config file, some sample C# code, and a sample application... | This seems to be a popular question so I'll provide an overview of what we did in our situation.
It seems that services built in .NET are following an older ws-addressing standard (<http://schemas.xmlsoap.org/ws/2004/03/addressing/>) and axis2 only understands the newer standard (<http://schemas.xmlsoap.org/ws/2004/08... | WS-Security specifications are not typically contained in a WSDL (never in a WSE WSDL). So wsdl2java does not know that WS-Security is even required for this service. The fact that security constraints are not present in a WSE WSDL is a big disappointment to me (WCF will include WS-Trust information in a WSDL).
On the... | Calling .NET Web Service (WSE 2/3, WS-Security) from Java | [
"",
"java",
".net",
"apache-axis",
"ws-security",
"wse",
""
] |
In an application that I am currently working on, a requirement is to bring a window of an external application to the foreground. Making Win32 API calls such as BringWindowToTop and SetForeground window do not work all the time. This is due to some restrictions within Windows XP. What I would like to do instead is sen... | Check out the section "How to steal focus on 2K/XP" at <http://www.codeproject.com/KB/dialog/dlgboxtricks.aspx>, as this is exactly what you need. I wouldn't go the taskbar route as the taskbar could be hidden or simply not there. | It's possible. But it's extremely sketchy. Your application may also break with the next version of Windows, since it's undocumented. What you need to do is find the window handle of the taskbar, then find the window handle of the child window representing the button, then send it a WM\_MOUSEDOWN (I think) message.
He... | Sending a mouse click to a button in the taskbar using C# | [
"",
"c#",
".net",
"windows",
"winapi",
""
] |
I have a list of integers, `List<Integer>` and I'd like to convert all the integer objects into Strings, thus finishing up with a new `List<String>`.
Naturally, I could create a new `List<String>` and loop through the list calling `String.valueOf()` for each integer, but I was wondering if there was a better (read: *m... | As far as I know, iterate and instantiate is the only way to do this. Something like (for others potential help, since I'm sure you know how to do this):
```
List<Integer> oldList = ...
/* Specify the size of the list up front to prevent resizing. */
List<String> newList = new ArrayList<>(oldList.size());
for (Integer... | Using [Google Collections from Guava-Project](https://github.com/google/guava/), you could use the `transform` method in the [Lists](https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Lists.html) class
```
import com.google.common.collect.Lists;
import com.google.common.base.Functions
Lis... | Converting List<Integer> to List<String> | [
"",
"java",
"string",
"collections",
"integer",
""
] |
I have a "showall" query string parameter in the url, the parameter is being added dynamically when "Show All/Show Pages" button is clicked.
I want the ability to toggle "showall" query string parameter value depending on user clicking the "Show All/Show Pages" button.
I'm doing some nested "if's" and `string.Replace... | Just to elaborate on Toran's answer:
Use:
`<asp:HiddenField ID="ShowAll" Value="False" runat="server" />`
To toggle your state:
```
protected void ToggleState(object sender, EventArgs e)
{
//parse string as boolean, invert, and convert back to string
ShowAll.Value = (!Boolean.Parse(ShowAll.Value)).ToString... | Another dirty alternative could be just to use a hidden input and set that on/off instead of manipulating the url. | reassign value to query string parameter | [
"",
"c#",
"query-string",
""
] |
While I've seen rare cases where *private* inheritance was needed, I've never encountered a case where *protected* inheritance is needed. Does someone have an example? | People here seem to mistake Protected class inheritance and Protected methods.
FWIW, I've never seen anyone use protected class inheritance, and if I remember correctly I think Stroustrup even considered the "protected" level to be a mistake in c++. There's precious little you cannot do if you remove that protection l... | There is a very rare use case of protected inheritance. It is where you want to make use of [covariance](http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29 "Covariance"):
```
struct base {
virtual ~base() {}
virtual base & getBase() = 0;
};
struct d1 : private /* protected */... | Are there any examples where we *need* protected inheritance in C++? | [
"",
"c++",
"oop",
"inheritance",
""
] |
Ok, I have a strange exception thrown from my code that's been bothering me for ages.
```
System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall
at System.Net.Sockets.Socket.Accept()
at System.Net.Sockets.TcpListener.AcceptTcpClient()
```
MSDN isn't terribly ... | Is it possible that the serverSocket is being closed from another thread? That will cause this exception. | This is my example solution to avoid WSAcancelblablabla:
Define your thread as global then you can use invoke method like this:
```
private void closinginvoker(string dummy)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(closinginvoker), new object[] { dummy });
retu... | WSACancelBlockingCall exception | [
"",
"c#",
"multithreading",
"sockets",
"socketexception",
""
] |
There seem to be many ways to define [singletons](http://en.wikipedia.org/wiki/Singleton_pattern) in Python. Is there a consensus opinion on Stack Overflow? | I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway.
If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so ... | Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the `Instance` method. Here's an example:
```
@Singleton
class Foo:
def __init__(self):
print 'Foo created'
f = Foo() # Error, this isn't how you get the instance of a singleton
... | Is there a simple, elegant way to define singletons? | [
"",
"python",
"design-patterns",
"singleton",
""
] |
Does anyone know how to transform a enum value to a human readable value?
For example:
> ThisIsValueA should be "This is Value A". | Converting this from a vb code snippet that a certain Ian Horwill left at a [blog post long ago](http://secretgeek.net/progr_purga.asp)... i've since used this in production successfully.
```
/// <summary>
/// Add spaces to separate the capitalized words in the string,
/// i.e. insert a space before each ... | The .ToString on Enums is relatively slow in C#, comparable with GetType().Name (it might even use that under the covers).
If your solution needs to be very quick or highly efficient you may be best of caching your conversions in a static dictionary, and looking them up from there.
---
A small adaptation of @Leon's ... | Convert enums to human readable values | [
"",
"c#",
"enums",
"human-readable",
""
] |
Could someone recommend any good resources for creating Graphics User Interfaces, preferably in C/C++?
Currently my biggest influence is [3DBuzz.com](http://www.3dbuzz.com)'s [C++/OpenGL VTMs](http://www.3dbuzz.com/xcart/product.php?productid=30&cat=12&page=1) (Video Training Modules). While they are very good, they c... | I wouldn't use OpenGL for the GUI unless you are planning for hardware accelerated and/or 3D effects that you don't think you would get with a more traditional GUI toolkit (e.g [Qt](http://trolltech.com/), [wxWidgets](http://www.wxwidgets.org/), [GTK](http://www.gtk.org/), etc). If you just need a quick simple GUI for ... | Have a look at [Qt](https://www.qt.io/download-open-source/). It is an open source library for making GUI's. Unlike Swing in Java, it assumes a lot of stuff, so it is really easy to make functional GUI's. For example, a textarea assumes that you want a context menu when you right click it with copy, paste, select all, ... | GUI system development resources? | [
"",
"c++",
"user-interface",
"playstation-portable",
""
] |
I need to validate an integer to know if is a valid enum value.
What is the best way to do this in C#? | You got to love these folk who assume that data not only always comes from a UI, but a UI within your control!
`IsDefined` is fine for most scenarios, you could start with:
```
public static bool TryParseEnum<TEnum>(this int enumValue, out TEnum retVal)
{
retVal = default(TEnum);
bool success = Enum.IsDefined(typeo... | IMHO the post marked as the answer is incorrect.
Parameter and data validation is one of the things that was drilled into me decades ago.
**WHY**
Validation is required because essentially any integer value can be assigned to an enum without throwing an error.
I spent many days researching C# enum validation beca... | Validate Enum Values | [
"",
"c#",
"validation",
"enums",
""
] |
OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up.
I'd like to write a teeny app that has nothing but a task... | **for C# 3.5**
without notifyicon therefore you will need to terminate this application in task manager manually
```
using System;
using System.Drawing;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Timer timer = new Timer();
// timer.Interval = 4 minutes
tim... | The "correct" way to do this is to respond to the WM\_SYSCOMMAND message. In C# this looks something like this:
```
protected override void WndProc(ref Message m)
{
// Abort screensaver and monitor power-down
const int WM_SYSCOMMAND = 0x0112;
const int SC_MONITOR_POWER = 0xF170;
const int SC_SCREENSAVE... | Wiggling the mouse | [
"",
"c#",
"winapi",
"mouse",
""
] |
I am currently working on a project and my goal is to locate text in an image. OCR'ing the text is not my intention as of yet. I want to basically obtain the bounds of text within an image. I am using the AForge.Net imaging component for manipulation. Any assistance in some sense or another?
Update 2/5/09:
I've since ... | This is an active area of research. There are literally oodles of academic papers on the subject. It's going to be difficult to give you assistance especially w/o more deatails. Are you looking for specific types of text? Fonts? English-only? Are you familiar with the academic literature?
"Text detection" is a standar... | recognizing text inside an image is indeed a hot topic for researchers in that field, but only begun to grow out of control when [captcha's](http://en.wikipedia.org/wiki/Captcha) became the "norm" in terms of defense against spam bots. Why use captcha's as protection? well because it is/was very hard to locate (and rea... | Locating Text within image | [
"",
"c#",
"image",
"image-processing",
"artificial-intelligence",
""
] |
What do I need to look at to see whether I'm on Windows or Unix, etc.? | ```
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
```
The output of [`platform.system()`](https://docs.python.org/library/platform.html#platform.system) is as follows:
* Linux: `Linux`
* Mac: `Darwin`
* Windows: `Windows`
See: [`pla... | Here are the system results for [Windows Vista](https://en.wikipedia.org/wiki/Windows_Vista)!
```
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'
```
And for Windows 10:
```
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system... | How to identify which OS Python is running on | [
"",
"python",
"operating-system",
"cross-platform",
"platform-agnostic",
""
] |
How do I delimit a Javascript data-bound string parameter in an anchor `OnClick` event?
* I have an anchor tag in an ASP.NET Repeater control.
* The `OnClick` event of the anchor contains a call to a Javascript function.
* The Javascript function takes a string for its input parameter.
* The string parameter is popula... | I had recently similar problem and the only way to solve it was to use plain old HTML codes for single (`'`) and double quotes (`"`).
Source code was total mess of course but it worked.
Try
```
<a id="aShowHide" onclick='ToggleDisplay("<%# DataBinder.Eval(Container.DataItem, "JobCode") %>");'>Show/Hi... | ```
onclick='javascript:ToggleDisplay("<%# DataBinder.Eval(Container.DataItem, "JobCode")%> "); '
```
Use like above. | Triple Quotes? How do I delimit a databound Javascript string parameter in ASP.NET? | [
"",
"asp.net",
"javascript",
"anchor",
"quotes",
""
] |
How can I do this fast?
Sure I can do this:
```
static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if (a1.Length != a2.Length)
return false;
for (int i=0; i<a1.Length; i++)
if (a1[i]!=a2[i])
return false;
return true;
}
```
But I'm looking for either a [BCL](https://en.wik... | Edit: modern fast way is to use `a1.SequenceEquals(a2)`
User *gil* suggested unsafe code which spawned this solution:
```
// Copyright (c) 2008-2013 Hafthor Stefansson
// Distributed under the MIT/X11 software license
// Ref: http://www.opensource.org/licenses/mit-license.php.
static unsafe bool UnsafeCompare(byte[] ... | You can use [Enumerable.SequenceEqual](http://msdn.microsoft.com/en-us/library/bb348567.aspx) method.
```
using System;
using System.Linq;
...
var a1 = new int[] { 1, 2, 3};
var a2 = new int[] { 1, 2, 3};
var a3 = new int[] { 1, 2, 4};
var x = a1.SequenceEqual(a2); // true
var y = a1.SequenceEqual(a3); // false
```
I... | Comparing two byte arrays in .NET | [
"",
"c#",
".net",
"arrays",
"performance",
"j#",
""
] |
In Django's template language, you can use `{% url [viewname] [args] %}` to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?
What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). ... | If you need to use something similar to the `{% url %}` template tag in your code, Django provides the `django.core.urlresolvers.reverse()`. The `reverse` function has the following signature:
```
reverse(viewname, urlconf=None, args=None, kwargs=None)
```
<https://docs.djangoproject.com/en/dev/ref/urlresolvers/>
At... | I'm using two different approaches in my `models.py`. The first is the `permalink` decorator:
```
from django.db.models import permalink
def get_absolute_url(self):
"""Construct the absolute URL for this Item."""
return ('project.app.views.view_name', [str(self.id)])
get_absolute_url = permalink(get_absolute... | How to generate urls in django | [
"",
"python",
"django",
"url",
"django-urls",
""
] |
When I'm joining three or more tables together by a common column, I'd write my query like this:
```
SELECT *
FROM a, b, c
WHERE a.id = b.id
AND b.id = c.id
```
a colleague recently asked my why I didn't do explicit *Join Transitive Closure* in my queries like this:
```
SELECT *
FROM a, b, c
WHERE a.id = b.... | You don't need to do this in todays database engines, but there was a time when things like that would give the query optimizer more hints as to possible index paths and thus to speedier results.
These days that entire syntax is going out anyway. | This is filthy, evil legacy syntax. You write this as
> ```
> Select
> * -- Oh, and don't ever use *, either
> From
> A
> Inner Join B On A.ID = B.ID
> Inner Join C On B.ID = C.ID
> ``` | What are the advantages of explicit Join Transitive Closure in SQL? | [
"",
"sql",
""
] |
Should the folders in a solution match the namespace?
In one of my teams projects, we have a class library that has many sub-folders in the project.
Project Name and Namespace: `MyCompany.Project.Section`.
Within this project, there are several folders that match the namespace section:
* Folder `Vehicles` has class... | Also, note that if you use the built-in templates to add classes to a folder, it will by default be put in a namespace that reflects the folder hierarchy.
The classes will be easier to find and that alone should be reasons good enough.
The rules we follow are:
* Project/assembly name is the same as the root namespac... | No.
I've tried both methods on small and large projects, both with single (me) and a team of developers.
I found the simplest and most productive route was to have a single namespace per project and all classes go into that namespace. You are then free to put the class files into whatever project folders you want. Th... | Should the folders in a solution match the namespace? | [
"",
"c#",
".net",
"namespaces",
""
] |
What are the pros and cons of using table aliases in SQL? I personally try to avoid them, as I think they make the code less readable (especially when reading through large where/and statements), but I'd be interested in hearing any counter-points to this. When is it generally a good idea to use table aliases, and do y... | Table aliases are a necessary evil when dealing with highly normalized schemas. For example, and I'm not the architect on this DB so bear with me, it can take 7 joins in order to get a clean and complete record back which includes a person's name, address, phone number and company affiliation.
Rather than the somewhat... | Well, there are some cases you *must* use them, like when you need to join to the same table twice in one query.
It also depends on wether you have unique column names across tables. In our legacy database we have 3-letter prefixes for all columns, stemming from an abbreviated form from the table, simply because one a... | SQL Table Aliases - Good or Bad? | [
"",
"sql",
"alias",
""
] |
I had used Server Explorer and related tools for graphical database development with Microsoft SQL Server in some of my learning projects - and it was a great experience. However, in my work I deal with Oracle DB and SQLite and my hobby projects use MySQL (because they are hosted on Linux).
Is there a way to leverage ... | Here is instructions on how to connect to your MySQL database from Visual Studio:
> To make the connection in server
> explorer you need to do the following:
>
> * first of all you need to install the MyODBC connector 3.51 (or latest) on
> the development machine (NB. you can
> find this at
> <http://www.mysql.c... | I found this during my research on Sqlite. I haven't had the chance to use it though. Let us know if this works for you.
<http://sqlite.phxsoftware.com/>
> **System.Data.SQLite** System.Data.SQLite is the original
> SQLite database engine and a complete
> ADO.NET 2.0 provider all rolled into a
> single mixed mode ass... | Does Visual Studio Server Explorer support custom database providers? | [
"",
"c#",
"mysql",
"visual-studio",
"oracle",
"sqlite",
""
] |
I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.
On OSX, I can open a window in the finder with
```
os.system('open "%s"' % foldername)
```
and on Windows with
```
os.startfile(foldername)
```
What about unix/linux? Is there a sta... | ```
os.system('xdg-open "%s"' % foldername)
```
`xdg-open` can be used for files/urls also | this would probably have to be done manually, or have as a config item since there are many file managers that users may want to use. Providing a way for command options as well.
There might be an function that launches the defaults for kde or gnome in their respective toolkits but I haven't had reason to look for the... | Standard way to open a folder window in linux? | [
"",
"python",
"linux",
"cross-platform",
"desktop",
""
] |
I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.
The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows `.bat` file to download the actual MP3 file. I w... | Use [`urllib.request.urlopen()`](https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen):
```
import urllib.request
with urllib.request.urlopen('http://www.example.com/') as f:
html = f.read().decode('utf-8')
```
This is the most basic way to use the library, minus any error handling. You ca... | One more, using [`urlretrieve`](https://docs.python.org/3/library/urllib.request.html#module-urllib.request):
```
import urllib.request
urllib.request.urlretrieve("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
```
(for Python 2 use `import urllib` and `urllib.urlretrieve`) | How to download a file over HTTP? | [
"",
"python",
"http",
"urllib",
""
] |
How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.
The client that uses the component isn't required to load all the library script files (and ... | You may create a script element dynamically, using [Prototypes](http://www.prototypejs.org/):
```
new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});
```
The problem here is that we do not know *when* the external script file is fully loaded.
We often want our dependant code on the very nex... | There is no import / include / require in javascript, but there are two main ways to achieve what you want:
1 - You can load it with an AJAX call then use eval.
This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs an... | Dynamically load a JavaScript file | [
"",
"javascript",
"file",
"import",
"include",
""
] |
VC++ makes functions which are implemented within the class declaration inline functions.
If I declare a class `Foo` as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions?
```
class Foo
{
int* p;
public:
Foo() { p = new char[0x00100000]; }
~Foo() { delete [] p; }
};
{
Foo f;
(f);
... | Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the "inline" keyword.
In both cases it's a hint to the compiler. An "inline" function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other ... | The short answer is yes. Any function can be declared inline, and putting the function body in the class definition is one way of doing that. You could also have done:
```
class Foo
{
int* p;
public:
Foo();
~Foo();
};
inline Foo::Foo()
{
p = new char[0x00100000];
}
inline Foo::~Foo()
{
delet... | In C++ can constructor and destructor be inline functions? | [
"",
"c++",
"constructor",
"destructor",
""
] |
If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the **fastest** way to convert that absolute path back into a relative web path? | Perhaps this might work:
```
String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
```
*I'm using c# but could be adapted to vb.* | Wouldn't it be nice to have **Server.RelativePath(path)**?
well, you just need to extend it ;-)
```
public static class ExtensionMethods
{
public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)
{
return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"]... | Absolute path back to web-relative path | [
"",
"c#",
"asp.net",
".net",
"path",
"mappath",
""
] |
If I have data like this:
| Key | Name |
| --- | --- |
| 1 | Dan |
| 2 | Tom |
| 3 | Jon |
| 4 | Tom |
| 5 | Sam |
| 6 | Dan |
What is the SQL query to bring back the records where `Name` is repeated 2 or more times?
So the result I would want is
| Tom |
| --- |
| Dan | | Couldn't be simpler...
```
Select Name, Count(Name) As Count
From Table
Group By Name
Having Count(Name) > 1
Order By Count(Name) Desc
```
This could also be extended to delete duplicates:
```
Delete From Table
Where Key In (
Select Max(Key)
From Table
Group By Name
Havin... | ```
select name from table group by name having count(name) > 1
``` | SQL query, count and group by | [
"",
"sql",
""
] |
I'd like some sorthand for this:
```
Map rowToMap(row) {
def rowMap = [:];
row.columns.each{ rowMap[it.name] = it.val }
return rowMap;
}
```
given the way the GDK stuff is, I'd expect to be able to do something like:
```
Map rowToMap(row) {
row.columns.collectMap{ [it.name,it.val] }
}
```
but I have... | I've recently came across the need to do exactly that: converting a list into a map. This question was posted before Groovy version 1.7.9 came out, so the method [`collectEntries`](http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#collectEntries(java.lang.Iterable,%20groo... | Check out "inject". Real functional programming wonks call it "fold".
```
columns.inject([:]) { memo, entry ->
memo[entry.name] = entry.val
return memo
}
```
And, while you're at it, you probably want to define methods as Categories instead of right on the metaClass. That way, you can define it once for all C... | shortcut for creating a Map from a List in groovy? | [
"",
"java",
"collections",
"groovy",
"expandometaclass",
""
] |
(assume php5) consider
```
<?php
$foo = 'some words';
//case 1
print "these are $foo";
//case 2
print "these are {$foo}";
//case 3
print 'these are ' . $foo;
?>
```
Is there much of a difference between 1 and 2?
If not, what about between 1/2 and 3? | Well, as with all "What might be faster in real life" questions, you can't beat a real life test.
```
function timeFunc($function, $runs)
{
$times = array();
for ($i = 0; $i < $runs; $i++)
{
$time = microtime();
call_user_func($function);
$times[$i] = microtime() - $time;
}
return array_sum($ti... | The performance difference has been [irrelevant](http://nikic.github.com/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html) since at least January 2012, and likely earlier:
```
Single quotes: 0.061846971511841 seconds
Double quotes: 0.061599016189575 seconds
```
Earlier versions of PHP may have had a diff... | Speed difference in using inline strings vs concatenation in php5? | [
"",
"php",
"optimization",
"performance",
""
] |
I've seen it mentioned in many blogs around the net, but I believe it shoud be discussed here.
What can we do when we have an MVC framework (I am interested in ZEND) in PHP but our host does not provide mod\_rewrite?
Are there any "short-cuts"? Can we transfer control in any way (so that a mapping may occur between pag... | Zend framework should work without `mod_rewrite`. If you can live with your URL:s looking more like "/path/to/app/index.php/controller/action". If you had mod\_rewrite you could do away with the "index.php" bit, but it should work with too.
It's all a matter of setting up the routes to accept the index.php part. | OK my verdict :-): I have used successfully zend without mod\_rewrite and it's as you've all said site/index.php/controller/action. I knew that before posting this. I've also found out around the net a technique that "pushes" 404 pages to index.php therefore what is not a resource (eg. CSS, image, etc) get there, with ... | php Zend / MVC without mod_rewrite | [
"",
"php",
"model-view-controller",
"zend-framework",
""
] |
There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this:
```
function Vector(x, y, x) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); }
```
and closure base... | Assigning functions to the prototype is better (for public methods) because all instances of the class will share the same copy of the method. If you assign the function inside the constructor as in the second example, every time you create a new instance, the constructor creates a new copy of the length function and a... | There is also the object literal approach to the prototype:
```
var Vector = function(){};
Vector.prototype = {
init:function(x,y,z) {
this.x = x;
this.y = y;
this.z = z;
},
length:function() {
return Math.sqrt(x * x + ...);
}
};
var v1 = new Vector();
v1.init(1,2,3);
``` | What style do you use for creating a "class"? | [
"",
"javascript",
""
] |
Does C# have built-in support for parsing strings of page numbers? By page numbers, I mean the format you might enter into a print dialog that's a mixture of comma and dash-delimited.
Something like this:
```
1,3,5-10,12
```
What would be really nice is a solution that gave me back some kind of list of all page numb... | Should be simple:
```
foreach( string s in "1,3,5-10,12".Split(',') )
{
// try and get the number
int num;
if( int.TryParse( s, out num ) )
{
yield return num;
continue; // skip the rest
}
// otherwise we might have a range
// split on the range delimiter
string[] subs... | It doesn't have a built-in way to do this, but it would be trivial to do using String.Split.
Simply split on ',' then you have a series of strings that represent either page numbers or ranges. Iterate over that series and do a String.Split of '-'. If there isn't a result, it's a plain page number, so stick it in your ... | Does C# have built-in support for parsing page-number strings? | [
"",
"c#",
"parsing",
""
] |
I've used jdom in the past, and have looked briefly at XOM and `DOM4j`. Each seems to provide essentially the same thing, as they each provide a simplified wrapper over the (very obtuse) standard W3C DOM APIs.
I know that JDOM went through some effort to develop a JSR and standardization process at one point, but as f... | I like [XOM](http://www.xom.nu/), because I like the way Elliotte Rusty Harold thinks. Of the ones you mention I belive it's the one that strays away from the DOM standard API:s the most, but I consider that a benefit.
I once implemented a DOM library for Cocoa, and XOM was my inspiration.
I've worked with JDOM as we... | While [dom4j](http://www.dom4j.org/dom4j-1.6.1/guide.html) is an old player, we have been using it for a while and haven't regret it yet. Strong features: simplicity, xpath support and others.
Weak sides: yet to support java 5.0, but version 2.0 has been finally announced. | Which Java DOM Wrapper is the Best or Most Popular? | [
"",
"java",
"xml",
"dom",
""
] |
I infrequently (monthly/quarterly) generate hundreds of Crystal Reports reports using Microsoft SQL Server 2005 database views. Are those views wasting CPU cycles and RAM during all the time that I am not reading from them? Should I instead use stored procedures, temporary tables, or short-lived normal tables since I r... | For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT \* FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 ... | A view is a query that you run often with preset parameters. If you know you will be looking at the same data all the time you can create a view for ease of use and for data binding.
That being said, when you select from a view the view defining query is run along with the query you are running.
For example, if vwCus... | Is it okay to have a lot of database views? | [
"",
"sql",
"sql-server",
"database",
"database-design",
"crystal-reports",
""
] |
Is there a way to shutdown a computer using a built-in Java method? | Create your own function to execute an OS command through the [command line](http://www.computerhope.com/shutdown.htm)?
For the sake of an example. But know where and why you'd want to use this as others note.
```
public static void main(String arg[]) throws IOException{
Runtime runtime = Runtime.getRuntime();
... | Here's another example that could work cross-platform:
```
public static void shutdown() throws RuntimeException, IOException {
String shutdownCommand;
String operatingSystem = System.getProperty("os.name");
if ("Linux".equals(operatingSystem) || "Mac OS X".equals(operatingSystem)) {
shutdownComma... | Shutting down a computer | [
"",
"java",
"cross-platform",
"shutdown",
""
] |
What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework? | I've had good success using [Mockito](https://github.com/mockito/mockito).
When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me).
I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is de... | I am the creator of PowerMock so obviously I must recommend that! :-)
[PowerMock](http://powermock.org) extends both EasyMock and Mockito with the ability to [mock static methods](http://code.google.com/p/powermock/wiki/MockStatic), final and even private methods. The EasyMock support is complete, but the Mockito plug... | What's the best mock framework for Java? | [
"",
"java",
"unit-testing",
"mocking",
""
] |
I have a listening port on my server that I'm connecting to using a Java class and the `Socket` interface, i.e.
```
Socket mySocket = new Socket(host,port);
```
I then grab an `OutputStream`, decorate with a `PrintWriter` in autoflush mode and I'm laughing - except if the listening port closes. Then I get
```
tcp4 ... | Set a short timeout?
Does `isOutputShutdown()` not get you what you want?
You could always build a `SocketWatcher` class that spins up in its own `Thread` and repeatedly tries to write empty strings to the `Socket` until that raises a `SocketClosedException`. | The only reliable way to detect a broken connection in TCP is to write to it, which will eventually cause a 'connection reset' IOException. However due to buffering it won't happen on the first write after the disconnection,p but on a subsequent write. You can't do anything about this. | Configure a Java Socket to fail-fast on disconnect? | [
"",
"java",
"exception",
"sockets",
"networking",
""
] |
I'm a PHP developer, and I use the MVC pattern and object-oriented code. I really want to write applications for the iPhone, but to do that I need to know Cocoa, but to do that I need to know Objective-C 2.0, but to do that I need to know C, and to do that I need to know about compiled languages (versus interpreted).
... | Yes, you're really best off learning C and then Objective-C. There are some resources that will get you over the C and Objective-C language learning curve:
* Uli Kusterer's online book [Masters of the Void](http://www.zathras.de/angelweb/masters-of-the-void.htm)
* Stephen Kochan's book [Programming in Objective-C](htt... | Get [Cocoa Programming For Mac OS X](https://rads.stackoverflow.com/amzn/click/com/0321503619) by Aaron Hillegass. This should get you on your way to Cocoa programming. You can look up C-related programming as things come up.
[K&R C Programming Language](https://rads.stackoverflow.com/amzn/click/com/0131103628) is the... | Cocoa tips for PHP developers? | [
"",
"php",
"c",
"objective-c",
"cocoa",
""
] |
Is there an efficient method of converting an integer into the written numbers, for example:
```
string Written = IntegerToWritten(21);
```
would return "Twenty One".
Is there any way of doing this that doesn't involve a massive look-up table? | This should work reasonably well:
```
public static class HumanFriendlyInteger
{
static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "S... | I use this handy library called Humanizer.
<https://github.com/Humanizr/Humanizer>
It supports several cultures and converts not only numbers to words but also date and it's very simple to use.
Here's how I use it:
```
int someNumber = 543;
var culture = System.Globalization.CultureInfo("en-US");
var result = someN... | Convert integers to written numbers | [
"",
"c#",
"integer",
""
] |
> **Possible Duplicate:**
> [How do I calculate someone's age in C#?](https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c)
Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my prof... | If you were born on January 12th 1975, you would be 33 years old today.
If you were born on December 1st 1975, you would be 32 years old today.
If you read the note by the birthday field when editing your profile you'll see it says "YYYY/MM/DD", I'm sure it will try to interpret dates of other formats but it looks li... | > Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, doesn't it better to calculate the exact age?
My guess would be that... | Exact age calculation | [
"",
"c#",
""
] |
### Update: Solved, with code
[I got it working, see my answer below for the code...](https://stackoverflow.com/questions/18585/why-cant-you-bind-the-size-of-a-windows-form-to-applicationsettings#19056)
### Original Post
As Tundey pointed out in [his answer](https://stackoverflow.com/questions/18421/best-way-to-bind... | I finally came up with a Form subclass that solves this, once and for all. To use it:
1. Inherit from RestorableForm instead of Form.
2. Add a binding in (ApplicationSettings) -> (PropertyBinding) to WindowRestoreState.
3. Call Properties.Settings.Default.Save() when the window is about to close.
Now window position ... | The reason why the Form.Size property is not available in the settings binding UI is because this property is marked **DesignerSerializationVisibility.Hidden**. This means that the designer doesn't know how to serialise it, let alone generate a data binding for it. Instead the **Form.ClientSize** property is the one th... | Why can't you bind the Size of a windows form to ApplicationSettings? | [
"",
"c#",
"visual-studio",
"data-binding",
".net-2.0",
""
] |
CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.
---
> Som... | I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP:
```
function urlmtime($url) {
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
if ($path[0] == "/") {
$filename = $_SERVER['... | Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.
```
<script type="text/javascript" src="funkycode.js?v1">
```
You could use the SVN revision number to automate this [for you](https://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number) b... | How can I make the browser see CSS and Javascript changes? | [
"",
"javascript",
"css",
"http",
"caching",
""
] |
Given a string of JSON data, how can I safely turn that string into a JavaScript object?
Obviously I can do this unsafely with something like:
```
var obj = eval("(" + json + ')');
```
but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval. | [`JSON.parse(jsonString)`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser. | The jQuery method is now deprecated. Use this method instead:
```
let jsonObject = JSON.parse(jsonString);
```
---
*Original answer using deprecated jQuery functionality*:
If you're using jQuery just use:
```
jQuery.parseJSON( jsonString );
```
It's exactly what you're looking for (see the jQuery [documentation](... | Safely turning a JSON string into an object | [
"",
"javascript",
"json",
"parsing",
""
] |
I have a collection of objects in a database. Images in a photo gallery, products in a catalog, chapters in a book, etc. Each object is represented as a row. I want to be able to arbitrarily order these images, storing that ordering in the database so when I display the objects, they will be in the right order.
For ex... | Since I've mostly run into this with Django, I've found [this solution](http://www.djangosnippets.org/snippets/1053/) to be the most workable. It seems that there isn't any "right way" to do this in a relational database. | An other alternative would be (if your RDBMS supports it) to use columns of type array. While this breaks the normalization rules, it can be useful in situations like this. One database which I know about that has arrays is PostgreSQL. | Represent Ordering in a Relational Database | [
"",
"sql",
"database",
"django",
"django-models",
""
] |
I need to find a bottleneck and need to accurately as possible measure time.
Is the following code snippet the best way to measure the performance?
```
DateTime startTime = DateTime.Now;
// Some execution process
DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);
``` | No, it's not. Use the [Stopwatch](http://msdn2.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) (in `System.Diagnostics`)
```
Stopwatch sw = Stopwatch.StartNew();
PerformWork();
sw.Stop();
Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);
```
Stopwatch automatically checks for the e... | If you want something quick and dirty I would suggest using Stopwatch instead for a greater degree of precision.
```
Stopwatch sw = new Stopwatch();
sw.Start();
// Do Work
sw.Stop();
Console.WriteLine("Elapsed time: {0}", sw.Elapsed.TotalMilliseconds);
```
Alternatively, if you need something a little more sophistic... | Is DateTime.Now the best way to measure a function's performance? | [
"",
"c#",
".net",
"performance",
"datetime",
"timer",
""
] |
I am using SourceForge for some Open Source projects and I want to automate the deployment of releases to the SourceForge File Release System. I use Maven for my builds and the standard SFTP deployment mechanism doesn't seem to work unless you do some manual preparation work. I have come across some old postings on oth... | I'm not able to test this to confirm, but I believe it is possible without writing any plugins.
You can [deploy to SourceForge using SCP](http://sourceforge.net/apps/trac/sourceforge/wiki/SCP), and the maven-deploy-plugin can be configured to [use SCP](http://maven.apache.org/plugins/maven-deploy-plugin/examples/deplo... | I have uploaded an example to sourceforge.net at: <http://sf-mvn-plugins.sourceforge.net/example-1jar-thinlet/>
You can check out it via svn - so you can see how to use plugins for upload and download of and to sourceforge.net file system area and web site.
The main points to upload are to use sftp:
Add this similar... | How can I deploy artifacts from a Maven build to the SourceForge File Release System? | [
"",
"java",
"maven-2",
"sourceforge",
""
] |
How can I check `file permissions`, without having to run operating system specific command via `passthru()` or `exec()`? | Use [fileperms()](http://php.net/fileperms) function
```
clearstatcache();
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
``` | You can use the [is\_readable()](http://www.php.net/manual/en/function.is-readable.php), [is\_executable()](http://www.php.net/manual/en/function.is-executable.php) etc.. commands. | Check file permissions | [
"",
"php",
"file-permissions",
""
] |
I have done Java and JSP programming in the past, but I am new to Java Server Faces and want to know if there's a set of best practices for JSF development. | Some tips:
Understand the JSF request [lifecycle](http://www.java-samples.com/showtutorial.php?tutorialid=470) and where your various pieces of code fit in it. Especially find out why your model values will not be updated if there are validation errors.
Choose a tag library and then stick with it. Take your time to de... | Consider using [facelets](https://facelets.dev.java.net/)- it greatly simplifies the worst parts of JSF development. I'm doing a CMS-based JSF project now without facelets (after doing a project with it) and it feels like my left arm is missing.... | What are the best practices for JSF? | [
"",
"java",
"jsf",
""
] |
I've developed my own delivery extension for Reporting Services 2005, to integrate this with our SaaS marketing solution.
It takes the subscription, and takes a snapshot of the report with a custom set of parameters. It then renders the report, sends an e-mail with a link and the report attached as XLS.
Everything wo... | What's at:
```
at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort)
in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48
at MyDeliveryExtension.MyDelivery.Deliver(Notification notif... | That's why you have to avoid:
```
catch (Exception ex)
{
throw ex;
}
```
As that basically cloaks your exception in a new one.
If you use:
```
catch (Exception ex)
{
throw; //note: no ex
}
```
It keeps the original exception and stack trace. | Sending e-mail from a Custom SQL Server Reporting Services Delivery Extension | [
"",
"c#",
"reporting-services",
""
] |
I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.
It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way.
What's the simplest way of do... | ```
var d = new Date();
d.setDate(d.getDate() - 1);
console.log(d);
``` | ```
day.setDate(day.getDate() -1); //will be wrong
```
this will return wrong day. under UTC -03:00, check for
```
var d = new Date(2014,9,19);
d.setDate(d.getDate()-1);// will return Oct 17
```
**Better use:**
```
var n = day.getTime();
n -= 86400000;
day = new Date(n); //works fine for everything
``` | What's the simplest way to decrement a date in Javascript by 1 day? | [
"",
"javascript",
"browser",
"date",
""
] |
I'm sure this is easy but I can't figure it out:
I have an ASP.NET page with some UpdatePanels on it. I want the page to *completely* load with some 'Please wait' text in the UpdatePanels. Then once the page is *completely loaded* I want to call a code-behind function to update the UpdatePanel.
Any ideas as to what c... | Use a timer control that will be fired after a certain number of milliseconds (for page to load). In the timer tick event refresh the update panel. | I fiddled around with the ScriptManager suggestions - which I reckon I would have eventually got working but it seems to me that the Timer idea is easier to implement and not really(!) that much of a hack?!
Here's how I got my panel updated *after* the initial page render was complete...
default.aspx
```
<%@ Pag... | ASP.NET AJAX: Firing an UpdatePanel after the page load is complete | [
"",
"asp.net",
"javascript",
"asp.net-ajax",
""
] |
I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this? | Using [regular expressions](http://en.wikipedia.org/wiki/Regular_expression) is probably the best way of validating an email address in JavaScript. [View a bunch of tests on JSFiddle](http://jsfiddle.net/ghvj4gy9/embedded/result.js) taken from [Chromium](https://cs.chromium.org/chromium/src/third_party/blink/web_tests/... | I've slightly modified [Jaymon's answer](https://stackoverflow.com/a/48800/4832311) for people who want really simple validation in the form of:
```
anystring@anystring.anystring
```
The regular expression:
```
/^\S+@\S+\.\S+$/
```
To prevent matching multiple @ signs:
```
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
```
The abo... | How can I validate an email address in JavaScript? | [
"",
"javascript",
"html",
"regex",
"email-validation",
""
] |
I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.
I was kind of hoping that this would work
```
int? val = stringVal as int?;
```
But that won't work, so the way I'm doing it now is I've written this extension method
```... | `int.TryParse` is probably a tad easier:
```
public static int? ToNullableInt(this string s)
{
int i;
if (int.TryParse(s, out i)) return i;
return null;
}
```
**Edit** @Glenn `int.TryParse` is "built into the framework". It and `int.Parse` are *the* way to parse strings to ints. | You can do this in one line, using the conditional operator and the fact that you can cast `null` to a nullable type (two lines, if you don't have a pre-existing int you can reuse for the output of `TryParse`):
Pre C#7:
```
int tempVal;
int? val = Int32.TryParse(stringVal, out tempVal) ? tempVal : (int?)null;
```
Wi... | How to parse a string into a nullable int | [
"",
"c#",
".net",
"string",
".net-3.5",
"nullable",
""
] |
In Java, there is no such thing as an unsigned byte.
Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign.
What's a good way to work around this? (Saying don't ... | When reading any single value from the array copy it into something like a short or an int and manually convert the negative number into the positive value it should be.
```
byte[] foobar = ..;
int value = foobar[10];
if (value < 0) value += 256 // Patch up the 'falsely' negative value
```
You can do a similar conver... | It is actually possible to get rid of the if statement and the addition if you do it like this.
```
byte[] foobar = ..;
int value = (foobar[10] & 0xff);
```
This way Java doesn't interpret the byte as a negative number and flip the sign bit on the integer also. | What is the best way to work around the fact that ALL Java bytes are signed? | [
"",
"java",
"byte",
"unsigned",
"signed",
""
] |
Having a heckuva time with this one, though I feel I'm missing something obvious. I have a control that inherits from `System.Web.UI.WebControls.Button`, and then implements an interface that I have set up. So think...
```
public class Button : System.Web.UI.WebControls.Button, IMyButtonInterface { ... }
```
In the c... | Longhorn213 almost has the right answer, but as as Sean Chambers and bdukes say, you should use
```
ctrl is IInterfaceToFind
```
instead of
```
ctrl.GetType() == aTypeVariable
```
The reason why is that if you use `.GetType()` you will get the true type of an object, not necessarily what it can also be cast to in i... | You can just search on the Interface. This also uses recursion if the control has child controls, i.e. the button is in a panel.
```
private List<Control> FindControlsByType(ControlCollection controls, Type typeToFind)
{
List<Control> foundList = new List<Control>();
foreach (Control ctrl in this.Page.Control... | Finding controls that use a certain interface in ASP.NET | [
"",
"c#",
"asp.net",
""
] |
```
#if SYMBOL
//code
#endif
```
what values does C# predefine for use? | To add to what Nick said, the MSDN documentation does not list any pre-defined names. It would seem that all need to come from `#define` and `/define`.
[#if on MSDN](http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx) | Depends on what /define compiler options you use. `Visual Studio` puts the `DEBUG` symbol in there for you via the project settings, but you could create any ones that you want. | What Predefined #if symbos does c# have? | [
"",
"c#",
""
] |
SQL Experts,
Is there an efficient way to group runs of data together using SQL?
Or is it going to be more efficient to process the data in code.
For example if I have the following data:
```
ID|Name
01|Harry Johns
02|Adam Taylor
03|John Smith
04|John Smith
05|Bill Manning
06|John Smith
```
I need to display this... | Try this:
```
select n.name,
(select count(*)
from myTable n1
where n1.name = n.name and n1.id >= n.id and (n1.id <=
(
select isnull(min(nn.id), (select max(id) + 1 from myTable))
from myTable nn
where nn.id > n.id and nn.name <> n.name
)
))
from myTable n
w... | I hate cursors with a passion... but here's a dodgy cursor version...
```
Declare @NewName Varchar(50)
Declare @OldName Varchar(50)
Declare @CountNum int
Set @CountNum = 0
DECLARE nameCursor CURSOR FOR
SELECT Name
FROM NameTest
OPEN nameCursor
FETCH NEXT FROM nameCursor INTO @NewName
WHILE @@FETCH_STATUS = 0
... | Grouping runs of data | [
"",
"sql",
""
] |
I have a simple webform that will allow unauthenticated users to input their information, including name. I gave the name field a limit of 50 characters to coincide with my database table where the field is `varchar(50)`, but then I started to wonder.
Is it more appropriate to use something like the `Text` column type... | [UK Government Data Standards Catalogue](http://webarchive.nationalarchives.gov.uk/20100407120701/http://cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards.aspx) suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name. | I know I'm late on this one, but I'll add this comment anyway, as others may well come here in the future with similar questions.
Beware of tweaking column sizes dependent on locale. For a start, it sets you up for a maintenance nightmare, leaving aside the fact that people migrate, and take their names with them.
Fo... | What is a reasonable length limit on person "Name" fields? | [
"",
"html",
"sql",
"sql-server",
"textbox",
"limit",
""
] |
Within c#, I need to be able to
* Connect to a remote system, specifying username/password as appropriate
* List the members of a localgroup on that system
* Fetch the results back to the executing computer
So for example I would connect to \SOMESYSTEM with appropriate creds, and fetch back a list of local administra... | This should be easy to do using WMI. Here you have a pointer to some docs:
[WMI Documentation for Win32\_UserAccount](http://msdn.microsoft.com/en-us/library/aa394507.aspx)
Even if you have no previous experience with WMI, it should be quite easy to turn that VB Script code at the bottom of the page into some .NET co... | davidg was on the right track, and I am crediting him with the answer.
But the WMI query necessary was a little less than straightfoward, since I needed not just a list of users for the whole machine, but the subset of users *and groups*, whether local or domain, that were members of the local Administrators group. Fo... | Enumerate Windows user group members on remote system using c# | [
"",
"c#",
"windows",
"user-management",
"usergroups",
""
] |
Here is my code, which takes two version identifiers in the form "1, 5, 0, 4" or "1.5.0.4" and determines which is the newer version.
Suggestions or improvements, please!
```
/// <summary>
/// Compares two specified version strings and returns an integer that
/// indicates their relationship to one anoth... | The [System.Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) class does not support versions with commas in it, so the solution presented by [Darren Kopp](https://stackoverflow.com/questions/30494#30510) is not sufficient.
Here is a version that is as simple as possible (but no simpler).
It uses ... | Use the [Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) class.
```
Version a = new Version("1.0.0.0");
Version b = new Version("2.0.0.0");
Console.WriteLine(string.Format("Newer: {0}", (a > b) ? "a" : "b"));
// prints b
``` | Compare Version Identifiers | [
"",
"c#",
".net",
"compare",
"versions",
""
] |
Has anyone got a working solution without some Java/COM-bridge? E.g. process the Email as a file (.msg) rather than locating the data that is referenced in the Clipboard? | Maybe this is a solution for your problem:
<http://sourceforge.net/projects/javaoutlookdd/>
It allows to handle outlook items like File objects during drag&drop. | I did make some headway on this sort of thing a few years back using [Apache POI](http://poi.apache.org) to extract the contents of an email from .msg files. I'm pretty sure they have a simple swing explorer / viewer that you can use to examine the structure within the compound document format, but I can't find it righ... | Drag and Drop an Email from MS Outlook to Eclipse RCP | [
"",
"java",
"eclipse",
"ms-office",
"integration",
"desktop",
""
] |
What is the fastest method of parsing an XML file in C#? I'm using .Net 2.0 | If you're using .Net 2 then the XmlReader and XmlDocument are about it.
If you can use .Net 3.5 then the new Linq to Xml methods are a big improvement. | I haven't benched-marked it myself, but when I've asked about it in the past I've been told that XmlDocument is supposed to be faster. I have my doubts, though, since XmlDocument would need to create a DOM while XmlReader does not. | Parsing an XML file in C# | [
"",
"c#",
"xml",
""
] |
It's about PHP but I've no doubt many of the same comments will apply to other languages.
Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop?
```
for ($i = 0; $i < 10; $i++)
{
# code...
}
foreach ($ar... | For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet
The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9;
```
for ($i = 0; $i < 10; $i++)
{
#... | @brendan:
The article you cited is seriously outdated and the information is just plain wrong. Especially the last point (use `for` instead of `foreach`) is misleading and the justification offered in the article no longer applies to modern versions of .NET.
While it's true that the `IEnumerator` uses virtual calls, ... | The difference between loops | [
"",
"php",
"loops",
""
] |
Using [PyObjC](http://pyobjc.sourceforge.net/), you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how? | Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift.
There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term.
That said, Objective-C and Swift really are not too scary...
> # ... | You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See [iPhone Applications in Python](http://www.saurik.com/id/5).
Note that this requires a jailbroken iPhone at the moment. | Can I write native iPhone apps using Python? | [
"",
"iphone",
"python",
"cocoa-touch",
""
] |
I would like to filter an array of items by using the `map()` function. Here is a code snippet:
```
var filteredItems = items.map(function(item)
{
if( ...some condition... )
{
return item;
}
});
```
The problem is that filtered out items still uses space in the array and I would like to completely... | You should use the `filter` method rather than map unless you want to mutate the items in the array, in addition to filtering.
eg.
```
var filteredItems = items.filter(function(item)
{
return ...some condition...;
});
```
[Edit: Of course you could always do `sourceArray.filter(...).map(...)` to both filter and ... | Inspired by writing this answer, I ended up later expanding and writing a blog post going over this in careful detail. I recommend [checking that out](http://code.kylebaker.io/2018/03/16/stack-overflow/) if you want to develop a deeper understanding of how to think about this problem--I try to explain it piece by piece... | Removing elements with Array.map in JavaScript | [
"",
"javascript",
"functional-programming",
"data-manipulation",
"client-side",
""
] |
I want to know what a "*virtual base class*" is and what it means.
Let me show an example:
```
class Foo
{
public:
void DoSomething() { /* ... */ }
};
class Bar : public virtual Foo
{
public:
void DoSpecific() { /* ... */ }
};
``` | Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance.
Consider the following scenario:
```
class A { public: void Foo() {} };
class B : public A {};
class C : public A {};
class D : public ... | ## About the memory layout
As a side note, the problem with the Dreaded Diamond is that the base class is present multiple times. So with regular inheritance, you believe you have:
```
A
/ \
B C
\ /
D
```
But in the memory layout, you have:
```
A A
| |
B C
\ /
D
```
This explain why when call `D::... | In C++, what is a virtual base class? | [
"",
"c++",
"virtual-inheritance",
""
] |
I'm wondering how to make a release build that includes all necessary DLL files into the .exe so the program can be run on a non-development machine without having to install the Microsoft redistributable on the target machine.
Without doing this you get the error message that the application configuration is not corr... | 1. Choose Project -> Properties
2. Select Configuration -> General
3. In the box for how you should link MFC, choose to statically link it.
4. Choose Linker -> Input. Under **Additional Dependencies**, add any libraries you need your app to statically link in. | You need to set the run-time library (Under C/C++ -> Code Generation) for ALL projects to static linkage, which correlates to the following default building configurations:
* Multithreaded Debug/Release
* Singlethreaded Debug/Release
As opposed to the "DLL" versions of those libraries.
Even if you do that, depending... | How do you pack a visual studio c++ project for release? | [
"",
"c++",
"visual-studio",
"build",
""
] |
I want to write C/C++ programs that take input from a MIDI device.
The MIDI device connects to my PC using a USB connector.
I'm looking for a (C/C++ implemented) library that I can use to read the MIDI signals from the MIDI device through the USB port.
I'm happy manipulating the MIDI data once I get it, I just don't... | [PortMidi](http://portmedia.sourceforge.net/portmidi/) is another open source cross-platform MIDI I/O library worth checking out. On the other hand, if you are working on a sysex type of app, then direct Win32 works easily enough.
Just came across another open source cross-platform framework that includes MIDI support... | Check out the open source project [LMMS](http://lmms.sourceforge.net/). It's a music studio for Linux that includes the ability to use MIDI keyboards with software instruments. If you dig around in [source files](http://lmms.sourceforge.net/wiki/index.php?title=Accessing_SVN) with 'midi' in the name, you'll probably fi... | C/C++ library for reading MIDI signals from a USB MIDI device | [
"",
"c++",
"c",
"signal-processing",
"midi",
"dev-c++",
""
] |
How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request.
This would allow people to hit a url to the type <http://www.foo.com?Image=test.jpg> and have the image display ... | This is ugly, but the best way is to look at the file and set the content type as appropriate:
```
switch ( fileExtension )
{
case "pdf": Response.ContentType = "application/pdf"; break;
case "swf": Response.ContentType = "application/x-shockwave-flash"; break;
case "gif": Response.ContentType = "image/... | This is part of a solution I use on a local intranet. Some of the variables you will have to collect yourself as I pull them from a database but you may pull them from somewhere else.
The only extra but I've got in there is a function called **getMimeType** which connects to the database and pulls back the correct min... | Displaying ad content from Respose.WriteFile()/ Response.ContentType | [
"",
"c#",
""
] |
Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++?
I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether th... | `||` and `&&` are boolean operators and the built-in ones are guaranteed to return either `true` or `false`. Nothing else.
`|`, `&` and `^` are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is... | Two main reasons. In short, consider carefully; there could be a good reason for it, but if there is be VERY explicit in your comments because it can be brittle and, as you say yourself, people aren't generally used to seeing code like this.
## Bitwise xor != Logical xor (except for 0 and 1)
Firstly, if you are opera... | Using bitwise operators for Booleans in C++ | [
"",
"c++",
"boolean",
"bitwise-operators",
""
] |
I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.
Should I do it at declaration?:
```
public class Dice
{
private int topFace = 1;
private Random myRand = new Random();
public void Roll()
{
// ......
}
}
```
or in a const... | My rules:
1. Don't initialize with the default values in declaration (`null`, `false`, `0`, `0.0`…).
2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
3. If the value of the field changes because of a constructor parameter put the initialization in t... | In C# it doesn't matter. The two code samples you give are utterly equivalent. In the first example the C# compiler (or is it the CLR?) will construct an empty constructor and initialise the variables as if they were in the constructor (there's a slight nuance to this that Jon Skeet explains in the comments below).
If ... | Initialize class fields in constructor or at declaration? | [
"",
"java",
""
] |
Is it a deliberate design decision or a problem with our current day browsers which will be rectified in the coming versions? | JavaScript does not support multi-threading because the JavaScript interpreter in the browser is a single thread (AFAIK). Even Google Chrome will not let a single web page’s JavaScript run concurrently because this would cause massive concurrency issues in existing web pages. All Chrome does is separate multiple compon... | JavaScript multi-threading (with some limitations) is here. Google implemented workers for Gears, and workers are being included with HTML5. Most browsers have already added support for this feature.
Thread-safety of data is guaranteed because all data communicated to/from the worker is serialized/copied.
For more in... | Why doesn't JavaScript support multithreading? | [
"",
"javascript",
"multithreading",
"browser",
""
] |
How do you retrieve selected text using Regex in C#?
I am looking for C# code that is equivalent to this Perl code:
```
$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = $1;}
``` | ```
int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)")
Match m = re.Match(s)
if(m.Success)
indexVal = int.TryParse(m.Groups[1].toString());
```
I might have the group number wrong, but you should be able to figure it out from here. | I think Patrick nailed this one -- my only suggestion is to remember that named regex groups exist, too, so you don't *have* to use array index numbers.
```
Regex.Match(s, @"Index (?<num>\d*)").Groups["num"].Value
```
I find the regex is a bit more readable this way as well, though [opinions vary](http://www.codingho... | How do you retrieve selected text using Regex in C#? | [
"",
"c#",
"regex",
"perl",
""
] |
*Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.*
I am used to create my properties in C# using a private and a public field:
```
private string title;
public string Title
{
get { return ti... | We use them all the time in Stack Overflow.
You may also be interested in a discussion of [Properties vs. Public Variables](http://blog.codinghorror.com/properties-vs-public-variables/). IMHO that's really what this is a reaction to, and for that purpose, it's great. | Yes, it does *just* save code. It's miles easier to read when you have loads of them. They're quicker to write and easier to maintain. Saving code is always a good goal.
You can set different scopes:
```
public string PropertyName { get; private set; }
```
So that the property can only be changed inside the class. T... | C# 3.0 auto-properties — useful or not? | [
"",
"c#",
".net",
"automatic-properties",
""
] |
Plug-in systems in C++ are hard because the ABI is not properly defined, and each compiler (or version thereof) follows its own rules. However, COM on Windows shows that it's possible to create a minimal plug-in system that allows programmers with different compilers to create plug-ins for a host application using a si... | Dr Dobb's Journal has an article [Building Your Own Plugin Framework: Part 1](http://www.ddj.com/cpp/204202899?cid=RSSfeed_DDJ_Cpp) which is pretty good reading on the subject. It is the start of a series of articles which covers the architecture, development, and deployment of a C/C++ cross-platform plugin framework. | You might also want to consider replacing the conventional plugin interface by a scripting interface. There are some very good bindings for several scripting languages in C/C++ that have already solved your problem. It might not be a bad idea to build on top of them. For example, have a look at [Boost.Python](http://ww... | What's safe for a C++ plug-in system? | [
"",
"c++",
"api",
"plugins",
"compiler-construction",
""
] |
I'm using the Yahoo Uploader, part of the Yahoo UI Library, on my ASP.Net website to allow users to upload files. For those unfamiliar, the uploader works by using a Flash applet to give me more control over the FileOpen dialog. I can specify a filter for file types, allow multiple files to be selected, etc. It's great... | [Here](http://swfupload.org/forum/generaldiscussion/98) is a post from the maintainer of [SWFUpload](http://swfupload.org) which explains how to load the session from an ID stored in Request.Form. I imagine the same thing would work for the Yahoo component.
Note the security disclaimers at the bottom of the post.
---... | Relying on [this blog post](http://konste.wordpress.com/2013/01/22/asp-net-accessing-any-session-data-by-session-id/), here's a function that should get you the session for any user based on the session ID, though it's not pretty:
```
public SessionStateStoreData GetSessionById(string sessionId)
{
HttpApplication ... | Can I put an ASP.Net session ID in a hidden form field? | [
"",
"c#",
"asp.net",
"session",
"yui",
""
] |
Is there a [Box Plot](http://en.wikipedia.org/wiki/Box_plot) graph, or box and whisker graph available for Reporting Services 2005? From the looks of the documentation there doesn't seem to be one out of the box; so I am wondering if there is a third party that has the graph, or a way to build my own? | There definitely isn't a Box Plot built into SSRS 2005, though it's possible that 2008 has one. SSRS 2005 does have a robust extension model. If you can implement a chart in System.Drawing/GDI+, you can make it into a [custom report item](http://msdn.microsoft.com/en-us/magazine/cc188686.aspx) for SSRS.
There are a fe... | [ZedGraph](http://sourceforge.net/project/showfiles.php?group_id=114675) is a good open source alternative. | Is there a Box Plot graph available for Reporting Services 2005? | [
"",
"sql",
"reporting-services",
"graph",
""
] |
I know the following libraries for drawing charts in an SWT/Eclipse RCP application:
* [Eclipse BIRT Chart Engine](http://www.eclipse.org/articles/article.php?file=Article-BIRTChartEngine/index.html) (Links to an article on how to use it)
* [JFreeChart](http://www.jfree.org/jfreechart/)
Which other libraries are ther... | I have not used BIRT or JGraph, however I use JFreeChart in my SWT application. I have found the best way to use JFreeChart in SWT is by making a composite an AWT frame and using the AWT functionality for JFreeChart. The way to do this is by creating a composite
```
Composite comp = new Composite(parent, SWT.NONE | SW... | SWTChart gives good results for line, scatter, bar, and area charts. The API is straight forward and there are numerous examples on the website. I went from finding it on google to viewing my data in less than an hour.
[SWTChart](http://www.swtchart.org/index.html) | Libraries for pretty charts in SWT? | [
"",
"java",
"eclipse",
"charts",
"swt",
""
] |
I have a .NET 2.0 windows forms app, which makes heavy use of the `ListView` control.
I've subclassed the `ListView` class into a templated `SortableListView<T>` class, so it can be a bit smarter about how it displays things, and sort itself.
Unfortunately this seems to break the Visual Studio Forms Designer, in both... | > when you added the listview, did you add it to the toolbox and then add it to the form?
No, I just edited `Main.Designer.cs` and changed it from `System.Windows.Forms.ListView` to `MyApp.Controls.SortableListView<Image>`
Suspecting it might have been due to the generics led me to actually finding a solution.
For e... | It happened to me because of x86 / x64 architecture.
Since Visual Studio (the development tool itself) has no x64 version, it's not possible to load x64 control into GUI designer.
The best approach for this might be tuning GUI under x86, and compile it for x64 when necessary. | "Could not find type" error loading a form in the Windows Forms Designer | [
"",
"c#",
".net",
"winforms",
"visual-studio-2008",
"visual-studio-2005",
""
] |
How do you create a static class in C++? I should be able to do something like:
```
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
```
Assuming I created the `BitParser` class. What would the `BitParser` class definition look like? | If you're looking for a way of applying the `static` keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.
But the looks of your sample, you just need to create a public static method on your `BitParser` object. Like so:
**BitParser.h**
```
class BitParser
{
public:... | Consider [Matt Price's solution](https://stackoverflow.com/questions/9321/how-do-you-create-a-static-class-in-c/9348#9348).
1. In C++, a "static class" has no meaning. The nearest thing is a class with only static methods and members.
2. Using static methods will only limit you.
What you want is, expressed in C++ sem... | How do you create a static class? | [
"",
"c++",
"class",
"oop",
"static-classes",
""
] |
I've got a group of inter-related classes that are all overridden together to create a particular implementation. I'm wondering if it is a good idea to enclose the interrelated subclasses in a namespace.
For example purposes, consider the following namespaces and classes:
```
namespace Protocol
{
public abstract cl... | I think you are perhaps worrying too much!
Does it make sense logically? Do you know where to find your code within the namespaces?
I would much rather see a codebase like the above with a small number of classes, relevant to the name with a hierarchy, than one large namespace where everything is interrelated..
Reme... | The original tags show that this post is about C# - therefore multiple inheritance is an irrelevancy - you can't multiply inherit in C#.
Maybe you should consider defining some interfaces that define what the basic contracts of a `Message` and a `Driver` are and then you may feel a little free-er to use the namespace ... | Is it a bad idea to expose inheritance hierarchy in namespace structure? | [
"",
"c#",
"oop",
"inheritance",
"naming",
"convention",
""
] |
In a C++ Windows (XP and NT, if it makes a difference) application I'm working on, I need to get the network name associated with the computer the code is executing on, so that I can convert local filenames from C:\filename.ext to \\network\_name\C$\filename.ext. How would I do this?
Alternatively, if there's a functi... | You'll want Win32's GetComputerName:
<http://msdn.microsoft.com/en-us/library/ms724295(VS.85).aspx> | There are more than one alternatives:
a. Use Win32's GetComputerName() as suggested by Stu.
Example: <http://www.techbytes.ca/techbyte97.html>
OR
b. Use the function gethostname() under Winsock. This function is cross platform and may help if your app is going to be run on other platforms besides Windows.
... | In C++/Windows how do I get the network name of the computer I'm on? | [
"",
"c++",
"windows-xp",
"networking",
"windows-nt",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.