instruction stringlengths 0 30k ⌀ |
|---|
You should not add a default to the constructor; this will mean that in the creation of the object the property will have to be assigned to twice (once as null, then again in the constructor). If you require a default value for a property it should broken out as a normal property (or possibly deferred to a builder in a creational pattern).
One other option is to do what ASP.Net does and define defaults via an attribute:
http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
But again, I would simply break out the property as this is the clearest and most efficient option. |
I believe that this tutorial on jQuery has an example that might help you: [http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery][1]
[1]: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery |
If you're looking at joining two private networks (two networks of machines behind a NAT), the best way to do this is with a [VPN][1]. There are many pieces of equipment available to accomplish this.
[1]: http://en.wikipedia.org/wiki/Virtual_private_network |
Comparing two byte arrays in .NET |
|c#| |
How can I do this fast?
Sure I can do this:
static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if(a1.Length!=a2.Length)
return false;
for(int i=0; i<a1.Length; i++)
if(a1[i]!=a2[i])
return false;
return true;
}
but I'm looking for either a BCL function or some highly optimized proven way to do this. |
How can I do this fast?
Sure I can do this:
static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if(a1.Length!=a2.Length)
return false;
for(int i=0; i<a1.Length; i++)
if(a1[i]!=a2[i])
return false;
return true;
}
but I'm looking for either a BCL function or some highly optimized proven way to do this.
[Edit]Thanks to JasonBunting and aku for their input.
ebil gil suggested unsafe code which spawned this solution:
static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) {
if(a1==null || a2==null || a1.Length!=a2.Length)
return false;
fixed (byte* p1=a1, p2=a2) {
byte* x1=p1, x2=p2;
int l = a1.Length;
for (int i=0; i < l/8; i++, x1+=8, x2+=8)
if (*((long*)x1) != *((long*)x2)) return false;
if ((l & 4)!=0) } if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; }
if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; }
if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false;
return true;
}
}
which does 64-bit based comparison for as much of the array as possible. This kinda counts on the fact that the arrays start qword aligned.
<p>It performs about 7x faster. Using the J# library performed equivelently to the original for loop. Using .SequenceEqual runs around 7x slower, I think just because it is using IEnumerator.MoveNext. |
Overriding the equals method is necessary if you want to test equivalence in standard library classes (for example, ensuring a java.util.Set contains unique elements or using objects as keys in java.util.Map objects).
Note, if you override equals, ensure you honour the API contract as described in the documentation. For example, ensure you also override [Object.hashCode][1]:
> If two objects are equal according to
> the equals(Object) method, then
> calling the hashCode method on each of
> the two objects must produce the same
> integer result.
EDIT: I didn't post this as a complete answer on the subject, so I'll echo Fredrik Kalseth's statement that overriding equals works best for [immutable objects][2]. To quote the API for [Map][3]:
> Note: great care must be exercised if
> mutable objects are used as map keys.
> The behavior of a map is not specified
> if the value of an object is changed
> in a manner that affects equals
> comparisons while the object is a key
> in the map.
[1]: http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html
[2]: http://en.wikipedia.org/wiki/Immutable_object
[3]: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Map.html |
Slightly oversimplified a lambda function is one that can be passed round to other functions and it's logic accessed.
In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.
For instance:
LinqToSqlContext.Where( x => x > 15 );
LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees. |
Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.
In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.
For instance:
LinqToSqlContext.Where(
row => row.FieldName > 15 );
LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.
The statement above becomes:
select ... from [tablename]
where [FieldName] > 15 --this line was 'read' from the lambda function
This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be *read*.
|
Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.
In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.
For instance:
LinqToSqlContext.Where(
row => row.FieldName > 15 );
LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.
The statement above becomes:
select ... from [tablename]
where [FieldName] > 15 --this line was 'read' from the lambda function
This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be *read*.
Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:
LinqToSqlContext.Where(
row => SomeComplexCheck( row.FieldName ) );
Now the expression tree cannot be read - SomeComplexCheck cannot be broken down. The SQL statement will execute without the where, and every row in the data will be put through `SomeComplexCheck`.
|
Since it is an Identity column and you haven't saved it to the database yet it is -1. I am assuming here that this is before you save the table back to the database, correct? You need to perform the insert before that value will be set correctly. |
In our [JBoss Seam in Action presentation][1] at the Javapolis conference last year, my colleague and I said that 'Seam is the next Struts'. This needed some explanation, which I later wrote-up as [Seam is the new Struts][2]. Needless to say, we like Seam.
One indication popularity is the level of traffic on the [Seam Users Forum][3].
[1]: http://www.lunatech-research.com/archives/2007/12/14/javapolis-2007-seam
[2]: http://www.lunatech-research.com/archives/2008/03/17/seam-is-the-new-struts
[3]: http://www.seamframework.org/Community/SeamUsers |
In our [JBoss Seam in Action presentation][1] at the Javapolis conference last year, my colleague and I said that 'Seam is the next Struts'. This needed some explanation, which I later wrote-up as [Seam is the new Struts][2]. Needless to say, we like Seam.
One indication of Seam's popularity is the level of traffic on the [Seam Users Forum][3].
[1]: http://www.lunatech-research.com/archives/2007/12/14/javapolis-2007-seam
[2]: http://www.lunatech-research.com/archives/2008/03/17/seam-is-the-new-struts
[3]: http://www.seamframework.org/Community/SeamUsers |
BTree files are often much faster than relational databases. SQLite contains within it a BTree library which is in the public domain (as in genuinely 'public domain', not using the term loosely).
Frankly though, if I wanted a multi-user system I would need a lot of persuading not to use a decent server relational database. |
@DrPizza - this is a very good question, and one that strikes right to the heart of the problem. There are a few reasons why QueueUserWorkItem and the Windows NT thread pool was ruled out (although the Vista one does look interesting, maybe in a few years).
Firstly, we wanted to have greater control over when it starts up and stops threads. We have heard that the NT thread pool is reluctant to start up a new thread if it thinks that the tasks are short running. We could use the WT_EXECUTELONGFUNCTION, but we really have no idea if the task is long or short
Secondly, if the thread pool was already filled up with long running, low priority tasks, there would be no chance of a high priority task getting to run in a timely manner. The NT thread pool has no real concept of task priorities, so we can't do a QueueUserWorkItem and say "oh by the way, run this one right away".
Thirdly, (according to MSDN) the NT thread pool is not compatible with the STA apartment model. I'm not sure quite what this would mean, but all of our worker threads run in an STA. |
Thread pool for executing arbitrary tasks with different priorities |
|c++|multithreading|windows| |
|c++|windows|multithreading| |
I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can.
The thread pool needs to execute a series of tasks. The tasks can be short running (<1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available.
The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it.
Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running).
The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important.
In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run.
It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).
For refernce, we might use the following interface:
namespace ThreadPool
{
class Task
{
public:
Task();
void run();
};
class ThreadPool
{
public:
ThreadPool();
~ThreadPool();
void run(Task *inst);
void stop();
};
} |
*string* is an alias for *System.String*. So technically, there is no difference. It's like *int* vs. *System.UInt32*.
As far as guidelines, I think it's generally recommended to use *string* any time you would you're referring to an object. e.g.
string place = "world";
Likewise, I think it's generally recommended to use *String* if you need to refer specifically to the class. e.g.
string greet = String.Format("Hello {0}!", place);
This is the style that Microsoft tends to use in [their examples](http://msdn.microsoft.com/en-us/library/fht0f5be.aspx#ctl00_rs1_mainContentContainer_ctl110CSharp). |
`string` is an alias for `System.String`. So technically, there is no difference. It's like `int` vs. `System.UInt32`.
As far as guidelines, I think it's generally recommended to use `string` any time you would you're referring to an object. e.g.
string place = "world";
Likewise, I think it's generally recommended to use `String` if you need to refer specifically to the class. e.g.
string greet = String.Format("Hello {0}!", place);
This is the style that Microsoft tends to use in [their examples](http://msdn.microsoft.com/en-us/library/fht0f5be.aspx#ctl00_rs1_mainContentContainer_ctl110CSharp). |
`string` is an alias for `System.String`. So technically, there is no difference. It's like `int` *vs.* `System.Int32`.
As far as guidelines, I think it's generally recommended to use `string` any time you're referring to an object. e.g.
string place = "world";
Likewise, I think it's generally recommended to use `String` if you need to refer specifically to the class. e.g.
string greet = String.Format("Hello {0}!", place);
This is the style that Microsoft tends to use in [their examples](http://msdn.microsoft.com/en-us/library/fht0f5be.aspx#ctl00_rs1_mainContentContainer_ctl110CSharp). |
This [post on the IE Blog][1] explains different options for script debugging in IE.
Here is the [Apple Dev FAQ][2] on debugging Javascript in Safari.
[1]: http://blogs.msdn.com/ie/archive/2004/10/26/247912.aspx
[2]: http://developer.apple.com/internet/safari/faq.html#anchor14 |
Safari 3.0 and 3.1 include the [Drosera][1] JavaScript debugger, which you can enable on the Mac by following the instructions at that link. There's also the Safari [Web Inspector][2]..
[1]: http://trac.webkit.org/wiki/Drosera "Drosera"
[2]: http://trac.webkit.org/wiki/Web%20Inspector "Safari Web Inspector" |
For Safari you need to enable the "Develop" menu via Preferences (in Safari 3.1; see [the entry in Apple's Safari development FAQ][1]) or via
$ defaults write com.apple.Safari IncludeDebugMenu 1
at the terminal in Mac OS X. Then from the Develop menu choose Show Web Inspector and click on the Console link. Your script can write to the console using window.console.log.
For Internet Explorer, Visual Studio is really the best script debugger but the Microsoft Script Debugger is okay if you don't have Visual Studio. [This post on the IE team blog][2] walks you through installing it and connecting to Internet Explorer.
Internet Explorer 8 [looks][3] like it will have a very fancy script debugger, so if you're feeling really adventurous you could install the Internet Explorer 8 beta and give that a whirl.
[1]: http://developer.apple.com/internet/safari/faq.html#anchor14
[2]: http://blogs.msdn.com/ie/archive/2004/10/26/247912.aspx "Scripting Debugging in Internet Explorer"
[3]: http://www.west-wind.com/weblog/posts/271352.aspx |
Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.
In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.
For instance (in C#3):
LinqToSqlContext.Where(
row => row.FieldName > 15 );
LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.
The statement above becomes:
select ... from [tablename]
where [FieldName] > 15 --this line was 'read' from the lambda function
This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be *read*.
Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:
LinqToSqlContext.Where(
row => SomeComplexCheck( row.FieldName ) );
Now the expression tree cannot be read - SomeComplexCheck cannot be broken down. The SQL statement will execute without the where, and every row in the data will be put through `SomeComplexCheck`.
Lambda functions should not be confused with anonymous methods. For instance:
LinqToSqlContext.Where(
delegate ( DataRow row ) {
return row.FieldName > 15;
} );
This also has an 'inline' function, but this time it's just compiler magic - the C# compiler will split this out to a new instance method with an autogenerated name.
Anonymous methods can't be read, and so the logic can't be translated out as it can for lambda functions.
|
ArgumentNullException for Integer |
|.net| |
In .NET, is it more appropriate to throw an argument null exception for an Integer if the value is Integer.MinValue or Integer = 0 (assuming that 0 is not a valid value)? |
Throwing an ArgumentNullException isn't appropriate unless the argument is actually **null**. Throw an ArgumentOutOfRangeException instead (preferably with a message informing the user what values of int are actually acceptable).
> **ArgumentOutOfRangeException** is thrown when a method is invoked and at least one of the arguments passed to the method is not a null reference (**Nothing** in Visual Basic) and does not contain a valid value.
|
We've got complex requirements like:
1. Only certain users can create folders in parts of the SVN tree, but everyone can edit files there
2. Certain file extensions cannot contain certain text in the file
3. Certain file extensions can only be stored in a subset of directories
4. As well as several simpler ones like, Must have a commit comment
5. Regression testable by running new hook against all previous SVN commits
\#5 is huge for us, there's no better way to know you're not gonna break commits moving forward than to be able to push all previous commits through your new hook. Making the hook understand that 1234 was a revision and 1234-1 was a transaction and making the appropriate argument changes when calling svnlook, etc. was the best decision we made during the process.
For us the nut got big enough that a fully unit testable, regression testable, C# console exe made the most sense. We have config files that feed the directory restrictions, parse the existing httpd_authz file to get "privileged" users, etc. Had we not been running on Windows with a .NET development work force, I would have probably written it all in Python, but since others might need to support it in the future I went .NET over .BAT, .VBS, Powershell silliness.
Personally I think Powershell is different enough from .NET to be mostly useless as a "scripting" language. It's good if the only cmd line support for a product comes via PS (Exchange, Windows 2k8), etc. but if all you want to do is parse some text or access regular .NET objects PS just adds a crazy syntax and stupid Security Iron Curtain to what could be a quick and easy little .NET app. |
well, based on the documentation (http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx) it looks like
1. security attributes (can pass null)
2. whether it's initially owned (can pass false)
3. the name of it
HTH |
The VB code looks something like this:
hMutex = CreateMutex(ByVal 0&, 1, ByVal 0&)
The first parameter is a pointer to an SECURITY_ATTRIBUTES structure. If you don't know what it is, you don't need it. Pass NULL (0).
The second parameter is TRUE (non-zero, or 1) if the calling thread should take ownership of the mutex. FALSE otherwise.
The third parameter is the mutex name and may be NULL (0), as shown. If you need a named mutex, pass the name (anything unique) in. Not sure whether the VB wrapper marshals the length-prefixed VB string type (BSTR) over to a null-terminated Ascii/Unicode string if not, you'll need to do that and numerous examples are out there.
Good luck! |
IP to Country? |
|ip|lookup|country|iso-3166-1-alpha-2| |
Does anyone know of a simple way to retrieve the country for a given IP Address? Preferably in ISO_3166-1 format? |
Here's a nice free service with a public API:
<http://www.hostip.info/use.html> |
You can use this program, [Handle](http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx), to find which process has the lock on your file. It's a command-line tool, so I guess you use the output from that... I'm not sure about finding it programmatically.
If deleting the file can wait, you could specify it for deletion when your computer next starts up:
1.
Start REGEDT32 (W2K) or REGEDIT (WXP) and navigate to:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager
2.
* W2K: Edit, Add Value..., Data Type: REG_MULTI_SZ, Value Name:
PendingFileRenameOperations, OK
* WXP: Edit, New, Multi-String Value, [enter]
PendingFileRenameOperations
3.
In the Data area, enter "\??\" + filename to be deleted. LFNs may
be entered without being embedded in quotes. To delete "C:\Long
Directory Name\Long File Name.exe", enter the following data:
\??\C:\Long Directory Name\Long File Name.exe
Then press OK.
4.
The "destination file name" is a null (zero) string. It is entered
as follows:
* W2K: Edit, Binary, select Data Format: Hex, click at the end of the
hex string, enter 0000 (four zeros), OK.
* WXP: Right-click the value, choose "Modify Binary Data", click at the
end of the hex string, enter 0000 (four zeros), OK.
5.
Close REGEDT32/REGEDIT and reboot to delete the file.
(Shamelessly stolen from [some random forum](http://www.pcreview.co.uk/forums/thread-1581158.php), for posterity's sake.) |
Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the **MoveFileEx** api function (<http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx>) to mark the file for deletion upon next reboot.
If it appears that you really need to delete a file in use by another process, I'd recommend re-considering the actual problem before considering any solutions. |
Quoting a much-replicated help page about Indexing Service query language:
> To use specially treated characters such as &, |, ^, #, @, $, (, ), in a query, enclose your query in quotation marks (“).
As far as I know, full text search in MSSQL is also done by the Indexing Service, so this might help. |
|wordpress|php|mysql|wiki|lamp| |
I am running a WordPress blog right now on my own LAMP hosting. I really want to add some basic Wiki functionality to my site. Ideally just the ability to have some posts or pages that users with certain roles / capabilities could edit. The latest version of WordPress has edit revisions, so it would seem like I could leverage that.
I looked at the basic [roles and capabilities][1], and the edit_others_posts capability of the Editor role seems like it would be a good option, but it allows editing of ***ALL*** posts. What I want is the ability for **some** users to edit **some** pages / posts that *they don't own*. Maybe a flag on certain pages / posts that allows others to edit them.
On the other end of the spectrum I would be happy if I could install a Wiki and share the login credentials between WordPress and the Wiki. I hacked MediaWiki a while ago to share logins with another site (in Classic ASP) via session cookies and it was a pain to do and even worse to maintain. Ideally I would like to find a plug-in or someone who knows a more elegant solution.
[1]: http://codex.wordpress.org/Roles_and_Capabilities |
|php|mysql|wiki|lamp|wordpress| |
Wordpress MediaWiki Integration |
On the other end of the spectrum I would be happy if I could install a Wiki and share the login credentials between WordPress and the Wiki. I hacked MediaWiki a while ago to share logins with another site (in Classic ASP) via session cookies and it was a pain to do and even worse to maintain. Ideally I would like to find a plug-in or someone who knows a more elegant solution.
|
|php|mysql|wordpress|lamp|mediawiki| |
Yeah, I admit the requirement is a bit unusual. Some of the information that the users will be entering into this application exists in scans of old documents that are in a couple of different repositories. The buttons facilitate finding and opening these old docs. It's difficult to predict where the users will be on the form when they decide to pull up a document with more information to enter on the form. The intent is to make the UI flow well in spite of these funky circumstances. |
Use [Linq Join][1] operator:
var q = from a in tableA
join b in tableB on a.Key equals b.Key
select a;
[1]: http://www.hookedonlinq.com/JoinOperator.ashx |
Use [Linq Join][1] operator:
var q = from d in Dealer
join dc in DealerConact on d.DealerID equals dc.DealerID
select dc;
[1]: http://www.hookedonlinq.com/JoinOperator.ashx |
A .NET event isn't actually an object, it's an endpoint represented by two functions -- one for adding and one for removing a handler. That's why the compiler won't let you do anything other than += (which represents the add) or -= (which represents the remove).
The only way to refer to an event for metaprogramming purposes is as a System.Reflection.EventInfo, and reflection is probably the best way (if not the only way) to get ahold of one. |
|c#|.net|j#| |
How can I do this fast?
Sure I can do this:
static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if(a1.Length!=a2.Length)
return false;
for(int i=0; i<a1.Length; i++)
if(a1[i]!=a2[i])
return false;
return true;
}
but I'm looking for either a BCL function or some highly optimized proven way to do this.
[Edit]Thanks to JasonBunting and aku for their input.
ebil gil suggested unsafe code which spawned this solution:
static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) {
if(a1==null || a2==null || a1.Length!=a2.Length)
return false;
fixed (byte* p1=a1, p2=a2) {
byte* x1=p1, x2=p2;
int l = a1.Length;
for (int i=0; i < l/8; i++, x1+=8, x2+=8)
if (*((long*)x1) != *((long*)x2)) return false;
if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; }
if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; }
if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false;
return true;
}
}
which does 64-bit based comparison for as much of the array as possible. This kinda counts on the fact that the arrays start qword aligned.
<p>It performs about 7x faster. Using the J# library performed equivelently to the original for loop. Using .SequenceEqual runs around 7x slower, I think just because it is using IEnumerator.MoveNext. |
How can I do this fast?
Sure I can do this:
static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if(a1.Length!=a2.Length)
return false;
for(int i=0; i<a1.Length; i++)
if(a1[i]!=a2[i])
return false;
return true;
}
but I'm looking for either a BCL function or some highly optimized proven way to do this.
[Edit]Thanks to JasonBunting and aku for their input.
java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2);
works nicely, but it doesn't look like that would work for x64.
ebil gil suggested unsafe code which spawned this solution:
static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) {
if(a1==null || a2==null || a1.Length!=a2.Length)
return false;
fixed (byte* p1=a1, p2=a2) {
byte* x1=p1, x2=p2;
int l = a1.Length;
for (int i=0; i < l/8; i++, x1+=8, x2+=8)
if (*((long*)x1) != *((long*)x2)) return false;
if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; }
if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; }
if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false;
return true;
}
}
which does 64-bit based comparison for as much of the array as possible. This kinda counts on the fact that the arrays start qword aligned.
<p>It performs about 7x faster. Using the J# library performed equivalently to the original for loop. Using .SequenceEqual runs around 7x slower, I think just because it is using IEnumerator.MoveNext. |
The union answer is _almost_ correct, depending on overlapping values:
SELECT distinct ColumnA FROM Table1
UNION
SELECT distinct ColumnA FROM Table2
If 'd' appeared in Table1 or 'c' appeared in Table2 you would have multiple rows with them.
|
If the argument is not null, don't throw an ArgumentNullException. It would probably be more reasonable to throw an ArgumentException, explained here http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx.
edit: ArgumentOutOfRangeException is probably even better, as suggested above by Avenger546. |
You will be able to validate your XML with either an XML Schema or a DTD using C#. DTDs are older standards as compared to XML Schemas.
So, I recommend an XML Schema approach. |
I think several of the answers hit around the possible solution to your problem.
I agree the easiest (and best solution for SEO purposes) is the 301 redirect. In IIS this is fairly trivial, you'd create a site for subdomain.hostone.com, after creating the site, right-click on the site and go into properties. Click on the "Home Directory" tab of the site properties window that opens. Select the radio button "A redirection to a URL", enter the url for the new site (http://subdomain.hosttwo.com), and check the checkboxes for "The exact URL entered above", "A permanent redirection for this resource" (this second checkbox causes a 301 redirect, instead of a 302 redirect). Click OK, and you're done.
Or you could create a page on the site of http://subdomain.hostone.com, using one of the following methods (depending on what the hosting platform supports)
PHP Redirect:
<pre><code>
<?
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://subdomain.hosttwo.com" );
?>
</code></pre>
ASP Redirect:
<pre><code>
<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://subdomain.hosttwo.com"
%>
</code></pre>
ASP .NET Redirect:
<pre><code>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://subdomain.hosttwo.com");
}
</script>
</code></pre>
Now assuming your CNAME record is correctly created, then the only problem you are experiencing is that the site created for http://subdomain.hosttwo.com is using a shared IP, and host headers to determine which site should be displayed. To resolve this issue under IIS, in IIS Manager on the web server, you'd right-click on the site for subdomain.hosttwo.com, and click "Properties". On the displayed "Web Site" tab, you should see an "Advanced" button next to the IP address that you'll need to click. On the "Advanced Web Site Identification" window that appears, click "Add". Select the same IP address that is already being used by subdomain.hosttwo.com, enter 80 as the TCP port, and then enter subdomain.hosttwo.com as the Host Header value. Click OK until you are back to the main IIS Manager window, and you should be good to go. Open a browser, and browse to http://subdomain.hostone.com, and you'll see the site at http://subdomain.hosttwo.com appear, even though your URL shows http://subdomain.hostone.com
Hope that helps...
|
I started with LabVIEW about 2 years ago and now use it all the time so may be biased but find it ideal for applications where data acquisition and control are involved.
We use LabVIEW mainly for testing where we take continuous measurements and control gas valves and ATE enclosures. This involves both digital and analogue input and outputs with signal analysis routines and process control all running from a GUI. By breaking down each part into subVIs we are able to reconfigure the tests with the click and drag of the mouse.
I think the process of programming is more important than the actual coding language and you should follow the style guidelines for a graphical programming language. LabVIEW block diagrams show the flow of data ([Dataflow programming][1]) so it should be easy to see potential race conditions although I've never had any problems.
If you have a C codebase then building it into a dll will allow LabVIEW to call it directly.
[1]:http://en.wikipedia.org/wiki/Dataflow_programming |
I'd recommend being defensive for data that enter a "component" or framework. Within a "component" or framework one should think that the data is "correct".
Thinking like this. It is up to the caller to supply correct parameters otherwise ALL functions and methods have to check every incomming parameter. But if the check is only done for the caller the check is only needed once. So, a parameter should be "correct" and thus can be passed through to lower levels.
1. Always check data from external sources, users etc
2. A "component" or framework should always check incomming calls.
If there is a bug and a wrong value is used in a call. What is really the right thing todo? One only have an indication that the "data" the program is working on is wrong and some like ASSERTS but others want to use advanced error reporting and possible error recovery. In any case the data is found to be faulty and in few cases it's good to continue working on it. (note it's good if servers don't die at least)
An image sent from a satellite might be a case to try advanced error recovery on...an image downloaded from the internet to put up an error icon for... |
The short answer is: No. In ASP.NET MVC Preview 3 there's no first-class way for including an anchor in an action link. Unlike Rails' url_for :anchor, UrlHelper.GenerateUrl (and ActionLink, RedirectToAction and so on which use it) don't have a magic property name that lets you encode an anchor.
As you point out, you could roll your own that does. This is probably the cleanest solution.
Hackily, you could just include an anchor in a route and specify the value in your parameters hash:
routes.MapRoute("WithTarget", "{controller}/{action}/{id}#{target}");
...
<%= Html.ActionLink("Home", "Index", new { target = "foo" })%>
This will generate a URL like /Home/Index/#foo. Unfortunately this doesn't play will with URL parameters, which appear at the end of the URL. So this hack is only workable in really simple circumstances where all of your parameters appear as URL path components. |
The player itself has a [Javascript API][1] that might be useful for syncing the video if you choose to make your own annotation-thingamajig.
[1]: http://code.google.com/apis/youtube/js_api_reference.html |
I am very much of the opinion that correct programming will protect against these risks. Things like avoiding deprecated functions, which (in the Microsoft C++ libraries at least) are commonly deprecated because of security vulnerabilities, and validating everything that crosses an external boundary.
Functions that are only called from your code should not require excessive parameter validation because you control the caller, that is, no external boundary is crossed. Functions called by other people's code should assume that the incoming parameters will be invalid and/or malicious at some point.
My approach to dealing with exposed functions is to simply crash out, with a helpful message if possible. If the caller can't get the parameters right then the problem is in their code and they should fix it, not you. (Obviously you have provided documentation for your function, since it is exposed.)
Code injection is only an issue if your application is able to elevate the current user. If a process can inject code into your application then it could easily write the code to memory and execute it anyway. Without being able to gain full access to the system code injection attacks are pointless. (This is why applications used by administrators should not be writeable by lesser users.) |
You could match the property names up to the keys and use reflection to get the name for the lookup. |
You could match the property names up to the keys and use reflection to get the name for the lookup.
Hmm.. hopefully someone can prove me wrong, but I don't think this is possible so never mind. I don't think you can use reflection to find the current method. |
You could match the property names up to the keys and use reflection to get the name for the lookup.
public string FirstProperty {
get {
return Dictionary[PropertyName()];
}
set {
Dictionary[PropertyName()] = value;
}
private string PropertyName()
{
return new StackFrame(1).GetMethod().Name.Substring(4);
}
This has the added benefit of making all your property implementation identical, so you could set them up in visual studio as code snippets if you want. |
There is a technique called "[Hole Punching][1]" that works well with "Cone" NAT (Cone is a technical familly of router). That's not an 100% sure technique, today, it works well with UDP on about 80% of the router.
There is some implementations of library to realize Hole Punching: [STUN][2] ([wikipedia][3])
[1]: http://en.wikipedia.org/wiki/Hole_punching
[2]: http://sourceforge.net/projects/stun/
[3]: http://en.wikipedia.org/wiki/STUN
|
A more specific question might give more helpful results, but here's a simple pair of snippets that shows and later updates text in a status container element.
<pre>
// give some visual cue that you're waiting
container.appendChild( document.createTextNode( "Getting stuff from remote server..." ) );
// then later...
// update request status
container.replaceChild( document.createTextNode( "Done." ), container.firstChild );
</pre> |
Best way to use a property to reference a Key-Value pair in a dictionary |
|dictionary| |
This is a fairly trivial matter, but I'm curious to hear people's opinions on it.
If I have a Dictionary<string, string> which I'm access through properties, which of these formats would you prefer for the property?
/// <summary>
/// This class's FirstProperty property
/// </summary>
[DefaultValue("myValue")]
public string FirstProperty {
get {
return Dictionary["myKey"];
}
set {
Dictionary["myKey"] = value;
}
This is probably the typical way of doing it. It's fairly efficient, easy to understand, etc. The only disadvantage is with a longer or more complex key it would be possible to misspell it or change only one instance or something, leading me to this:
/// <summary>
/// This class's SecondProperty property
/// </summary>
[DefaultValue("myValue")]
private const string DICT_MYKEY = "myKey"
public string SecondProperty {
get {
return Dictionary[DICT_MYKEY];
}
set {
Dictionary[DICT_MYKEY] = value;
}
Which is marginally more complicated, but seems to offer additional safety, and is closer to what I would think of as the "Code Complete" solution. The downside is that when you also have a /// <summary> block and a [DefaultValue()] block above the property already, it starts getting a bit crowded up there.
So which do you like better, and why? Does anybody have any better ideas?
|
I started with LabVIEW about 2 years ago and now use it all the time so may be biased but find it ideal for applications where data acquisition and control are involved.
We use LabVIEW mainly for testing where we take continuous measurements and control gas valves and ATE enclosures. This involves both digital and analogue input and outputs with signal analysis routines and process control all running from a GUI. By breaking down each part into subVIs we are able to reconfigure the tests with the click and drag of the mouse.
Not exactly the same as C/C++ but a similar implementation of measurement, control and analysis using Visual BASIC appears complex and hard to maintain by comparision.
I think the process of programming is more important than the actual coding language and you should follow the style guidelines for a graphical programming language. LabVIEW block diagrams show the flow of data ([Dataflow programming][1]) so it should be easy to see potential race conditions although I've never had any problems. If you have a C codebase then building it into a dll will allow LabVIEW to call it directly.
[1]:http://en.wikipedia.org/wiki/Dataflow_programming |
Is FindFirstChangeNotification the best API to use for file system change notification on windows? |
|windows|notifications| |
I'm new to windows programming and I'm trying to get notified of all changes to the file system (similar to the information that FileMon from SysInternals displays, but via an API). Is a FindFirstChangeNotification for each (non-network, non-substed) drive my best bet or are there other more suitable C/C++ APIs? |
|windows|notifications|winapi| |
|windows|c|file|winapi|notifications| |
Well, I think if you are using an int, then it would be better to say InvalidArgumentException.
Alternatively, you could make your INTs nullable by declaring them as *int?* (especially if you expect null values for your int.
|
Well, I think if you are using an int, then it would be better to say InvalidArgumentException.
Alternatively, you could make your INTs nullable by declaring them as *int?* (especially if you expect null values for your int.)
|
What is the best method for checking if a file exists from a SQL Server 2005 stored procedure? |
|sql-server| |
We used the "undocumented" xp_fileexist stored procedure for years in SQL Server 2000 and had no trouble with it. In 2005, it seems that they modified the behavior slightly to always return a 0 if the executing user account is not a sysadmin. It also seems to return a zero if the SQL Server service is running under the LocalSystem account and you are trying to check a file on the network.
I'd like to get away from xp_fileexist. Does anyone have a better way to check for the existence of a file at a network location from inside of a stored procedure? |
You should also check hardware connectivity to the database.
Perhaps this thread will be helpful:
[http://channel9.msdn.com/forums/TechOff/234271-Conenction-forcibly-closed-SQL-2005/][1]
[1]: http://channel9.msdn.com/forums/TechOff/234271-Conenction-forcibly-closed-SQL-2005/ |
If you want to do it programatically. I'm not sure... and I'd really recommend against it.
If you're just troubleshooting stuff on your own machine, [SysInternals Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) can help you
Run it, use the Find Handle command (I think it's either in the find or handle menu), and search for the name of your file. Once the handle(s) is found, you can forcibly close them.
You can then delete the file and so on.
**Beware**, doing this may cause the program which owns the handles to behave strangely, as you've just pulled the proverbial rug out from under it, but it works well when you are debugging your own errant code, or when visual studio / windows explorer is being crap and not releasing file handles even though you told them to close the file ages ago... sigh :-) |
Oh, one big hack I employed years ago, is that windows won't let you *delete* files, but it does let you *move* them.
Pseudo-sort-of-code:
mv %WINDIR%\System32\mfc42.dll %WINDIR\System32\mfc42.dll.old
Install new mfc42.dll
Tell user to save work and restart applications
Upon restart, the apps loaded the new mfc42.dll, and all was well. That, coupled with PendingFileOperations to delete the old one on system restart, worked pretty well |
try [libpcre](http://www.pcre.org/)
If you're stuck on windows they have a windows port which should work. I know [e-texteditor](http://e-texteditor.com) uses it, so at least that's proof it works :-) |
A lot of people (including my company) seem to use MaxMind GeoIP.
They have a free version [GeoLite](http://www.maxmind.com/app/geoip_country) which is not as accurate as the paid version, but if you're just after something simple, it may be good enough. |
The typical method is as follows. You've said you want to do this in C# so here goes...
1. If you don't know which process has the file locked, you'll need to examine each process's handle list, and query each handle to determine if it identifies the locked file. Doing this in C# will likely require P/Invoke or an intermediary C++/CLI to call the native APIs you'll need.
2. Once you've figured out which process(es) have the file locked, you'll need to safely inject a small native DLL into the process (you can also inject a managed DLL, but this is messier, as you then have to start or attach to the .NET runtime).
3. That bootstrap DLL then closes the handle using CloseHandle etc.
Essentially: the way to unlock a "locked" file is to inject a DLL into the offending process's address space and close it yourself. You can do this using native or managed code. No matter what, you're going to need a small amount of native code or at least P/Invoke into the same.
Good luck! |
The typical method is as follows. You've said you want to do this in C# so here goes...
1. If you don't know which process has the file locked, you'll need to examine each process's handle list, and query each handle to determine if it identifies the locked file. Doing this in C# will likely require P/Invoke or an intermediary C++/CLI to call the native APIs you'll need.
2. Once you've figured out which process(es) have the file locked, you'll need to safely inject a small native DLL into the process (you can also inject a managed DLL, but this is messier, as you then have to start or attach to the .NET runtime).
3. That bootstrap DLL then closes the handle using CloseHandle etc.
Essentially: the way to unlock a "locked" file is to inject a DLL into the offending process's address space and close it yourself. You can do this using native or managed code. No matter what, you're going to need a small amount of native code or at least P/Invoke into the same.
Helpful links:
- <http://www.codeproject.com/KB/threads/winspy.aspx>
- <http://damianblog.com/2008/07/02/net-code-injection/>
Good luck! |
I am also having a number of problems with VS 2008. Who would guess that I don't ever need to select multiple controls on a web form...
Anyway, a lot has been fixed in Service Pack 1, which is in Beta currently. Might be worth installing that. It has gone a little way to fixing absolute positioning. This isn't your problem, of course, but your fix might be in there as well. |
The funny thing is i wrote a php media gallery for all my music 2 days ago. I had a similar problem. Im using http://musicplayer.sourceforge.net/ for the player. and the playlis are built via php. all music request go there a script called xfer.php?file=WHATEVER
$filename = base64_url_decode($_REQUEST['file']);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($filename));
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename));
// Put either file counting code here. either a db or static files
//
readfile($filename); //and spit the user the file
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_,', '+/='));
}
And when you call files use something like
function base64_url_encode($input) {
return strtr(base64_encode($input), '+/=', '-_,');
}
http://us.php.net/manual/en/function.base64-encode.php |
The funny thing is i wrote a php media gallery for all my music 2 days ago. I had a similar problem. Im using http://musicplayer.sourceforge.net/ for the player. and the playlis are built via php. all music request go there a script called xfer.php?file=WHATEVER
$filename = base64_url_decode($_REQUEST['file']);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($filename));
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename));
// Put either file counting code here. either a db or static files
//
readfile($filename); //and spit the user the file
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_,', '+/='));
}
And when you call files use something like
function base64_url_encode($input) {
return strtr(base64_encode($input), '+/=', '-_,');
}
http://us.php.net/manual/en/function.base64-encode.php
If you are using some javascript or a flash player (JW player for example) that requires the actual link to be an mp3 file or whatever, you can append the text "&type=.mp3" so the final linke becomes something like "www.example.com/xfer.php?file=34842ffjfjxfh&type=.mp3". That way it looks like it ends with an mp3 extension without affecting the file link. |
We've had problems when trying to add large numbers of files to repositories through the client which I assume created orphaned processes on the server when we killed the crashed client. We had to kill the server processes too and restart the subversion service (we run SVN as a windows service). Our SVN machine is dedicated so we actually just rebooted the box and everything went back to normal. |
Animation in .Net |
|dictionary|constants|property| |
|dictionary|constants|property|.net| |
|.net|dictionary|properties|constants| |
Looking for a simple JavaScript example that updates DOM. |
|javascript| |
The question says it all. :) |