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",
""
] |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 8