Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
What are the ways that you use to model and retrieve hierarchical info in a database? | The definitive pieces on this subject have been written by Joe Celko, and he has worked a number of them into a book called Joe Celko's Trees and Hierarchies in SQL for Smarties.
He favours a technique called directed graphs. An introduction to his work on this subject can be found [here](http://web.archive.org/web/20... | I like the Modified Preorder Tree Traversal Algorithm. This technique makes it very easy to query the tree.
But here is a list of links about the topic which I copied from the Zend Framework (PHP) contributors webpage (posted there by Posted by Laurent Melmoux at Jun 05, 2007 15:52).
Many of the links are language ag... | SQL - How to store and navigate hierarchies? | [
"",
"sql",
"sql-server",
"oracle",
"database-design",
"hierarchy",
""
] |
What is the best full text search alternative to Microsoft SQL? (which works with MS SQL)
I'm looking for something similar to [Lucene](http://lucene.apache.org/java/docs/index.html) and [Lucene.NET](http://incubator.apache.org/lucene.net/) but without the .NET and Java requirements. I would also like to find a soluti... | Take a look at [CLucene](http://clucene.wiki.sourceforge.net/) - It's a well maintained C++ port of java Lucene. It's currently licenced under LGPL and we use it in our commercial application.
Performance is incredible, however you do have to get your head around some of the strange API conventions. | [Sphinx](http://www.sphinxsearch.com) is one of the best solutions. It's written in C++ and has amazing performance. | Best full text search alternative to MS SQL, C++ solution | [
"",
"c++",
"sql-server",
"full-text-search",
"lucene",
"lucene.net",
""
] |
My website was recently attacked by, what seemed to me as, an innocent code:
```
<?php
if ( isset( $ _GET['page'] ) ) {
include( $ _GET['page'] . ".php" );
} else {
include("home.php");
}
?>
```
There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of i... | Use a whitelist and make sure the page is in the whitelist:
```
$whitelist = array('home', 'page');
if (in_array($_GET['page'], $whitelist)) {
include($_GET['page'].'.php');
} else {
include('home.php');
}
``` | Another way to sanitize the input is to make sure that only allowed characters (no "/", ".", ":", ...) are in it. However don't use a blacklist for *bad* characters, but a whitelist for allowed characters:
```
$page = preg_replace('[^a-zA-Z0-9]', '', $page);
```
... followed by a file\_exists.
That way you can make ... | Best way to avoid code injection in PHP | [
"",
"php",
"security",
"code-injection",
""
] |
I'm getting this problem:
```
PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12
```
from this script:
```
<?php
$to = "chris.mahan@gmail.com";
$subject = "test";
$body = "this is a test";
if (mail($to, $subjec... | Try removing the IP restrictions for Relaying in the SMTP server, and opening it up to all relays. If it works when this is set, then you know that the problem has to do with the original restrictions. In this case, it may be a DNS issue, or perhaps you had the wrong IP address listed. | You are using the wrong SMTP-server. If you you are only going to send emails to your gmail-account, have a look at my answer [here](https://stackoverflow.com/questions/29988/how-to-send-email-from-a-program-without-using-a-preexisting-account#30001).
If you also need to send email to other accounts, ask you ISP for y... | php mail() not working windows 2003, IIS SMTP | [
"",
"php",
"iis",
"smtp",
""
] |
I find that getting Unicode support in my cross-platform apps a real pain in the butt.
I need strings that can go from C code, to a database, to a Java application and into a Perl module. Each of these use a different Unicode encodings (UTF8, UTF16) or some other code page. The biggest thing that I need is a cross-pla... | Have a look at this: [http://www.icu-project.org/](http://www.icu-project.org/ "International Components for Unicode") | Perl has [Encode](http://search.cpan.org/~dankogai/Encode/Encode.pm) as a standard library. It can be used to read/write any encoding you want, so that's not going to be a problem. | cross platform unicode support | [
"",
"java",
"c",
"perl",
"unicode",
"cross-platform",
""
] |
I would like to test a string containing a path to a file for existence of that file (something like the `-e` test in Perl or the `os.path.exists()` in Python) in C#. | Use:
```
File.Exists(path)
```
MSDN: <http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx>
Edit: In System.IO | [System.IO.File](http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx):
```
using System.IO;
if (File.Exists(path))
{
Console.WriteLine("file exists");
}
``` | How to find out if a file exists in C# / .NET? | [
"",
"c#",
".net",
"io",
""
] |
I want to merge two dictionaries into a new dictionary.
```
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
```
Whenever a key `k` is present in both dictionaries, only the value `y[k]` should be kept. | ## How can I merge two Python dictionaries in a single expression?
For dictionaries `x` and `y`, their shallowly-merged dictionary `z` takes values from `y`, replacing those from `x`.
* In Python 3.9.0 or greater (released 17 October 2020, [`PEP-584`](https://www.python.org/dev/peps/pep-0584/), [discussed here](https... | In your case, you can do:
```
z = dict(list(x.items()) + list(y.items()))
```
This will, as you want it, put the final dict in `z`, and make the value for key `b` be properly overridden by the second (`y`) dict's value:
```
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 10, 'c': 11}
>>> z = dict(list(x.items()) + list(y.ite... | How do I merge two dictionaries in a single expression in Python? | [
"",
"python",
"dictionary",
"merge",
""
] |
If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?
I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing.
What would you consider best practice? I'm using NUnit, ... | If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes.
Lets go with a smarter route instead; if your goal is to **avoid code and test code duplication** you might want to... | I disagree with [Jon Limjap](https://stackoverflow.com/questions/39003/nunit-how-to-test-all-classes-that-implement-a-particular-interface#39036) when he says,
> It is not a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type)... | NUnit - How to test all classes that implement a particular interface | [
"",
"c#",
".net",
"unit-testing",
"nunit",
""
] |
I am working on localization for a asp.net application that consists of several projects.
For this, there are some strings that are used in several of these projects. Naturally, I would prefer to have only one copy of the resource file in each project.
Since the resource files don't have an namespace (at least as far... | You can just create a class library project, add a resource file there, and then refer to that assembly for common resources. | I have used this solution before to share a assembley info.cs file across all projects in a solution I would presume the same would work fro a resource file.
Create a linked file to each individual project/class library. There will be only one copy and every project will have a reference to the code via a linked file ... | Referencing resource files from multiple projects in a solution | [
"",
"c#",
"localization",
"resx",
""
] |
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.
What is the best way to do this, within the following code?
```
f = open(... | I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:
```
from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove
def replace(file_path, pattern, subst):
#Create temp file
fh, abs_path = mkstemp... | The shortest way would probably be to use the [fileinput module](https://docs.python.org/3/library/fileinput.html#fileinput.input). For example, the following adds line numbers to a file, in-place:
```
import fileinput
for line in fileinput.input("test.txt", inplace=True):
print('{} {}'.format(fileinput.filelinen... | Search and replace a line in a file in Python | [
"",
"python",
"file",
""
] |
I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache.
What is the best way in c# to implement cache locking in ASP.NET? | Here's the basic pattern:
* Check the cache for the value, return if its available
* If the value is not in the cache, then implement a lock
* Inside the lock, check the cache again, you might have been blocked
* Perform the value look up and cache it
* Release the lock
In code, it looks like this:
```
private stati... | For completeness a full example would look something like this.
```
private static object ThisLock = new object();
...
object dataObject = Cache["globalData"];
if( dataObject == null )
{
lock( ThisLock )
{
dataObject = Cache["globalData"];
if( dataObject == null )
{
//Get D... | What is the best way to lock cache in asp.net? | [
"",
"c#",
".net",
"asp.net",
"caching",
""
] |
I'm working on a module for a CMS. This module is distributed as a class library DLL.
I have several utility libraries I'd like to use in this module. Is there anyway I can link these libraries statically so I won't have to distribute several DLL's (thereby distributing my utility libraries separately)?
I would like ... | You can merge your many DLLs with ILMERGE:
<http://research.microsoft.com/~mbarnett/ILMerge.aspx>
Haven't tried it myself. Hope it helps.
---
Download here:
<http://www.microsoft.com/downloads/details.aspx?familyid=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en>
**Brief Description** *(from download-page)* ... | If you don't want to use ILMerge, see this page:
<http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx>
*editor's note*: Jeffrey Richter advices to put your dlls into exe file as resources (*For each DLL file you add, display its properties and change ... | Linking statically in C# | [
"",
"c#",
"visual-studio-2008",
"linker",
""
] |
I want to create a Java application bundle for Mac without using Mac.
According to [Java Deployment Options for Mac OS X](http://developer.apple.com/documentation/Java/Conceptual/Java14Development/03-JavaDeployment/JavaDeployment.html#//apple_ref/doc/uid/TP40001885-208447-TPXREF120), I can do this by using Xcode, Jar ... | A Java application bundle on OS X is nothing more than a directory containing your .jars and a number of configuration files. The SetFile tool sets a custom HFS filesystem property on the directory to tell finder that it is an app, but giving it a ".app" extension serves the same purpose. I don't think there's anything... | One way is to generate a zip file with the App using for example Ant. In ant you can specify that the file in Contents/MacOS should have execute-permissions using something like filemode="755". | Do I need a Mac to make a Java application bundle? | [
"",
"java",
"macos",
"deployment",
""
] |
I want to assign the decimal variable "trans" to the double variable "this.Opacity".
```
decimal trans = trackBar1.Value / 5000;
this.Opacity = trans;
```
When I build the app it gives the following error:
> Cannot implicitly convert type decimal to double | An explicit cast to `double` like this isn't necessary:
```
double trans = (double) trackBar1.Value / 5000.0;
```
Identifying the constant as `5000.0` (or as `5000d`) is sufficient:
```
double trans = trackBar1.Value / 5000.0;
double trans = trackBar1.Value / 5000d;
``` | **A more generic answer for the generic question "Decimal vs Double?":**
**Decimal** is for monetary calculations to preserve precision. **Double** is for scientific calculations that do not get affected by small differences. Since Double is a type that is native to the CPU (internal representation is stored in *base ... | How to convert Decimal to Double in C#? | [
"",
"c#",
"floating-point",
"type-conversion",
"double",
"decimal",
""
] |
Given a `DateTime` representing a person's birthday, how do I calculate their age in years? | An easy to understand and simple solution.
```
// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;
```
However, this assumes you are... | This is a strange way to do it, but if you format the date to `yyyymmdd` and subtract the date of birth from the current date then drop the last 4 digits you've got the age :)
I don't know C#, but I believe this will work in any language.
```
20080814 - 19800703 = 280111
```
Drop the last 4 digits = `28`.
C# Code:
... | How do I calculate someone's age based on a DateTime type birthday? | [
"",
"c#",
".net",
"datetime",
""
] |
Given a specific `DateTime` value, how do I display relative time, like:
* `2 hours ago`
* `3 days ago`
* `a month ago` | Jeff, [your code](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/12#12) is nice but could be clearer with constants (as suggested in Code Complete).
```
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
v... | ## [jquery.timeago plugin](https://timeago.yarp.com/)
Jeff, because Stack Overflow uses jQuery extensively, I recommend the [jquery.timeago plugin](https://timeago.yarp.com/).
Benefits:
* Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.
* You can ... | Calculate relative time in C# | [
"",
"c#",
"datetime",
"time",
"datediff",
"relative-time-span",
""
] |
Code below does not run correctly and throws `InvalidOperationExcepiton`.
```
public void Foo()
{
DataContext context = new DataContext();
LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ;
context.LinqEntities.Attach(item, true);
}
``` | By default, the entities will use all fields for checking concurrency when making edits. That's what's throwing the InvalidOperationException.
This can be setting the Update Check property for all fields to Never. This must be done on all fields to attach the entity as modified. If this is done, an additional call to ... | I'm not sure what you mean by disconnected from the database.
It appears that you are trying to insert a new row into the LinqEntities table -- is that correct?
If that is the case you'll want to do
```
context.LinqEntities.InsertOnSubmit(item);
context.Submit();
``` | How can I update in Linq an entity that is disconnected from database? | [
"",
"c#",
"linq",
""
] |
Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?
Or if this is not possible, is there at least an easy way to check if it has a particular method, other than checking if an error occurs when the method is called? | **For many objects**, you can use this code, replacing 'object' with the object you're interested in:
```
object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]
```
I discovered it at [diveintopython.net](https://web.archive.org/web/20180901124519/htt... | You can use the built in `dir()` function to get a list of all the attributes a module has. Try this at the command line to see how it works.
```
>>> import moduleName
>>> dir(moduleName)
```
Also, you can use the `hasattr(module_name, "attr_name")` function to find out if a module has a specific attribute.
See the ... | Finding what methods a Python object has | [
"",
"python",
"introspection",
""
] |
So I have a Sybase stored proc that takes 1 parameter that's a comma separated list of strings and runs a query with in in an IN() clause:
```
CREATE PROCEDURE getSomething @keyList varchar(4096)
AS
SELECT * FROM mytbl WHERE name IN (@keyList)
```
How do I call my stored proc with more than 1 value in the list?
So fa... | If you're using Sybase 12.5 or earlier then you can't use functions. A workaround might be to populate a temporary table with the values and read them from there. | This is a little late, but I had this exact issue a while ago and I found a solution.
The trick is double quoting and then wrapping the whole string in quotes.
```
exec getSomething """John"",""Tom"",""Bob"",""Harry"""
```
Modify your proc to match the table entry to the string.
```
CREATE PROCEDURE getSomething @k... | How to pass a comma separated list to a stored procedure? | [
"",
"sql",
"sap-ase",
""
] |
Given a select with multiple option's in jQuery.
```
$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
.append("<option>John</option>") //Key = 32
.append("<option>Paul</option>") //Key = 423
```
How should the key be stored and retrieved?
The ID may be an OK place bu... | Like lucas said the value attribute is what you need. Using your code it would look something like this ( I added an id attribute to the select to make it fit ):
```
$select = $('<select id="mySelect"></select>');
$select.append('<option value="1">Jason</option>') //Key = 1
.append('<option value="32">John</option>... | The HTML `<option>` tag has an attribute called "value", where you can store your key.
e.g.:
```
<option value=1>Jason</option>
```
I don't know how this will play with jQuery (I don't use it), but I hope this is helpful nonetheless. | Keeping key value pairs together in HTML <select/> with jQuery? | [
"",
"javascript",
"jquery",
"html",
""
] |
I love list comprehensions in Python, because they concisely represent a transformation of a list.
However, in other languages, I frequently find myself writing something along the lines of:
```
foreach (int x in intArray)
if (x > 3) //generic condition on x
x++
//do other processing
```
This example is i... | The increment in the original `foreach` loop will not affect the contents of the array, the only way to do this remains a `for` loop:
```
for(int i = 0; i < intArray.Length; ++i)
{
if(intArray[i] > 3) ++intArray[i];
}
```
Linq is not intended to modify existing collections or sequences. It creates new sequences b... | In C# you can apply selective processing on anything that lives inside an IEnumerable like this:
```
intArray.Where(i => i > 3).ConvertAll();
DoStuff(intArray.Where(i => i 3));
```
Etc.. | Replacement for for... if array iteration | [
"",
".net",
"python",
"arrays",
"loops",
"iteration",
""
] |
Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I do... | Here's what I ended up with. I have never found another solution out there for this, so if you have something better, by all means, contribute.
First, the long array definition in the wsdl:types area:
```
<xsd:complexType name="ArrayOf_xsd_long">
<xsd:complexContent mixed="false">
<xsd:restriction base="s... | Here's a more or less copy-pasted version of a [blog post](http://www.tomergabel.com/GettingWCFAndApacheAxisToBeFriendly.aspx) I wrote on the subject.
Executive summary: You can either change the way .NET deserializes the result set (see Chris's solution above), or you can reconfigure Axis to serialize its results in ... | Why won't .NET deserialize my primitive array from a web service? | [
"",
"java",
".net",
"service",
"primitive",
""
] |
I would like to have a reference for the pros and cons of using include **files vs objects(classes)** when developing PHP applications.
I know I would benefit from having one place to go for this answer...I have a few opinions of my own but I look forward to hearing others.
**A Simple Example:**
Certain pages on my ... | These are not really opposite choices. You will have to include the checking code anyway. I read your question as procedural programming vs. OO programming.
Writing a few lines of code, or a function, and including it in your page header was how things were done in PHP3 or PHP4. It's simple, it works (that's how we di... | While the question touches on a couple of very debatable issues (OOP, User authentication) I'll skip by those and second Konrad's comment about \_\_autoload. Anyone who knows C/C++ knows how much of a pain including files can be. With autoload, a PHP5 addition, if you choose to use OOP (which I do almost exclusively) y... | PHP includes vs OOP | [
"",
"php",
"coding-style",
""
] |
I have a php server that is running my domain name. For testing purposes I am running an asp.net on a dotted quad IP. I am hoping to link them together via either PHP or some kind of DNS/`.htaccess` voodoo.
So if I go to `www.mydomain.com/test` it redirects (but keeps the url of (`www.mydomain.com/test`) in the browse... | Instead of pointing `www.yourdomain.com/test` at your test server, why not use `test.yourdomain.com`?
Assuming you have access to the DNS records for `yourdomain.com`, you should just need to create an A record mapping `test.yourdomain.com` to your test server's IP address. | It is quite possible, if I understand what you're getting at.
You have a PHP server with your domain pointing to it. You also have a separate ASP.NET server that only has an IP address associated with it, no domain.
Is there any drawback to simply pointing your domain name to your ASP.NEt box? | Redirect from domain name to a dotted quad hosted box | [
"",
"php",
"hosting",
"dns",
""
] |
Details:
* Only disable after user clicks the submit button, but before the posting back to the server
* ASP.NET Webforms (.NET 1.1)
* Prefer jQuery (if any library at all)
* Must be enabled if form reloads (i.e. credit card failed)
This isn't a necessity that I do this, but if there is a simple way to do it without ... | For all submit buttons, via JQuery, it'd be:
```
$('input[type=submit]').click(function() { this.disabled = true; });
```
Or it might be more useful to do so on form submission:
```
$('form').submit(function() {
$('input[type=submit]', this).attr("disabled","disabled");
});
```
But I think we could give a bette... | You could do something like this:
```
$('form').submit(function() {
$(this)
.find(":submit,:image") // get all the submit buttons
.attr({ disabled : 'disabled' }) // disable them
.end() // go back to this form
.submit(function() { ... | What is the best approach for (client-side) disabling of a submit button? | [
"",
"asp.net",
"javascript",
"jquery",
"webforms",
".net-1.1",
""
] |
I'm using ant to generate javadocs, but get this exception over and over - why?
I'm using JDK version **1.6.0\_06**.
```
[javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc
[javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotation... | It looks like this has been reported as a [Java bug](https://bugs.java.com/bugdatabase/view_bug?bug_id=6442982). It appears to be caused by using annotations from a 3rd party library (like JUnit) and not including the jar with that annotation in the javadoc invocation.
If that is the case, just use the -classpath opti... | I have some idea regarding this problem but this not exact solution to get.
If you give single comment line `//` before annotation and try to run the javadoc once again. This problem will solve
Eg: `sample.java` file
```
@ChannelPipeline
```
Makes changes in
```
//@ChannelPipeline
```
Try to run javadoc command o... | Why am I getting a ClassCastException when generating javadocs? | [
"",
"java",
"ant",
"javadoc",
"classcastexception",
""
] |
I am looking for good methods of manipulating HTML in PHP. For example, the problem I currently have is dealing with malformed HTML.
I am getting input that looks something like this:
```
<div>This is some <b>text
```
As you noticed, the HTML is missing closing tags. I could use regex or an XML Parser to solve this ... | PHP has [a PECL extension that gives you access to the features of HTML Tidy](http://php.net/tidy). Tidy is a pretty powerful library that should be able to take code like that and close tags in an intelligent manner.
I use it to clean up malformed XML and HTML sent to me by a classified ad system prior to import. | I've found PHP Simple HTML DOM to be the most useful and straight forward library yet. Better than PECL I would say.
I've written an article on [how to use it to scrape myspace artist tour dates](http://www.crainbandy.com/programming/using-php-and-simple-html-dom-parser-to-scrape-artist-tour-dates-off-myspace) (just a... | DOM manipulation in PHP | [
"",
"php",
"html",
"dom",
""
] |
How do you expose a LINQ query as an ASMX web service?
Usually, from the business tier, I can return a typed `DataSet` or a `DataTable` which can be serialized for transport over ASMX.
How can I do the same for a LINQ query?
Is there a way to populate a typed `DataSet` or a `DataTable` via a LINQ query?
```
pub... | As mentioned in the question, `IEnumerable` has a `CopyToDataTable` method:
```
IEnumerable<DataRow> query =
from order in orders.AsEnumerable()
where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
select order;
// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<... | To perform this query against a `DataContext` class, you'll need to do the following:
```
MyDataContext db = new MyDataContext();
IEnumerable<DataRow> query =
(from order in db.Orders.AsEnumerable()
select new
{
order.Property,
order.Property2
})
as IEnumerable<... | Filling a DataSet or a DataTable from a LINQ query result set | [
"",
"c#",
"linq",
"web-services",
".net-3.5",
""
] |
I have lots of article store in MS SQL server 2005 database in a table called Articles-
```
"Articles (ArticleID, ArticleTitle, ArticleContent)"
```
Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackov... | Something like this might work, a kind of ranking system. You would probably have to split the string in your application to build a SQL string, but I have used similar to build an effective site search.
```
Select
Top 10
ArticleID,
ArticleTitle,
ArticleContent
From
Articles
Order By
(Case When ArticleTitle = 'Article... | First of all you need to define what article similarity means.
For example you can associate some meta information with articles, like tags.
To be able to find similar articles you need to extract some features from them, for example you can build full text index.
You can take advantage of full text search capabil... | "Similar Posts" like functionality using MS SQL Server? | [
"",
"sql",
"sql-server",
"database",
""
] |
Having been a PHP developer on LAMP servers for quite a while, is there anything that I will need to take into consideration while preparing an application for *IIS* on windows. | Make sure you get the FastCGI extension for IIS 6.0 or IIS 7.0. It is the single most important thing you can have when running PHP under IIS. Also this article should get you setup:
<http://learn.iis.net/page.aspx/247/using-fastcgi-to-host-php-applications-on-iis-60/>
Everything beyond this is simple, MySQL and what... | We just rolled out PHP 5.2.6 + FastCGI on our shared hosting platform without any problems. As long as you follow the steps outlined in [the article Nick linked](https://stackoverflow.com/questions/10515/php-on-iis#10519) to then you should be just fine.
My only additional piece of advice would be to forget about usin... | What do I need to run PHP applications on IIS? | [
"",
"php",
"windows",
"iis",
"portability",
"lamp",
""
] |
Is there any way to check whether a file is locked without using a try/catch block?
Right now, the only way I know of is to just open the file and catch any `System.IO.IOException`. | No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan).
Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice.
If your code ... | When I faced with a similar problem, I finished with the following code:
```
public class FileManager
{
private string _fileName;
private int _numberOfTries;
private int _timeIntervalBetweenTries;
private FileStream GetStream(FileAccess fileAccess)
{
var tries = 0;
while (true)
... | How to check for file lock? | [
"",
"c#",
".net",
"io",
"filelock",
""
] |
I wanted some of those spiffy rounded corners for a web project that I'm currently working on.
I thought I'd try to accomplish it using javascript and not CSS in an effort to keep the requests for image files to a minimum (yes, I know that it's possible to combine all required rounded corner shapes into one image) and... | How about this?
```
var mozborderAvailable = false;
try {
if (typeof(document.body.style.MozBorderRadius) !== "undefined") {
mozborderAvailable = true;
}
} catch(err) {}
```
I tested it in Firefox 3 (true) and false in: Safari, IE7, and Opera.
(Edit: better undefined test) | Why not use `-moz-border-radius` and `-webkit-border-radius` in the stylesheet? It's valid CSS and throwing an otherwise unused attribute would hurt less than having javascript do the legwork of figuring out if it should apply it or not.
Then, in the javascript you'd just check if the browser is IE (or Opera?) - if it... | The best way of checking for -moz-border-radius support | [
"",
"javascript",
"css",
""
] |
In Java 5 and above you have the foreach loop, which works magically on anything that implements `Iterable`:
```
for (Object o : list) {
doStuff(o);
}
```
However, `Enumerable` still does not implement `Iterable`, meaning that to iterate over an `Enumeration` you must do the following:
```
for(; e.hasMoreElements(... | Enumeration hasn't been modified to support Iterable because it's an interface not a concrete class (like Vector, which was modifed to support the Collections interface).
If Enumeration was changed to support Iterable it would break a bunch of people's code. | As an easy and **clean** way of using an Enumeration with the enhanced for loop, convert to an ArrayList with java.util.Collections.list.
```
for (TableColumn col : Collections.list(columnModel.getColumns()) {
```
(javax.swing.table.TableColumnModel.getColumns returns Enumeration.)
Note, this may be very slightly le... | Why aren't Enumerations Iterable? | [
"",
"java",
"enumeration",
"iterable",
""
] |
I've had a lot of good experiences learning about web development on [w3schools.com](http://www.w3schools.com/). It's hit or miss, I know, but the PHP and CSS sections specifically have proven very useful for reference.
Anyway, I was wondering if there was a similar site for [jQuery](http://en.wikipedia.org/wiki/JQuer... | Rick Strahl and Matt Berseth's blogs both tipped me into jQuery and man am I glad they did. jQuery completely changes a) your client programming perspective, b) the grief it causes it you, and c) how much fun it can be!
<http://www.west-wind.com/weblog/>
<http://mattberseth.com/>
I used the book jQuery in Action
[ht... | A great resource for learning jQuery is: [Learning jQuery](http://www.learningjquery.com). The author, Karl Swedberg, also co-wrote the book titled... ready? Yup, *[Learning jQuery](https://rads.stackoverflow.com/amzn/click/com/1847192505)*. Remy Sharp also has great info geared towards the visual aspects of jQuery on ... | Where can I learn jQuery? Is it worth it? | [
"",
"javascript",
"jquery",
"review",
""
] |
I have tried both of :
```
ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes');
```
and also :
```
php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes"
```
in the .htaccess file.
Both methods actually **do work** but only intermittently. That is, they will w... | It turned out the issue was related to a PHP bug in 5.2.5
Setting an "admin\_flag" for include\_path caused the include path to be empty in some requests, and Plesk sets an admin\_flag in the default config for something or other. An update of PHP solved the issue.
<http://bugs.php.net/bug.php?id=43677> | Have you tried [set\_include\_path()](http://www.php.net/manual/en/function.set-include-path.php)?. As a benefit this returns false on failure, allowing you to at least catch the occurence and generate some meaningful debug data.
Additionally, you should be using the constant `PATH_SEPARATOR` as it differs between wind... | Setting include path in PHP intermittently fails | [
"",
"php",
"include-path",
""
] |
When should I include PDB files for a production release? Should I use the `Optimize code` flag and how would that affect the information I get from an exception?
If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically don... | When you want to see source filenames and line numbers in your stacktraces, generate PDBs using the pdb-only option. Optimization is separate from PDB generation, i.e. you can optimize *and* generate PDBs without a performance hit.
From [the C# Language Reference](http://msdn.microsoft.com/en-us/library/8cw0bt21(VS.80... | To answer your first question, you only need to include PDBs for a production release if you need line numbers for your exception reports.
To answer your second question, using the "Optimise" flag with PDBs means that any [stack "collapse" will be reflected in the stack trace](https://www.hanselman.com/blog/release-is... | PDB files for production app and the "Optimize code" flag | [
"",
"c#",
"visual-studio",
"build-process",
""
] |
I was trying to get my head around XAML and thought that I would try writing some code.
Trying to add a grid with 6 by 6 column definitions then add a text block into one of the grid cells. I don't seem to be able to reference the cell that I want. There is no method on the grid that I can add the text block too. Ther... | WPF makes use of a funky thing called [attached properties](http://msdn.microsoft.com/en-us/library/ms749011.aspx). So in your XAML you might write this:
```
<TextBlock Grid.Row="0" Grid.Column="0" />
```
And this will effectively move the TextBlock into cell (0,0) of your grid.
In code this looks a little strange. ... | The cell location is an attached property - the value belongs to the TextBlock rather than Grid. However, since the property itself belongs to Grid, you need to use either the property definition field or the provided static functions.
```
TextBlock tb = new TextBlock();
//
// Locate tb in the second row, third column... | How do I generate WPF controls through code | [
"",
"c#",
".net",
"wpf",
"xaml",
""
] |
I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much.
The mail created by the mailto action has the syntax:
> subject: unde... | What we used in a projet is a popup window that opens a mailto: link, it is the only way we found to compose a mail within the default mail client that works with all mail clients (at least all our clients used).
```
var addresses = "";//between the speech mark goes the receptient. Seperate addresses with a ;
var body... | You more or less only have two alternatives when sending mail via the browser..
1. make a page that takes user input, and allows them to send the mail via your web-server. You need some kind of server-side scripting for this.
2. use a mailto: link to trigger opening of the users registered mail client. This has the ob... | Can I use JavaScript to create a client side email? | [
"",
"javascript",
"email",
""
] |
First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier.
I myself have always had problems with
* naming,
* placing
So,
1. Where do you put your... | I've really come to like Maven's [Standard Directory Layout](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html "S").
One of the key ideas for me is to have two source roots - one for production code and one for test code like so:
```
MyProject/src/main/java/com/acme/Widget... | I'm a huge fan of organized sources, so I always create the following directory structure:
```
/src - for your packages & classes
/test - for unit tests
/docs - for documentation, generated and manually edited
/lib - 3rd party libraries
/etc - unrelated stuff
/bin (or /classes) - compiled classes, output of your compi... | How should I structure a Java application, where do I put my classes? | [
"",
"java",
"architecture",
""
] |
Is there any free or commercial component written in .NET (no COM interop) that will work with most twain scanners? | In my company we use [Pegasus](http://www.pegasusimaging.com). It's great. | > ### [TwainDotNet](https://github.com/tmyroadctfig/twaindotnet)
I've just wrapped up the code from Thomas Scheidegger's article ([CodeProject: .NET TWAIN image scanning](http://www.codeproject.com/KB/dotnet/twaindotnet.aspx)) into a Google code project: [http://code.google.com/p/twaindotnet/](https://github.com/tmyro... | .NET Scanning API | [
"",
"c#",
".net",
"twain",
"scanning",
""
] |
We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this:
e.g. for "Employee" Entity
**Design 1:**
```
-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- Holds the Employ... | 1. Do **not** put it all in one table with an IsCurrent discriminator attribute. This just causes problems down the line, requires surrogate keys and all sorts of other problems.
2. Design 2 does have problems with schema changes. If you change the Employees table you have to change the EmployeeHistories table and all ... | I think the key question to ask here is 'Who / What is going to be using the history'?
If it's going to be mostly for reporting / human readable history, we've implemented this scheme in the past...
Create a table called 'AuditTrail' or something that has the following fields...
```
[ID] [int] IDENTITY(1,1) NOT NULL... | Database Design for Revisions? | [
"",
"sql",
"database",
"database-design",
"versioning",
""
] |
While the C# spec does include a pre-processor and basic directives (#define, #if, etc), the language does not have the same flexible pre-processor found in languages such as C/C++. I believe the lack of such a flexible pre-processor was a design decision made by Anders Hejlsberg (although, unfortunately, I can't find ... | Consider taking a look at an aspect-oriented solution like [PostSharp](http://www.postsharp.org/), which injects code after the fact based on custom attributes. It's the opposite of a precompiler but can give you the sort of functionality you're looking for (PropertyChanged notifications etc). | > Should I build a C# pre-processor? Is there one available that does the simple things I want to do?
You can always use the C pre-processor -- C# is close enough, syntax-wise. M4 is also an option. | C# Preprocessor | [
"",
"c#",
"c-preprocessor",
""
] |
I'm having issues getting the C sockets API to work properly in C++ on z/OS.
Although I am including `sys/socket.h`, I still get compile time errors telling me that `AF_INET` is not defined.
Am I missing something obvious, or is this related to the fact that being on z/OS makes my problems much more complicated?
I d... | Keep a copy of the IBM manuals handy:
* [z/OS V1R11.0 XL C/C++ Programming Guide](http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/CBCPG1A0/CCONTENTS?DT=20090606065305)
* [z/OS V1R11.0 XL C/C++ Run-Time Library Reference](http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/EDCLB1A0/CCONTENTS?DT=200906... | I've had no trouble using the BSD sockets API in C++, in GNU/Linux. Here's the sample program I used:
```
#include <sys/socket.h>
int
main()
{
return AF_INET;
}
```
So my take on this is that z/OS is probably the complicating factor here, however, because I've never used z/OS before, much less programmed in it, ... | How to use the C socket API in C++ on z/OS | [
"",
"c++",
"c",
"sockets",
"mainframe",
"zos",
""
] |
I am looking for a (preferably) command-line tool that can reformat the C# source code on a directory tree. Ideally, I should be able to customize the formatting. Bonus points if the tool can be run on [Mono](https://en.wikipedia.org/wiki/Mono_%28software%29) (or Linux). | You could also try [NArrange](http://www.narrange.net) to reformat your code. The formatting options it supports are still pretty limited, but it can process an entire directory and is a command-line tool. Also, NArrange runs under Mono. | You could give [Artistic Style](http://astyle.sourceforge.net/) a try. It requires [Perl](https://en.wikipedia.org/wiki/Perl) to be installed though.
It's got a decent list of formatting options, and supports C and Java as well. | Is there a tool for reformatting C# code? | [
"",
"c#",
"code-formatting",
""
] |
I'm about to start a fairly Ajax heavy feature in my company's application. What I need to do is make an Ajax callback every few minutes a user has been on the page.
* I don't need to do any DOM updates before, after, or during the callbacks.
* I don't need any information from the page, just from a site cookie which ... | If you don't want to create a blank page, you could call a IHttpHandler (ashx) file:
```
public class RSSHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/xml";
string sXml = BuildXMLString(); //not showing t... | You should use ASP.Net Callbacks which were introduced in Asp.Net 2.0. Here is an article that should get you set to go:
[Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages](http://msdn.microsoft.com/en-us/library/ms178208.aspx)
Edit: Also look at this:
[ICallback & JSON Based JavaS... | ASP.NET JavaScript Callbacks Without Full PostBacks? | [
"",
"asp.net",
"javascript",
"ajax",
""
] |
I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing?
I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a "`GOTO 10`"-like command... | They are not adding a real GOTO, but extending the BREAK keyword to use static labels. Basically, it will be enhancing the ability to break out of ~~switch~~ nested if statements. Here's the concept example I found:
```
<?php
for ($i = 0; $i < 9; $i++) {
if (true) {
break blah;
}
echo "not shown";
... | I'm always astonished at how incredibly dumb the PHP designers are.
If the purpose of using GOTOs is to make breaking out of multiply nested
loops more efficient there's a better way: labelled code blocks
and break statements that can reference labels:
```
a: for (...) {
b: for (...) {
c: for (...) {
... | GOTO command in PHP? | [
"",
"php",
"language-features",
"goto",
""
] |
How can I monitor an SQL Server database for changes to a table without using triggers or modifying the structure of the database in any way? My preferred programming environment is [.NET](http://en.wikipedia.org/wiki/.NET_Framework) and C#.
I'd like to be able to support any [SQL Server 2000](http://en.wikipedia.org/... | Take a look at the CHECKSUM command:
```
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK);
```
That will return the same number each time it's run as long as the table contents haven't changed. See my post on this for more information:
[CHECKSUM](http://msdn.microsoft.com/en-us/library/aa25824... | **Unfortunately CHECKSUM does not always work properly to detect changes**.
It is only a primitive checksum and no cyclic redundancy check (CRC) calculation.
Therefore you can't use it to detect all changes, e. g. symmetrical changes result in the same CHECKSUM!
E. g. the solution with `CHECKSUM_AGG(BINARY_CHECKSUM(... | Check for changes to an SQL Server table? | [
"",
"sql",
"sql-server",
"datatable",
"rdbms",
""
] |
I am aware that in [.NET](http://en.wikipedia.org/wiki/.NET_Framework) there are three timer types (see *[Comparing the Timer Classes in the .NET Framework Class Library](http://msdn.microsoft.com/en-us/magazine/cc164015.aspx)*). I have chosen a threaded timer as the other types can drift if the main thread is busy, an... | You can use something like `Console.ReadLine()` to block the main thread, so other background threads (like timer threads) will still work. You may also use an [AutoResetEvent](https://learn.microsoft.com/en-us/dotnet/api/system.threading.autoresetevent) to block the execution, then (when you need to) you can call Set(... | Consider using a [ManualResetEvent](https://learn.microsoft.com/en-us/dotnet/api/system.threading.manualresetevent) to block the main thread at the end of its processing, and call `Reset()` on it once the timer's processing has finished. If this is something that needs to run continuously, consider moving this into a s... | Reliable timer in a console application | [
"",
"c#",
".net",
"vb.net",
"timer",
""
] |
I'm trying to wrap my head around reflection, so I decided to add plugin capability to a program that I'm writing. The only way to understand a concept is to get your fingers dirty and write the code, so I went the route of creating a simple interface library consisting of the IPlugin and IHost interfaces, a plugin imp... | I'm just guessing here because from your code it's not obvious where do you have definition of IPlugin interface but if you can't cast in your host application then you are probably having IPlugin interface in your host assembly and then at the same time in your plugin assembly. This won't work.
The easiest thing is t... | hmmm... If you are using Assembly.LoadFrom to load your assembly try changing it Assembly.LoadFile instead.
Worked for me
From here: <http://www.eggheadcafe.com/community/aspnet/2/10036776/solution-found.aspx> | How to properly cast objects created through reflection | [
"",
"c#",
".net",
"reflection",
""
] |
I'm trying to create a bookmarklet for posting del.icio.us bookmarks to a separate account.
I tested it from the command line like:
```
wget -O - --no-check-certificate \
"https://seconduser:thepassword@api.del.icio.us/v1/posts/add?url=http://seet.dk&description=test"
```
This works great.
I then wanted to create a... | Can you sniff the traffic to find what's actually being sent? Is it sending any auth data at all and it's incorrect or being presented in a form the server doesn't like, or is it never being sent by firefox at all? | @travis Looks very nice! I will sure take a look into it. I can think of several places I can use that
I never got round to sniff the traffic but found out that a php site on my own server with http-auth worked fine, so i figured it was something with delicious. I then created a php page that does a wget of the delici... | Http Auth in a Firefox 3 bookmarklet | [
"",
"javascript",
"firefox",
"delicious-api",
""
] |
I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface.
How does one go about writing 'hooks' into their code so that plugins can attach to specific events? | You could use an Observer pattern. A simple functional way to accomplish this:
```
<?php
/** Plugin system **/
$listeners = array();
/* Create an entry point for plugins */
function hook() {
global $listeners;
$num_args = func_num_args();
$args = func_get_args();
if($num_args < 2)
trigger_... | So let's say you don't want the Observer pattern because it requires that you change your class methods to handle the task of listening, and want something generic. And let's say you don't want to use `extends` inheritance because you may already be inheriting in your class from some other class. Wouldn't it be great t... | Best way to allow plugins for a PHP application | [
"",
"php",
"plugins",
"architecture",
"hook",
""
] |
I'm writing an app that will need to make use of `Timer`s, but potentially very many of them. How scalable is the `System.Threading.Timer` class? The documentation merely say it's "lightweight", but doesn't explain further. Do these timers get sucked into a single thread (or very small threadpool) that processes all th... | I say this in response to a lot of questions: Don't forget that the (managed) source code to the framework is available. You can use this tool to get it all: <http://www.codeplex.com/NetMassDownloader>
Unfortunately, in this specific case, a lot of the implementation is in native code, so you don't get to look at it..... | I think you might want to rethink your design (that is, if you have control over the design yourself). If you're using so many timers that this is actually a concern for you, there's clearly some potential for consolidation there.
Here's a good article from MSDN Magazine from a few years ago that compares the three av... | How scalable is System.Threading.Timer? | [
"",
"c#",
".net",
"multithreading",
"timer",
""
] |
For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the [Builder pattern](http://en.wikipedia.org/wiki/Builder_pattern) in *Effective Java* that is kinda the same).
Basically, all setter methods return the object itself so then you ca... | @pek
Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return **this**. If you're interested in this topic, there is a bunch of links and a simple example on [Alex Miller's Java 7 page](http://tech.puredanger.com/java7#chained). | This is called a [Fluent Interface](http://en.wikipedia.org/wiki/Fluent_interface), for reference.
Personally, I think it's a pretty neat idea, but a matter of taste really. I think [jQuery](http://en.wikipedia.org/wiki/Jquery) works this way. | Design: Java and returning self-reference in setter methods | [
"",
"java",
""
] |
I am writing a few extensions to mimic the map and reduce functions in Lisp.
```
public delegate R ReduceFunction<T,R>(T t, R previous);
public delegate void TransformFunction<T>(T t, params object[] args);
public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial)
{
var aggregate = initial... | These look very similar to extensions in Linq already:
```
//takes a function that matches the Func<T,R> delegate
listInstance.Aggregate(
startingValue,
(x, y) => /* aggregate two subsequent values */ );
//takes a function that matches the Action<T> delegate
listInstance.ForEach(
x => /* do something w... | According to this link [Functional Programming in C# 3.0: How Map/Reduce/Filter can Rock your World](http://www.25hoursaday.com/weblog/2008/06/16/FunctionalProgrammingInC30HowMapReduceFilterCanRockYourWorld.aspx) the following are the equivalent in C# under the System.Linq namespace:
* map --> [Enumerable.Select](http... | Generic Map/Reduce List Extensions in C# | [
"",
"c#",
"functional-programming",
"extension-methods",
""
] |
What would be the easiest way to separate the directory name from the file name when dealing with `SaveFileDialog.FileName` in C#? | Use:
```
System.IO.Path.GetDirectoryName(saveDialog.FileName)
```
(and the corresponding `System.IO.Path.GetFileName`). The Path class is really rather useful. | You could construct a FileInfo object. It has a Name, FullName, and DirectoryName property.
```
var file = new FileInfo(saveFileDialog.FileName);
Console.WriteLine("File is: " + file.Name);
Console.WriteLine("Directory is: " + file.DirectoryName);
``` | How to get only directory name from SaveFileDialog.FileName | [
"",
"c#",
"string",
"parsing",
""
] |
I've been using PHP & MySQL for ages and am about to start using PostgreSQL instead.
What's the preferred method?
Is it via the PDO objects or is there something better? | PDO objects are the new hotness. I'd recommend that as long as you can ensure that your target platform will always be running PHP 5.2+.
There are many other database abstraction layers that support PostgreSQL that are compatible with older versions of PHP; I'd recommend [ADODB](http://adodb.sourceforge.net/).
You sh... | Using Zend Db:
```
require_once 'Zend/Db.php';
$DB_ADAPTER = 'Pdo_Pgsql';
$DB_CONFIG = array(
'username' => 'app_db_user',
'password' => 'xxxxxxxxx',
'host' => 'localhost',
'port' => 5432,
'dbname' => 'mydb'
);
$db = Zend_Db::factory($DB_ADAPTER, $DB_CONFIG);
``` | What's the preferred way to connect to a postgresql database from PHP? | [
"",
"php",
"postgresql",
""
] |
I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines.
I tried this but it just barfs.
```
preg_match(
'^J[0-9]{7}:\s+
(.*?) #Extract the Transaction Start Date msg
\s+J[0-9]{7}:\s+Project\sname:\s+
(.*?) #... | You can use the extended syntax:
```
preg_match("/
test
/x", $foo, $bar);
``` | Yes, you can add the `/x` [Pattern Modifier](http://us.php.net/manual/en/reference.pcre.pattern.modifiers.php).
> This modifier turns on additional
> functionality of PCRE that is
> incompatible with Perl. Any backslash
> in a pattern that is followed by a
> letter that has no special meaning
> causes an error, thus r... | Passing a commented, multi-line (freespace) regex to preg_match | [
"",
"php",
"regex",
""
] |
Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to th... | This is much more concise:
```
where
datediff(day, date1, date2) = 0
``` | You pretty much have to keep the left side of your where clause clean. So, normally, you'd do something like:
```
WHERE MyDateTime >= @activityDateMidnight
AND MyDateTime < (@activityDateMidnight + 1)
```
(Some folks prefer DATEADD(d, 1, @activityDateMidnight) instead - but it's the same thing).
The TimeZone ... | What's a good way to check if two datetimes are on the same calendar day in TSQL? | [
"",
"sql",
"sql-server",
"t-sql",
"datetime",
"user-defined-functions",
""
] |
I have a `DataTable` with a `Name` column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the *order by* clause.
```
var names =
(from DataRow dr in dataTable.Rows
orderby (string)dr["Name"]
select (string)dr["Name"]).Distinct();
```
Why does the `o... | To make it more readable and maintainable, you can also split it up into multiple LINQ statements.
1. First, select your data into a new list, let's call it `x1`, do a projection if desired
2. Next, create a distinct list, from `x1` into `x2`, using whatever distinction you require
3. Finally, create an ordered list, ... | **The problem is that the Distinct
operator does not grant that it will
maintain the original order of
values.**
So your query will need to work like this
```
var names = (from DataRow dr in dataTable.Rows
select (string)dr["Name"]).Distinct().OrderBy( name => name );
``` | How do I get a distinct, ordered list of names from a DataTable using LINQ? | [
"",
"c#",
"linq",
".net-3.5",
""
] |
What's the cleanest, most effective way to validate decimal numbers in JavaScript?
Bonus points for:
1. Clarity. Solution should be clean and simple.
2. Cross-platform.
Test cases:
```
01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true... | [@Joel's answer](https://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/174921#174921) is pretty close, but it will fail in the following cases:
```
// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;
// Number literals:
IsNumeric(-1) ==... | Arrrgh! Don't listen to the regular expression answers. RegEx is icky for this, and I'm not talking just performance. It's so easy to make subtle, impossible to spot mistakes with your regular expression.
If you can't use `isNaN()` — and remember: I said, "IF" — this should work much better:
```
function IsNumeric(in... | Validate decimal numbers in JavaScript - IsNumeric() | [
"",
"javascript",
"validation",
"numbers",
""
] |
In C++, there isn't a de-facto standard logging tool. In my experience, shops roll their own. This creates a bit of a problem, however, when trying to create reusable software components. If everything in your system depends on the logging component, this makes the software less reusable, basically forcing any downstre... | Yes. But dependency injection will help in this case.
You can create an abstract logging base-class and create implementations for the logging-frameworks you want to use. Your components are just dependent on the abstract base-class. And you inject the implementations along with al their dependencies as needed. | Yes, Mendelt is right. We do exactly this in our products. Everything depends on the ILogger abstract interface, but it does not depend on anything else. Typically an executable or a high-level DLL will be the one to construct an actual implemented Logger interface and inject it. | Do C++ logging frameworks sacrifice reusability? | [
"",
"c++",
"logging",
"code-reuse",
""
] |
I have to do some JavaScript in the future, so it is time to update my toolbox. Right now I use Firefox with some addons:
* JavaScript Shell from <https://www.squarefree.com/bookmarklets/webdevel.html>
* Firefox Dom Inspector
* Firebug
* Greasemonkey
* Stylish
I plan to use [Venkman Javascript debugger](http://www.ha... | I use both Firefox and IE for Web Development and a few add-ons in each:
**Firefox:**
* [Firebug](https://addons.mozilla.org/en-US/firefox/addon/1843)
* [Web Developer Toolbar](https://addons.mozilla.org/en-US/firefox/addon/60)
**Internet Explorer:**
* [IE Developer Toolbar](http://www.microsoft.com/en-us/download/... | I sometimes use Emacs with Steve Yegge's [js2-mode](http://code.google.com/p/js2-mode/), evaluating code with [Rhino](http://www.mozilla.org/rhino/) & John Resig's [env.js](http://ejohn.org/blog/bringing-the-browser-to-the-server/) to load jQuery or Prototype in my standalone scripts.
This allows me to explore javascr... | What is in your JavaScript development toolbox? | [
"",
"javascript",
"debugging",
""
] |
I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying?
```
function loadPage(pagePath, displayElement)
{
var xmlHttp;... | I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't ins... | I would remove this line.
```
alert("Your browser does not support AJAX!")
```
Shouting at the user in a language he probably doesn't understand is worse than failure. :-) | What more is needed for Ajax than this function | [
"",
"javascript",
"ajax",
""
] |
I have a large tree of Java Objects in my Desktop Application and am trying to decide on the best way of persisting them as a file to the file system.
Some thoughts I've had were:
* **Roll my own serializer using DataOutputStream**: This would give me the greatest control of what was in the file, but at the cost of m... | [db4objects](http://www.db4o.com) might be the best choice | I would go for the your final option JavaDB (Sun's distribution of [Derby](http://db.apache.org/derby)) and use an object relational layer like [Hibernate](http://hibernate.org) or [iBatis](http://ibatis.apache.org). Using the first three aproaches means you are going to spend more time building a database engine than ... | What's the best way to persist data in a Java Desktop Application? | [
"",
"java",
"persistence",
"desktop",
"oop",
""
] |
In one of my applications, I am querying active directory to get a list of all users below a given user (using the "Direct Reports" thing). So basically, given the name of the person, it is looked up in AD, then the Direct Reports are read. But then for every direct report, the tool needs to check the direct reports of... | In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around:
```
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry();
// Push the property values from AD back to cache... | Depends on how up to date you want the information to be. If you **must have** the very latest data in your report then querying directly from AD is reasonable. And I agree that AD is quite robust, a typical dedicated AD server is actually very lightly utilised in normal day to day operations *but best to check with yo... | Caching Active Directory Data | [
"",
"c#",
"asp.net",
"active-directory",
""
] |
I have a complete XML document in a string and would like a `Document` object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)
**Solution** Thanks to [Matt McMinn](https://stackoverflow.com/users/1322/matt-mcminn), I have settled on this implementation. It has the right level of inpu... | This works for me in Java 1.5 - I stripped out specific exceptions for readability.
```
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;
public Document loadXMLFromString(String xml) throws Exception
{
Docu... | Whoa there!
There's a potentially serious problem with this code, because it ignores the character encoding specified in the `String` (which is UTF-8 by default). When you call `String.getBytes()` the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 d... | How do I load an org.w3c.dom.Document from XML in a string? | [
"",
"java",
"xml",
"document",
"w3c",
""
] |
There are two weird operators in C#:
* the [true operator](http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx)
* the [false operator](http://msdn.microsoft.com/en-us/library/6292hy1k.aspx)
If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where ... | You can use it to override the `&&` and `||` operators.
The `&&` and `||` operators can't be overridden, but if you override `|`, `&`, `true` and `false` in exactly the right way the compiler will call `|` and `&` when you write `||` and `&&`.
For example, look at this code (from <http://ayende.com/blog/1574/nhiberna... | Shog9 and Nir:
thanks for your answers. Those answers pointed me to [Steve Eichert article](http://steve.emxsoftware.com/NET/Overloading+the++and++operators) and it pointed me to [msdn](http://msdn.microsoft.com/en-us/library/aa691312.aspx):
> The operation x && y is evaluated as T.false(x) ? x : T.&(x, y), where T.fa... | What's the false operator in C# good for? | [
"",
"c#",
".net",
"syntax",
""
] |
Is it true that the only way to handle default function arguments is through function overloading?
For example, in PHP I can do this:
```
function foo($x, $y=0)
{
}
```
Would the best way to handle it in C# be this?
```
void foo(int x)
{
foo(x, 0);
}
void foo(int x, int y)
{
}
```
***[Example lifted from here](... | Yes, that'd be best~~, except you'd omit the `$`s on the parameter names~~, as others have pointed out. For those interested in the rationale behind the lack of default parameter values, see @Giovanni Galbo's explanation. | Just to satisfy some curiosity:
From [Why doesn't C# support default parameters?](http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx):
> In languages such as C++, a default value can be included as part of the method declaration:
>
> void Process(Employee employee, bool bonus = false)
>
> This method can b... | Is overloading the only way to have default function arguments in C#? | [
"",
"c#",
"overloading",
""
] |
I have a custom validation function in JavaScript in a user control on a .Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due.
I've placed the validator code in the `ascx` file, and I have also tried using `Page.ClientScript.RegisterClientScriptBlock()` and in both cases the v... | Try changing the argument names to `sender` and `args`. And, after you have it working, switch the call over to `ScriptManager.RegisterClientScriptBlock`, regardless of AJAX use. | When you're using .Net 2.0 and Ajax - you should use:
```
ScriptManager.RegisterClientScriptBlock
```
It will work better in Ajax environments then the old Page.ClientScript version | ASP.Net Custom Client-Side Validation | [
"",
"asp.net",
"javascript",
"validation",
""
] |
Is it possible to configure [xampp](http://www.apachefriends.org/en/xampp.html) to serve up a file outside of the `htdocs` directory?
For instance, say I have a file located as follows:
`C:\projects\transitCalculator\trunk\TransitCalculator.php`
and my [xampp](http://www.apachefriends.org/en/xampp.html) files are no... | Ok, per [pix0r](https://stackoverflow.com/questions/1408/#2471)'s, [Sparks](https://stackoverflow.com/questions/1408/#1413)' and [Dave](https://stackoverflow.com/questions/1408/#1414)'s answers it looks like there are three ways to do this:
---
## [Virtual Hosts](https://stackoverflow.com/questions/1408/#2471)
1. Op... | You can relocate it by editing the **DocumentRoot** setting in XAMPP\apache\conf\httpd.conf.
It should currently be:
> C:/xampp/htdocs
Change it to:
> C:/projects/transitCalculator/trunk | Make XAMPP / Apache serve file outside of htdocs folder | [
"",
"php",
"apache",
"xampp",
"server-configuration",
""
] |
What techniques can be applied effectively to improve the performance of SQL queries? Are there any general rules that apply? | * Use primary keys
* Avoid select \*
* Be as specific as you can when building your conditional statements
* De-normalisation can often be more efficient
* Table variables and temporary tables (where available) will often be better than using a large source table
* Partitioned views
* Employ indices and constraints | Learn what's really going on under the hood - you should be able to understand the following concepts in detail:
* Indexes (not just what they are but actually how they work).
* Clustered indexes vs heap allocated tables.
* Text and binary lookups and when they can be in-lined.
* [Fill factor](https://stackoverflow.co... | What generic techniques can be applied to optimize SQL queries? | [
"",
"sql",
"performance",
""
] |
What is the SQL query to select all of the MSSQL Server's logins?
Thank you. More than one of you had the answer I was looking for:
```
SELECT * FROM syslogins
``` | Is this what you're after?
```
select * from master.syslogins
``` | On SQL Azure as of 2012;
logins:
```
--connecct to master
--logins
SELECT * from sys.sql_logins
--users
SELECT * from sys.sysusers
```
and users on a specific database:
```
--connect to database
SELECT * from sys.sysusers
```
Also note that 'users' on Azure SQL now (2022-11-17) have mo... | SQL Query for Logins | [
"",
"sql",
"sql-server",
""
] |
I have a JavaScript method that I need to run on one of my pages, in particular, the `onresize` event.
However, I don't see how I can set that event from my content page. I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page.
Any hel... | Place the following in your content page:
```
<script type="text/javascript">
// here is a cross-browser compatible way of connecting
// handlers to events, in case you don't have one
function attachEventHandler(element, eventToHandle, eventHandler) {
if(element.attachEvent) {
element.attachEvent(eventToH... | How about use code like the following in your Content Page (C#)?
```
Page.ClientScript.RegisterStartupScript(this.GetType(), "resizeMyPage", "window.onresize=function(){ resizeMyPage();}", true);
```
Thus, you could have a `resizeMyPage` function defined somewhere in the Javascript and it would be run whenever the br... | Call onresize from ASP.NET content page | [
"",
"asp.net",
"javascript",
"master-pages",
"onresize",
""
] |
I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o? | We run DB40 .NET version in a large client/server project.
Our experiences is that you can potentially get much better performance than typical relational databases.
However, you really have to tweak your objects to get this kind of performance. For example, if you've got a list containing a lot of objects, DB4O acti... | Most native queries can and are efficiently converted into SODA queries behind the scenes so that should not make a difference. Using NQ is of course preferred as you remain in the realms of strong typed language. If you have problems getting NQ to use indexes please feel free to post your problem to the [db4o forums](... | db4o experiences? | [
"",
"java",
"db4o",
""
] |
I have a (potentially dumb) question about the C++ STL. When I make a container (vector, set, map, etc), is it allocated on the stack or on the heap? If I make a set and put 5 million strings, will I have to worry about a stack overflow? | STL classes by default allocate their internal buffers from the heap, although these classes also allow custom allocators that allow a user to specify an alternate location to allocate from - e.g. a shared memory pool. | The default allocator for STL containers uses operator new and delete, so it's whatever those route to for the type being contained. (In general, it comes from the heap unless you do something to override that.)
You will not get a stack overflow from allocating 5 million strings. Even if you made a stack based allocat... | C++ STL question: allocators | [
"",
"c++",
"stl",
""
] |
I'm working on an internal project for my company, and part of the project is to be able to parse various "Tasks" from an XML file into a collection of tasks to be ran later.
Because each type of Task has a multitude of different associated fields, I decided it would be best to represent each type of Task with a seper... | I use reflection to do this.
You can make a factory that basically expands without you having to add any extra code.
make sure you have "using System.Reflection", place the following code in your instantiation method.
```
public Task CreateTask(XmlElement elem)
{
if (elem != null)
{
try
{
... | Create a "Prototype" instanace of each class and put them in a hashtable inside the factory , with the string you expect in the XML as the key.
so CreateTask just finds the right Prototype object,
by get() ing from the hashtable.
then call LoadFromXML on it.
you have to pre-load the classes into the hashtable,
If y... | Abstract Factory Design Pattern | [
"",
"c#",
"design-patterns",
"factory",
""
] |
Searching for some sample code for converting a point in WGS84 coordinate system to a map position in Google Maps (pixel position), also supporting zoom levels.
If the codes is well commented, then it can also be in some other language.
You can also point me to a open source Java project :)
Some resources found:
[O... | [Tile utility code in Java](http://web.archive.org/web/20110809084551/http://mapki.com/wiki/Tile_utility_code_in_Java) on mapki.com (great resource for google map developers) | Here are the functions in JavaSCript ... As extracted from OpenLayers
```
function toMercator (lon, lat) {
var x = lon * 20037508.34 / 180;
var y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
y = y * 20037508.34 / 180;
return [x, y];
}
function inverseMercator (x, y) {
var lon = (x ... | Java code for WGS84 to Google map position and back | [
"",
"java",
"google-maps",
"mapping",
"wgs84",
""
] |
I am wrapping existing C++ code from a **BSD** project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses `fprintf` to print to **stderr** in order to log / report errors.
I want to redirect this to an alternative place within the same process. On **Unix** ... | You can use a similar technique on Windows, you just need to use different words for the same concepts. :) This article: <http://msdn.microsoft.com/en-us/library/ms682499.aspx> uses a win32 pipe to handle I/O from another process, you just have to do the same thing with threads within the same process. Of course, in yo... | You have to remember that what MSVCRT calls "OS handles" are not Win32 handles, but another layer of handles added just to confuse you. MSVCRT tries to emulate the Unix handle numbers where `stdin` = 0, `stdout` = 1, `stderr` = 2 and so on. Win32 handles are numbered differently and their values always happen to be a m... | Windows C++: How can I redirect stderr for calls to fprintf? | [
"",
"c++",
"windows",
"redirect",
""
] |
I often encounter the following scenario where I need to offer many different types of permissions. I primarily use ASP.NET / VB.NET with SQL Server 2000.
**Scenario**
I want to offer a dynamic permission system that can work on different parameters. Let's say that I want to give either a department or just a specifi... | I agree with John Downey.
Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.
```
"[Flags]
public enum Permission
{
VIEWUSERS = 1, // 2^0 // 0000 0001
EDITUSERS = 2, // 2^1 // 0000 0010
VIEWPRODUCTS = 4,... | The way I typically go about coding permission systems is having 6 tables.
* Users - this is pretty straight forward it is your typical users table
* Groups - this would be synonymous to your departments
* Roles - this is a table with all permissions generally also including a human readable name and a description
* U... | What is the best way to handle multiple permission types? | [
"",
"sql",
"permissions",
""
] |
I am trying to set a `javascript` `date` so that it can be submitted via `JSON` to a `.NET` type, but when attempting to do this, `jQuery` sets the `date` to a full `string`, what format does it have to be in to be converted to a `.NET` type?
```
var regDate = student.RegistrationDate.getMonth() + "/" + student.Regist... | This [MSDN article](http://msdn.microsoft.com/en-us/library/ey1cdcx8.aspx) has some example Date strings that are parse-able is that what you're looking for?
```
string dateString = "5/1/2008 8:30:52 AM";
DateTime date1 = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
``` | As travis suggests, you could simply change the parameter or class property (depending on what you are passing back) to a string, the parse it as his example.
You may also want to take a look at [this article](http://www.nikhilk.net/DateSyntaxForJSON2.aspx). It suggests that direct conversion for DateTime JSON seriali... | How can I format a javascript date to be serialized by jQuery | [
"",
"c#",
"json",
"serialization",
"date",
"castle-monorail",
""
] |
I'm trying to do this (which produces an unexpected T\_VARIABLE error):
```
public function createShipment($startZip, $endZip, $weight =
$this->getDefaultWeight()){}
```
I don't want to put a magic number in there for weight since the object I am using has a `"defaultWeight"` parameter that all new shipments get if ... | This isn't much better:
```
public function createShipment($startZip, $endZip, $weight=null){
$weight = !$weight ? $this->getDefaultWeight() : $weight;
}
// or...
public function createShipment($startZip, $endZip, $weight=null){
if ( !$weight )
$weight = $this->getDefaultWeight();
}
``` | Neat trick with Boolean OR operator:
```
public function createShipment($startZip, $endZip, $weight = 0){
$weight or $weight = $this->getDefaultWeight();
...
}
``` | Using object property as default for method property | [
"",
"php",
"parameters",
"error-handling",
""
] |
How do you express an integer as a binary number with Python literals?
I was easily able to find the answer for hex:
```
>>> 0x12AF
4783
>>> 0x100
256
```
and octal:
```
>>> 01267
695
>>> 0100
64
```
**How do you use literals to express binary in Python?**
---
***Summary of Answers***
* Python 2.5 and earlier: ... | For reference—*future* Python possibilities:
Starting with Python 2.6 you can express binary literals using the prefix **0b** or **0B**:
```
>>> 0b101111
47
```
You can also use the new **bin** function to get the binary representation of a number:
```
>>> bin(173)
'0b10101101'
```
Development version of the docu... | ```
>>> print int('01010101111',2)
687
>>> print int('11111111',2)
255
```
Another way. | How do you express binary literals in Python? | [
"",
"python",
"syntax",
"binary",
"integer",
"literals",
""
] |
In C#, if I have an inherited class with a default constructor, do I have to explicitly call the base class' constructor or will it be implicitly called?
```
class BaseClass
{
public BaseClass()
{
// ... some code
}
}
class MyClass : BaseClass
{
public MyClass() // Do I need to put ": base()" h... | You do not need to explicitly call the base constructor, it will be implicitly called.
Extend your example a little and create a Console Application and you can verify this behaviour for yourself:
```
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
... | It is implied, provided it is parameterless. This is because you **need to implement constructors that take values**, see the code below for an example:
```
public class SuperClassEmptyCtor
{
public SuperClassEmptyCtor()
{
// Default Ctor
}
}
public class SubClassA : SuperClassEmptyCtor
{
// N... | In C#, do you need to call the base constructor? | [
"",
"c#",
"inheritance",
"constructor",
""
] |
I would like to sort an array in ascending order using `C/C++`. The outcome is an array containing element indexes. Each index is corespondent to the element location in the sorted array.
**Example**
```
Input: 1, 3, 4, 9, 6
Output: 1, 2, 3, 5, 4
```
**Edit:** I am using shell sort procedure. The duplicate value in... | Since you're using C++, I would do it something like this. The `SortIntPointers` function can be any sort algorithm, the important part is that it sorts the array of pointers based on the `int` that they are pointing to. Once that is done, you can go through the array of pointers and assign their sorted index which wil... | Ok, here is my atempt in C++
```
#include <iostream>
#include <algorithm>
struct mycomparison
{
bool operator() (int* lhs, int* rhs) {return (*lhs) < (*rhs);}
};
int main(int argc, char* argv[])
{
int myarray[] = {1, 3, 6, 2, 4, 9, 5, 12, 10};
const size_t size = sizeof(myarray) / sizeof(myarray[0]);
... | How does one rank an array (sort) by value? *With a twist* | [
"",
"c++",
"c",
"arrays",
"sorting",
""
] |
Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough. | Try this:
```
StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName ();
```
Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you ca... | ```
System.getProperty("sun.java.command")
``` | $0 (Program Name) in Java? Discover main class? | [
"",
"java",
""
] |
I'm trying to find a way to list the (static) dependency requirements of a jar file, in terms of which symbols are required at run time.
I can see that the methods exported by classes can be listed using "javap", but there doesn't seem to be an opposite facility to list the 'imports'. Is it possible to do this?
This ... | You could use the [Outbound dependencies](http://depfind.sourceforge.net/Manual.html#ShowingOnlyOutboundDependencies) feature of [DependencyFinder](http://depfind.sourceforge.net/). You can do that entirely in the GUI, or in command line exporting XML. | I think you can get that information using [JDepend](http://www.clarkware.com/software/JDepend.html) | Java import/export dependencies | [
"",
"java",
"import",
"export",
""
] |
I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using *IntelliSense* or using the classes in a visua... | Override them like Michael Suggests [above](https://stackoverflow.com/questions/1528/#1533) and to prevent folks from using the overridden (sp?) methods, mark them as obsolete:
```
[Obsolete("These are not supported in this class.", true)]
public override void dontcallmeanymore()
{
}
```
If the second parm is set to... | While you cannot prevent usage of those inherited members to my knowledge, you should be able to hide them from IntelliSense using the [EditorBrowsableAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx):
```
Using System.ComponentModel;
[EditorBrowsable(EditorBrowsa... | Hiding inherited members | [
"",
"c#",
"wpf",
"silverlight",
"polymorphism",
"dependency-properties",
""
] |
I am attempting to POST against a vendor's server using PHP 5.2 with cURL. I'm reading in an XML document to post against their server and then reading in a response:
```
$request = trim(file_get_contents('test.xml'));
$curlHandle = curl_init($servletURL);
curl_setopt($curlHandle, CURLOPT_POST, TRUE);
curl_setopt($cur... | It turns out it's an encoding issue. The app apparently needs the XML in www-form-urlencoded instead of form-data so I had to change:
```
# This sets the encoding to multipart/form-data
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=>$request));
```
to
```
# This sets it to application/x-www-form-urlencode... | Not an answer, but I find the whole fopen/fread/fclose thing very dull to peruse when looking at code.
You can replace:
```
$file = 'test.xml';
$fileHandle = fopen($file, 'r');
$request = fread($fileHandle, filesize($file));
fclose($fileHandle);
$request = trim($request);
```
With:
```
$request = trim(file_get_cont... | cURL adding whitespace to post content? | [
"",
"php",
"xml",
"curl",
""
] |
Is there any way to capture the MouseDown even from the .NET 2.0 TextBox control?
I know the inherited Control class has the event, but it's not exposed in TextBox.
Is there a way to override the event handler?
I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what ... | Looks like you're right. Bummer. No MouseOver event.
One of the fallbacks that always works with .NET, though, is P/Invoke. Someone already took the time to do this for the .NET CF TextBox. I found this on CodeProject:
<http://www.codeproject.com/KB/cs/TextBox_subclassing.aspx>
Hope this helps | I know this answer is way late, but hopefully it ends up being useful for someone who finds this. Also, I didn't entirely come up with it myself. I believe I originally found most of the info on the OpenNETCF boards, but what is typed below is extracted from one of my applications.
You can get a mousedown event by imp... | Capture MouseDown event for .NET TextBox | [
"",
"c#",
".net",
"events",
"windows-mobile",
""
] |
I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your deskt... | To follow up on pauxu's answer, I'm using launch4j and NSIS on a project of mine and thought it would be helpful to show just how I'm using them. Here's what I'm doing for Windows. BTW, I'm creating .app and .dmg for Mac, but haven't figured out what to do for Linux yet.
## Project Copies of launch4j and NSIS
In my p... | In my company we use [Launch4J](http://launch4j.sourceforge.net/) to create the exe file, and [NSIS](http://nsis.sourceforge.net/) to create the installer, with SWT applications.
We have used it for years in several commercial applications and the pair works fine. | Packaging Java apps for the Windows/Linux desktop | [
"",
"java",
"windows",
"swt",
"executable",
"software-distribution",
""
] |
I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process.
Anyway, here's the problem:
Let's say you have some class which wraps or includes networked file IO op... | This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on [AOP in .NET](https://learn.microsoft.com/en-us/archive/blogs/simonince/aspect-oriented-interception). The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a sep... | Just wondering, what do you feel your method leaves to be desired? You could replace the anonymous delegate with a.. named? delegate, something like
```
public delegate void IoOperation(params string[] parameters);
public void FileDeleteOperation(params string[] fileName)
{
File.Delete(fileName[0]... | Reducing duplicate error handling code in C#? | [
"",
"c#",
"exception",
"error-handling",
""
] |
I have been working with Visual Studio (WinForm and ASP.NET applications using mostly C#) for several months now. For the most part my IDE is set up fairly standard but I have been wondering what are some suggestions in terms of plugins/settings that you find to be the most useful?
**Update**: Thanks for all the great... | **[Resharper](http://www.jetbrains.com/resharper/)** is definitely a great tool. It has a moderate learning curve but is easy to pick up for some simple things and add mastery later. It is a good price for students and kinda expensive for the rest of us. Resharper is similar to CodeRush, but seems to have a larger foll... | Make sure you install a custom color theme. These URLs are a good place to start looking for one:
<http://www.codinghorror.com/blog/archives/000682.html>
<http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx>
I myself love Oren Ellenbogen's Dark Scheme. Really pleasant to the eyes. Also, make sure t... | Customizing Visual Studio | [
"",
"c#",
"asp.net",
"winforms",
"visual-studio",
""
] |
I'm considering developing a website similar to stackoverflow, but the answers may also consist of drawings (schematics, in this case). I want to have an area in the answer form where they can make this schematic without requiring special plugins, etc.
1. Are we to the point where SVG has or should have critical mass ... | Unfortunately, I don't have an answer, but I do have three pointers to projects that you could look at.
The first is the [Lively Kernel](http://Research.Sun.Com/projects/lively/ "Lively Kernel") by Dan Ingalls (yes, *the* Dan Ingalls) at Sun Labs. It is an implementation of a Smalltalk Virtual World in JavaScript on t... | [Raphael](http://raphaeljs.com/) looks like an interesting take on the problem of cross-browser vector graphics. | About scripting SVG | [
"",
"javascript",
"ajax",
"svg",
""
] |
I'm developing a site in Visual Web Dev Express, and when I run/debug, I'd like to be able to set my application's document root so that I can use safer paths, like "/css/style.css' instead of "css/style.css". How would I accomplish this? | * Click on the web site node in the solution explorer.
* Press F4 to see the properties window.
* Change the virtual path from **/projectname** to **/**
Bear in mind that this has an impact on how you expect the application/web site to be deployed. If it is ever used outside the root of a web server, the URL paths wil... | I have been looking for the virtual path field in the properties window but haven't been able to find it... it only shows me the following options
* aperture directory URL
* complete access route
* policy file
* port
* use dynamic port
Do you know of some place else where I could find the Virtual Path field? | Visual Web Developer (Express): Setting Document Root for Dev Environment | [
"",
"c#",
"asp.net",
"visual-web-developer",
"server-configuration",
""
] |
After reading Jeff's blog post on [Protecting Your Cookies: HttpOnly](http://www.codinghorror.com/blog/archives/001167.html). I'd like to implement HttpOnly cookies in my web application.
How do you tell tomcat to use http only cookies for sessions? | httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.
See the [changelog](http://tomcat.apache.org/tomcat-6.0-doc/changelog.html) entry for bug 44382.
The last comment for bug [44382](https://issues.apache.org/bugzilla/show_bug.cgi?id=44382) states, "this has been applied to 5.5.x and will be included in 5.5.2... | > **Update: The JSESSIONID stuff here is
> only for older containers. Please use
> jt's currently accepted answer unless
> you are using < Tomcat 6.0.19 or < Tomcat
> 5.5.28 or another container that does not support HttpOnly JSESSIONID cookies as a config option.**
When setting cookies in your app, use
```
response.... | How do you configure HttpOnly cookies in tomcat / java webapps? | [
"",
"java",
"security",
"cookies",
"xss",
"httponly",
""
] |
So I'm getting a new job working with databases (Microsoft SQL Server to be precise). I know nothing about SQL much less SQL Server. They said they'd train me, but I want to take some initiative to learn about it on my own to be ahead. Where's the best place to start (tutorials, books, etc)? I want to learn more about ... | If you're planning on coding against a sql database using .NET, skip ADO and go directly to Linq. You will NOT miss anything.
Oh, also, Joe Celko. If you see his name on an article or a book about SQL, read it. | This can be broad but here are some responsibilities that could get thrown at you in a brain dump format.
on the DBA end
* Backups
* Indexes
* Triggers
* Security per table database creating users ect.
* ODBC in your windows control panel
* know you normal forms
* the diff between a data warehouse (for reporting)
* a... | Best way to learn SQL Server | [
"",
"sql",
"sql-server",
"database",
""
] |
I'm not quite sure if this is possible, or falls into the category of pivot tables, but I figured I'd go to the pros to see.
I have three basic tables: Card, Property, and CardProperty. Since cards do not have the same properties, and often multiple values for the same property, I decided to use the union table approa... | Is this for SQL server?
If yes then
[Concatenate Values From Multiple Rows Into One Column (2000)](http://wiki.lessthandot.com/index.php/Concatenate_Values_From_Multiple_Rows_Into_One_Column)
[Concatenate Values From Multiple Rows Into One Column Ordered (2005+)](http://wiki.lessthandot.com/index.php/Concatenate_Va... | Related but values are values are kept in separate columns and you have know your "special types" a head of time:
[SQL query to compare product sales by month](https://stackoverflow.com/questions/17194/sql-query-to-compare-product-sales-by-month#17290)
Otherwise I would do this with cursor in a stored procedure or ... | Query a union table with fields as columns | [
"",
"sql",
"database-design",
"stored-procedures",
""
] |
How is it possible to make prototype methods in C#.Net?
In JavaScript, I can do the following to create a trim method for the string object:
```
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
```
How can I go about doing this in C#.Net? | You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class.
You can, however, in C# 3.0, use extension methods, which *look* like new methods, but are compile-time magic.
To do this for your code:
```
public static class StringExtensions
{
public static... | It sounds like you're talking about C#'s Extension Methods. You add functionality to existing classes by inserting the "this" keyword before the first parameter. The method has to be a static method in a static class. Strings in .NET already have a "Trim" method, so I'll use another example.
```
public static class My... | How can I create Prototype Methods (like JavaScript) in C#.Net? | [
"",
"c#",
".net",
""
] |
How can I request a random row (or as close to truly random as possible) in pure SQL? | See this post: [SQL to Select a random row from a database table](http://www.petefreitag.com/item/466.cfm). It goes through methods for doing this in MySQL, PostgreSQL, Microsoft SQL Server, IBM DB2 and Oracle (the following is copied from that link):
Select a random row with MySQL:
```
SELECT column FROM table
ORDER... | Solutions like Jeremies:
```
SELECT * FROM table ORDER BY RAND() LIMIT 1
```
work, but they need a sequential scan of all the table (because the random value associated with each row needs to be calculated - so that the smallest one can be determined), which can be quite slow for even medium sized tables. My recommen... | How to request a random row in SQL? | [
"",
"sql",
"random",
""
] |
I am writing a query in which I have to get the data for only the last year. What is the best way to do this?
```
SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
``` | The following adds -1 years to the current date:
```
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
``` | I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting... | SQL Server: Get data for only the past year | [
"",
"sql",
"sql-server",
"database",
"t-sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.