input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Can you force activerecord associations to update without saving them? <p>I have a couple models which are associated with the <code>has_many</code> <code>belongs_to</code> pair. For the sake of demonstration, a client has one server but a server has many clients. I might do something like this:</p>
<pre><code>client1.server = the_server
client2.server = the_server
client3.server = the_server
</code></pre>
<p>My actual application is quite a bit more complex than this, but the example will work for illustration.</p>
<p>I want to inspect the associations between these objects before I save them. ActiveRecord doesn't update their information until they are saved though. In the example above, <code>the_server</code> has no idea who <code>client1</code>, <code>client2</code>, or <code>client3</code> are until one of them gets saved. I'm sure that this helps active_record's efficiency, but it leaves model instances in memory in an inconsistent state.</p>
<p>Is there anything I can call on the clients or on the server that will cause them to update their states?</p>
| <p>Call <code>#reload</code> on the objects to update them.</p>
|
Javascript: Why compare with null? <p>An open source JavaScript project I work on includes code:</p>
<pre><code>if (color) {
tapeDiv.style.backgroundColor = color;
// set color here if defined by event. Else use css
}
</code></pre>
<p>A contributor wants to change it to </p>
<pre><code>if (color != null) { // this line changed
tapeDiv.style.backgroundColor = color;
// set color here if defined by event. Else use css
}
</code></pre>
<p>color is a string var. Only a string of more than 0 characters should be used to explicitly set the color.</p>
<p>Since JS casts "" and null as boolean false, why would the comparison != null be needed?</p>
<p>Am I missing something in thinking that the first form is just as good (and a bit shorter) than the second?</p>
<p>I see comparisons with null quite often in JS source. Why are they needed when all JS simple objects have known results when cast as booleans? </p>
<p>Thanks,</p>
<p>Larry</p>
<p>ps. I suppose if 0 (an integer) was a valid case, then if(0) would be false [a problem] and if(0 != null) would be true [allows the 0 case]. Any other reason?</p>
<p>pps. Should have mentioned that the tapeDiv is newly created. So there's no point to resetting the style to "" since the div is brand new.</p>
| <p>Evaluate the assignment with all possible falsy values and you'll get your answer:</p>
<pre><code>tapeDiv.style.backgroundColor = false; // does nothing
tapeDiv.style.backgroundColor = 0; // sets as "black",
// but ignored by FF
tapeDiv.style.backgroundColor = null; // resets the background-color
// to use whatever is defined
// in a stylesheet (if any),
// but ignored by IE.
tapeDiv.style.backgroundColor = ''; // resets the background-color
// to use whatever is defined
// in a stylesheet (if any).
</code></pre>
<p>The check for "<code>if (color)</code>" will not let any of them through.</p>
<p>The check for "<code>if (color != null)</code>" will let 1), 2) and 4) through. 1) doesn't do anything, 2) won't work as expected in Firefox, and 4) will always work as expected. However, "works" is dependent on your context (which you did not provide).</p>
<p>Hope that helps.</p>
|
GCC compiler error: "redefinition...previously defined" <p>I'm getting a lot of " redefinition of x....x previously defined here". Please what does this error means?</p>
| <p>You need to limit each file from being included only once. You can do this in 2 ways. </p>
<p>1) At the top of your header files put:</p>
<pre><code>#pragma once
</code></pre>
<p>Or 2) if your compiler doesn't support that, put at the top/end of your header files:</p>
<pre><code>#ifndef _MYFILE_H_
#define _MYFILE_H_
...
#endif
</code></pre>
<p>Replace MYFILE with the name of your file, and replace ... with the contents of the header file. </p>
|
Modifying a type after it has been created with TypeBuilder.CreateType <p>I'm creating a dynamic class in a dynamic assembly at runtime, and want to be able to Define methods for that class on demand.</p>
<p>Ex.</p>
<ol>
<li>Build the Type X</li>
<li>Define Method GetA on Type X</li>
<li>Create Type X</li>
<li>Call GetA</li>
<li>use same type builder for Type X</li>
<li>Define new Method GetB on Type X</li>
<li>Recreate type X, that now has both GetA and GetB</li>
</ol>
<p>if that is impossible then I will have to build the type on demand for one of the methods, and to do that then I have to create the assembly as well, on each time.</p>
<p>Any Ideas,
Thanks</p>
| <p>You can't create "full" methods (discoverable via reflection) - however, you can use <code>DynamicMethod</code> to associate new IL blocks with a type (primarily for scope etc). But ultimately, what you describe is a job for the DLR in 4.0 (and a language such as Iron Python; C# and VB don't add language support for <em>declaring</em> dynamic methods - only consuming them).</p>
|
Is it possible to perform checks on what may be an uninitialized variable? <p>I'm working on a recursive method...</p>
<pre><code>public BinaryTree<T> TreeMirror ( BinaryTree<T> tree ) {
BinaryTree mirror = new BinaryTree();
mirror = clone(tree);
...
TreeMirror(...)
...
}
</code></pre>
<p>I do not wish for the method to make <code>mirror</code> reference a different <code>BinaryTree</code> object in each recursive step, nor to repeat the <code>mirror = clone(tree)</code> statement after the first iteration. I'm wondering if it's possible to put in an if-statement check to see if an instance of <code>mirror</code> has already been initialized -- in which case the <code>mirror = new BinaryTree()</code> and <code>mirror = clone(tree)</code> statements would be skipped. </p>
<p>I don't think this is possible without passing <code>mirror</code> as an argument into the method or defining it in the class definition... but I want to make sure.</p>
<p>Any advice is much appreciated.</p>
<p>---------EDIT-----------<p>
I am not allowed to change the method signature, so I cannot pass the object in in my implementation. I can create a mirror tree but only by modifying the original tree into a mirror which is something I want to try to avoid. I was attempting to create a new <code>BinaryTree</code> object that is the mirror of the original tree that is passed in but really cannot figure out how to do it recursively.</p>
| <p>It's rare to see public recursive functions like that. A better solution might be to have the public method that creates the object, and then calls a private function which is recursive that just makes the necessary changes. </p>
<p>It's generally difficult to have the recursive function signature match what you want to show to your clients. </p>
|
Why would I want to use jQuery? <p>(I understand that someone else asked a similar question and it was closed as 'argumentative', but I'm really interested in understanding the arguments around this.)</p>
<p>I know JavaScript really well. I've been writing it professionally for years. I've internalized a lot of the cross-browser incompatibilities and sketchiness, know DOM manipulation like the back of my hand, have worked with some of the best web developers in the industry & picked up a lot of their mojo. </p>
<p>I've been checking out jQuery. I understand the point of a javascript library (how many times have I written animation, getElementsByClass, and hide/show functions?). But to be honest, it seems like a waste of time to learn an entirely new syntax that isn't less complex. It seems like I'd be bashing my head against a wall to learn an entirely new interface to the same old JavaScript.</p>
<p>I'm not technically an engineer, so maybe I'm missing something. Could someone spell out the tradeoffs of jQuery? Is it really faster to learn and understand jQuery syntax than to just learn JavaScript?</p>
| <p>There are a few big benefits to using a framework over homegrown/handwritten code:</p>
<ul>
<li><p><strong>Abstractions</strong>. I'm sure you're very proud of the fact that you've slung enough JS to be able to write animations from scratch. You should be! However, abstracting common functionality away from yourself is actually very liberating. You just call the method and know the innards will be executed, and executed well. Even if you're very fast at writing the low-level stuff yourself, that's still time you've spent on that instead of solving today's problems.</p></li>
<li><p><strong>Common language</strong>. Using a common framework is like speaking a common language. You can collaborate with other developers very easily, and each can pick up where others left off without friction. (Compared to stepping into an application which uses a homegrown library for the things jQuery can do.)</p></li>
<li><p><strong>Experts</strong>. The people working on jQuery are JavaScript <em>gods</em>. I am really, really good at JavaScript, and you probably are too, but there's a big difference between normal good and jQuery good. A team of insanely good people are constantly poring over a small set of common functionality - tuning it, tweaking it, enhancing it to make it the best it can possibly be. That represents a huge number of man-hours a single person like you or me simply cannot reproduce, no matter how good we are. And if you <em>are</em> as good as the jQuery guys, you can only benefit by combining your talent with theirs and contributing to the jQuery codebase. It's a melting pot of insane talent.</p></li>
</ul>
|
Simple select nth highest <p>I'm trying to figure out which is the more efficient way to get the nth highest record in a mySQL database:</p>
<pre><code>SELECT *
FROM table_name
ORDER BY column_name DESC
LIMIT n - 1, 1
</code></pre>
<p>or</p>
<pre><code>SELECT *
FROM table_name AS a
WHERE n - 1 = (
SELECT COUNT(primary_key_column)
FROM products b
WHERE b.column_name > a. column_name)
</code></pre>
<p>There is an index on column_name.</p>
<p>I would think mySQL would efficiently perform the limit clause and the first option is the way to go.</p>
<p>I wasn't too clear what the 2nd query does exactly, so if that is more efficient can someone explain why.</p>
<p>Thanks.</p>
| <p>I tried EXPLAIN on both those queries on a database of mine (note: the optimizer may choose different plans for your schema/data) and it definitely looks like the first one wins in every regard: it's simpler to read and understand, and will most likely be faster. </p>
<p>As aaronls said, and EXPLAIN confirms, the second query has a correlated subquery which will require an extra iteration through the entire table for each row. </p>
<p>Since the first one is way easier to read, I'd choose it in a shot. If you do find that it's a bottleneck (after profiling your application), you could give the second a try but I don't see how it could possibly be faster.</p>
|
PHP Fatal error: Cannot redeclare class <p>Does anyone know what can cause this problem?</p>
<pre><code>PHP Fatal error: Cannot redeclare class
</code></pre>
| <p>You have a class of the same name declared more than once. Maybe via multiple includes. When including other files you need to use something like </p>
<pre><code>include_once "something.php";
</code></pre>
<p>to prevent multiple inclusions. It's very easy for this to happen, though not always obvious, since you could have a long chain of files being included by one another.</p>
|
How to use HTTP GET request in C# with SSL? (protocol violation) <p>I am currently trying to get a response from a server that is using SSL in C#. I have the code to do this in Java, but it looks like they do not translate 1:1. </p>
<p>I do have some code that I found that works for regular pages, but not for the one I need (maybe because of the SSL thing). Here is the code:</p>
<pre><code> WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort);
request.Proxy = null;
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
</code></pre>
<p>UPDATE: Sorry I seem to have forgotten what the error is. I'm getting a protocol violation exception at the "HttpWebResponse response = (HttpWebResponse)request.GetResponse(); " line.
Any ideas? Thanks guys.</p>
| <p>HTTP conversations over SSL use a properly issued certificate for validation. </p>
<p>You could use the RemoteCertificateValidationCallback delegate for validating the SSL certificate as follows:</p>
<pre><code>public static void ConnectSSL()
{
WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort);
request.Proxy = null;
request.Credentials = CredentialCache.DefaultCredentials;
//allows for validation of SSL certificates
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
//for testing purpose only, accept any dodgy certificate...
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
</code></pre>
|
PHP Addslashes adding double backslashes when escaping a single quote <p>Addslashes seems to be a bit confused. Given the following 2 lines of code</p>
<pre><code>$name = "Dave's test";
$newName = addslashes($name);
</code></pre>
<p>I am <em>expecting</em> $newName to be <strong>"Dave\'s test"</strong> (my one single quote nicely escaped)</p>
<p>However, what I'm <em>getting</em> is <strong>"Dave\\'s test"</strong> (note the DOUBLE backslashes). This contradicts every bit of online documentation I can find on addslashes - and causing me a lot of grief.</p>
<p>I am dumping the before and after addslashes results to the http error log via error_log...</p>
<pre><code>error_log("before=$name after=$newName");
</code></pre>
<p>results...</p>
<pre><code>before=Dave's test after=Dave\\'s test
</code></pre>
<p>Note - this is part of an ajax process, so I can't really 'echo' the results.</p>
<p>Any insights into why addslashes would be double up on the backslases are much appreciated.</p>
<p>FYI: I'm Using PHP 5.2.6 under linux with magic quotes OFF.</p>
| <p>Looks like error_log is calling addslashes internally. After reading the questions posted in reponse to my original question, I created a very trivial script...</p>
<pre><code><?php
$name = "Dave's test";
$newName = addslashes($name);
echo "name=$name. newName=$newName";
error_log("name=$name. newName=$newName");
?>
</code></pre>
<p>Result from the echo:</p>
<pre><code>name=Dave's test. newName=Dave\'s test
</code></pre>
<p>Result from the error_log:</p>
<pre><code>name=Dave's test. newName=Dave\\'s test
</code></pre>
<p>Many thanks to all who took the time to read and comment on this question. This was my first question on Stack Overflow and I was just blown away by the speed of the responses. What a great community! </p>
|
Ruby regular expression help using match to extract pieces of html doc <p>I have an HTML document of this format:</p>
<pre><code><tr><td colspan="4"><span class="fullName">Bill Gussio</span></td></tr>
<tr>
<td class="sectionHeader">Contact</td>
<td class="sectionHeader">Phone</td>
<td class="sectionHeader">Home</td>
<td class="sectionHeader">Work</td>
</tr>
<tr valign="top">
<td class="sectionContent"><span>Screen Name:</span> <span>bhjiggy</span><br><span>Email 1:</span> <span>wmgussio@erols.com</span></td>
<td class="sectionContent"><span>Mobile: </span><span>2404173223</span></td>
<td class="sectionContent"><span>NY</span><br><span>New York</span><br><span>78642</span></td>
<td class="sectionContent"><span>MD</span><br><span>Owings Mills</span><br><span>21093</span></td>
</tr>
<tr><td colspan="4"><hr class="contactSeparator"></td></tr>
<tr><td colspan="4"><span class="fullName">Eddie Osefo</span></td></tr>
<tr>
<td class="sectionHeader">Contact</td>
<td class="sectionHeader">Phone</td>
<td class="sectionHeader">Home</td>
<td class="sectionHeader">Work</td>
</tr>
<tr valign="top">
<td class="sectionContent"><span>Screen Name:</span> <span>eddieOS</span><br><span>Email 1:</span> <span>osefo@wam.umd.edu</span></td>
<td class="sectionContent"></td>
<td class="sectionContent"><span></span></td>
<td class="sectionContent"><span></span></td>
</tr>
<tr><td colspan="4"><hr class="contactSeparator"></td></tr>
</code></pre>
<p>So it alternates - chunk of contact info and then a "contact separator". I want to grab the contact info so my first obstacle is to grab the chunks in between the contact separator. I have already figured out the regular expression using rubular. It is:</p>
<pre><code>/<tr><td colspan="4"><span class="fullName">((.|\s)*?)<hr class="contactSeparator">/
</code></pre>
<p>You can check on rubular to verify that this isolates chunks. </p>
<p>However my big issue is that I am having trouble with the ruby code. I use the built in match function and make prints, but do not get the results I expect. Here is the code:</p>
<pre><code>page = agent.get uri.to_s
chunks = page.body.match(/<tr><td colspan="4"><span class="fullName">((.|\s)*?)<hr class="contactSeparator">/).captures
chunks.each do |chunk|
puts "new chunk: " + chunk.inspect
end
</code></pre>
<p>Note that page.body is just the body of the html document grabbed by Mechanize. The html document is much larger but has this format. So, the unexpected output is below:</p>
<pre><code>new chunk: "Bill Gussio</span></td></tr>\r\n\t<tr>\r\n\t\t<td class=\"sectionHeader\">Contact</td>\r\n\t\t<td class=\"sectionHeader\">Phone</td>\r\n\t\t<td class=\"sectionHeader\">Home</td>\r\n\t\t<td class=\"sectionHeader\">Work</td>\r\n\t</tr>\r\n\t<tr valign=\"top\">\r\n\t\t<td class=\"sectionContent\"><span>Screen Name:</span> <span>bhjiggy</span><br><span>Email 1:</span> <span>wmgussio@erols.com</span></td>\r\n\t\t<td class=\"sectionContent\"><span>Mobile: </span><span>2404173223</span></td>\r\n\t\t<td class=\"sectionContent\"><span>NY</span><br><span>New York</span><br><span>78642</span></td>\r\n\t\t<td class=\"sectionContent\"><span>MD</span><br><span>Owings Mills</span><br><span>21093</span></td>\r\n\t</tr>\r\n\t\r\n\t<tr><td colspan=\"4\">"
new chunk: ">"
</code></pre>
<p>There are 2 surprises here for me:</p>
<p>1) There are not 2 matches that contain the chunks of contact info, even though on rubular I have verified that these chunks should be extracted.</p>
<p>2) All of the \r\n\t (line feeds, tabs, etc.) are showing up in the matches.</p>
<p>Can anyone see the issue here?</p>
<p>Alternatively, if anyone knows of a good free AOL contacts importer, that would be great. I have been using blackbook but it keeps failing for me on AOL and I am attempting to fix it. Unfortunately, AOL has no contacts API yet.</p>
<p>Thank you!</p>
| <p>See <a href="http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege">Can you provide some examples of why it is hard to parse XML and HTML with a regex?</a>
for why this is a bad idea. Use an <a href="http://www.google.com/search?q=ruby%2Bhtml%2Bparser" rel="nofollow">HTML parser</a> instead. </p>
|
Compiler error with `<<` <p>I've been working on getting this program complete where it saves multiple structs to a file, can read them back and edit them, then save them all back to a file. I've been working on the logic of this not to mention lots of help from others and a ton of googling hours... now I am getting a compile error. Any help would be very appreciated.</p>
<p><strong>Code:</strong></p>
<pre><code>template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);
struct InventoryItem {
string Item;
string Description;
int Quantity;
int wholesaleCost;
int retailCost;
int dateAdded;
} ;
int main(void)
{
vector<InventoryItem> structList;
ofstream out("data.dat");
writeVector( out, structList );
return 0;
}
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
{
out << *i; // error C2679
}
}
</code></pre>
<p><strong>Compiler error:</strong></p>
<pre><code>1>.\Project 5.cpp(128) : error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const InventoryItem' (or there is no acceptable conversion)
// listed overload variants skipped
1> while trying to match the argument list '(std::ofstream, const InventoryItem)'
1> .\Project 5.cpp(46) : see reference to function template instantiation 'void writeVector<InventoryItem>(std::ofstream &,const std::vector<_Ty> &)' being compiled
1> with
1> [
1> _Ty=InventoryItem
1> ]
</code></pre>
| <p>You have no <code>operator<<</code> defined that would specify how your <code>InventoryItem</code> should be printed to an output stream. You try to print it and the compiler doesn't know how. You need to define a function like this one:</p>
<pre><code>std::ostream& operator<<(std::ostream &strm, const InventoryItem &i) {
return strm << i.Item << " (" << i.Description << ")";
}
</code></pre>
|
C#: Best way to inject CSS into MSHTML instance? <p>I'm trying to inject some CSS that accompanies some other HTML into a C# managed WebBrowser control. I am trying to do this via the underlying MSHTML (DomDocument property) control, as this code is serving as a prototype of sorts for a full IE8 BHO.</p>
<p>The problem is, while I can inject HTML (via mydomdocument.body.insertAdjacentHTML) and Javascript (via mydomdocument.parentWindow.execScript), it is flat-out rejecting my CSS code. </p>
<p>If I compare the string containing the HTML I want to insert with the destination page source after injection, the MSHTML's source will literally contain everything <em>except</em> for the <code><style></code> element and its underlying source.</p>
<p>The CSS passes W3C validation for CSS 2.1. It doesn't do anything too tricky, with the exception that some background-image properties have the image directly embedded into the CSS (e.g. <code>background-image: url("data:image/png;base64</code> ...), and commenting out those lines doesn't change the result.</p>
<p>More strangely (and I am not sure if this is relevant), was that I was having no problems with this last week. I came back to it this week and, after switching around some of the code that handles the to-be-injected HTML before actual injection, it no longer worked. Naturally I thought that one of my changes might somehow be the problem, but after commenting all that logic out and feeding it a straight string the HTML is still appearing unformatted.</p>
<p>At the moment I'm injecting into the <code><body></code> tag, though I've attempted to inject into <code><head></code> and that's met with similar results.</p>
<p>Thanks in advance for your help!</p>
<p>tom</p>
| <p>Ended up solving this myself:</p>
<pre><code>mshtml.HTMLDocument test = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
//inject CSS
if (test.styleSheets.length < 31) { // createStyleSheet throws "Invalid Argument if >31 stylesheets on page
mshtml.IHTMLStyleSheet css = (mshtml.IHTMLStyleSheet)test.createStyleSheet("", 0);
css.cssText = myDataClass.returnInjectionCSS(); // String containing CSS to inject into the page
// CSS should now affect page
} else {
System.Console.WriteLine("Could not inject CSS due to styleSheets.length > 31");
return;
}</code></pre>
<p>What I didn't realize is that createStyleSheet creates a pointer that is still 'live' in the document's DOM... therefore you don't need to append your created stylesheet back to its parent. I ended up figuring this out by studying dynamic CSS code for Javascript as the implementations are pretty much identical.</p>
|
Dynamic Compiled Plugins in .NET <p>Is there a possibility that I can put some of my code in non-compiled form with my application and then make changes to it on the fly and the application can then just use the new version onwards?</p>
<p>If it is possible (which i secretly know it is using CodeDOM), are there any issue to watch out for using this approach for pluggability (aside from the code protection issue)?</p>
<p>Is there a example available which i can re-use?</p>
| <p>You've already said you know how to do with with CodeDOM - why not just use that?</p>
<p>If you're happy with it being C# code, then <code>CSharpCodeProvider</code> does an admirable job. If you're feeling more adventurous, you might want to consider <a href="http://boo.codehaus.org">Boo</a> - <a href="http://manning.com/rahien/">read Ayende Rahien's book on building DSLs in Boo</a> for more information and advice.</p>
<p>For an example of using <code>CSharpCodeProvider</code>, you could download Snippy from my <a href="http://csharpindepth.com/Downloads.aspx">C# in Depth web site</a>. Basically Snippy lets you type in a code snippet and run it, without bothering to declare a class etc. It doesn't do much more than build and run code, so it's a fairly handy example :)</p>
<p>For plenty more examples, <a href="http://www.google.co.uk/search?q=site:stackoverflow.com%2Bcsharpcodeprovider">search for CSharpCodeProvider on Stack Overflow</a>. Here's a short but complete one - code for "hello world" is compiled and then executed.</p>
<pre><code>using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
class Test
{
public static void Main(string[] args)
{
string code = @"
using System;
class CodeToBeCompiled
{
static void Main()
{
Console.WriteLine(""Hello world"");
}
}";
var codeProvider = new CSharpCodeProvider();
var parameters = new CompilerParameters
{
GenerateExecutable = true,
OutputAssembly = "Generated.exe"
};
var results = codeProvider.CompileAssemblyFromSource
(parameters, new[] { code });
results.CompiledAssembly.EntryPoint.Invoke(null, null);
}
}
</code></pre>
|
Migrating / Upgrading NUnit to Team system <p>We are working on a C# windows application that is being upgraded from <strong>.Net</strong> <strong>1.1</strong> to <strong>3.5</strong>.
The application uses <strong>NUnit</strong> for <strong>automated testing</strong> and we are in turn changing this to <strong>Team System 2008</strong>.</p>
<ul>
<li>It seems to me that NUnit uses
similar <strong>attributes</strong> and code for
<strong>assertion</strong>?</li>
<li>What is the best way to <strong>upgrade</strong> /
<strong>migrate</strong> this code and are their any
<strong>procedures</strong> <strong>to</strong> <strong>avoid</strong>?</li>
</ul>
| <p>Here's how attributes map from NUnit to MSTest</p>
<pre><code>[TestFixture] -> [TestClass]
[Test] -> [TestMethod]
[SetUp] -> [TestInitialize]
[TearDown] -> [TestCleanup]
[TestFixtureSetUp] -> [ClassInitialize]
[TestFixtureTearDown] -> [ClassCleanup]
</code></pre>
<p>You can consider adding something like </p>
<pre><code>using TestClassAttribute = NUnit.Framework.TestFixtureAttribute;
using TestAttribute = NUnit.Framework.TestMethodAttribute;
</code></pre>
<p>to the top of your test classes.</p>
|
Getting the logical path in VIM when there's a symlink <p>I have the following setup:</p>
<pre><code>mkdir /1
mkdir /1/2
mkdir /1/2/3
ln -s /1/2/3 /1/3
</code></pre>
<p>If I do <code>cd /1/3</code>, and then <code>pwd</code>, I get <code>/1/3</code>. If I use <code>pwd -P</code>, I can get <code>/1/2/3</code>, or <code>pwd -L</code> to force <code>/1/3</code>. </p>
<p>In VIM, I'm looking for a way to get the <code>/1/3</code>.<br />
If I open a file in <code>/1/3/foo.txt</code>, and I use something like <code>fnamemodify(bufname(winbufnr(0)), ':p:h')</code>, it returns <code>/1/2/3</code>.<br />
How can I tell it to give me the same directory that <code>pwd</code> would give?</p>
| <p>It appears you can't, other than via <code>system('pwd -L')</code>. According to the <a href="http://groups.google.com/group/vim%5Fuse/browse%5Fthread/thread/602b96cd5441fb03/751fda406ec5940a?lnk=gst&q=resolve%2Bsymlinks#751fda406ec5940a">vim_use mailing list</a> Vim automatically resolves symlinks nowadays.</p>
<p>See the text around <code>:h E773</code> for rationale; if Vim went by symlinks instead of resolved filename, it'd be possible to have the same file open in two buffers under two different names, and Vim would become confused trying to figure out where the swap file should be. See also in <code>:h version7.txt</code>:</p>
<blockquote>
<p>Unix: When editing a file through a symlink the swap file would use the name
of the symlink. Now use the name of the actual file, so that editing the same
file twice is detected.</p>
</blockquote>
|
What is "tagged memory"? <p>What is "tagged memory" and how does it help in reducing program size?</p>
| <p>You may be referring to a <a href="http://en.wikipedia.org/wiki/Tagged_union" rel="nofollow">tagged union</a>, or more specifically a hardware implementation like the tagged architecture used in LISP machines. Basically a method for storing data with type information.</p>
<p>In a LISP machine, this was done in-memory by using a longer word length and using some of the extra bits to store type information. Handling and checking of tags was done implicitly in hardware.</p>
<p>For a type-safe C++ implementation, see boost:variant.</p>
|
What is the equivalent of glDrawPixels() in OpenGL ES 1.1? <p>Can anyone tell me the equivalent of <a href="http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=0650&db=man&fname=/usr/share/catman/g_man/cat3/OpenGL/gldrawpixels.z" rel="nofollow"><code>glDrawPixels()</code></a> in OpenGL ES 1.1?</p>
| <p>You're forced to use a texture.</p>
|
vs 2008 javascript intellisense in XML file problem <p>I am trying to get javascript intellisense to work for jQuery in a .xml file. I've already used a custom XSD to provide intellisense for the XML. Under the tag, I have a mixture of HTML and javascript which are enclosed by . And it is all greyed out so no intellisense there.</p>
<p>Adding a /// does not help as well.</p>
<p>I would really like to be able to have intellisense when writing javascript in the XML file.</p>
| <p><a href="http://blogs.msdn.com/webdevtools/archive/2008/11/07/hotfix-to-enable-vsdoc-js-intellisense-doc-files-is-now-available.aspx" rel="nofollow">http://blogs.msdn.com/webdevtools/archive/2008/11/07/hotfix-to-enable-vsdoc-js-intellisense-doc-files-is-now-available.aspx</a></p>
<p>This is a hot fix for java script intellisense that may help.</p>
|
What are the correspondent of Servlet and Applet in .NET? <p>I am trying to understand what's the correspondent of servlets and applets in .NET but I don't have much experience in JAVA.</p>
<p>I am thinking applets could be compared to the silverlight stuff, meaning you code independently from the browser, but then it's not like that since (between other things) you can re-use an applet outside the browser.</p>
<p>I need to demonstrate web technologies for a JAVA-based college-course and I can use .NET <em>as long as I can demonstrate the same stuff</em>. </p>
<p>Any help or ideas appreciated! </p>
| <p>In .Net, HTTP handlers (.ashx) are probably the closest thing to a servlet. As for applets, there isn't a direct equivelent, but siverlight is probably the closest (although its closer to Flash/JavaFX)</p>
|
Create image with transparent background using GDI+? <p>I'm trying to create an image with a transparent background to display on a web page.<br />
I've tried several techniques but the background is always black.<br />
How can I create a transparent image and then draw some lines on it ?</p>
| <p>Call <code>Graphics.Clear(Color.Transparent)</code> to, well, clear the image. Don't forget to create it with a pixel format that has an alpha channel, e.g. <code>PixelFormat.Format32bppArgb</code>. Like this:</p>
<pre><code>var image = new Bitmap(135, 135, PixelFormat.Format32bppArgb);
using (var g = Graphics.FromImage(image)) {
g.Clear(Color.Transparent);
g.DrawLine(Pens.Red, 0, 0, 135, 135);
}
</code></pre>
<p>Assumes you're <code>using</code> <code>System.Drawing</code> and <code>System.Drawing.Imaging</code>.</p>
<p>Edit: Seems like you don't actually need the <code>Clear()</code>. Just creating the image with an alpha channel creates a blank (fully transparent) image.</p>
|
How does Google App Engine compare to web hosting plans? <p>Google App Engine offers free quotas of 1 GB outbound traffic per day and 6.5 CPU-hours (based on a 1.2 GHz Intel x86 processor) per day.</p>
<p>How do those free quotas compare to web hosting plans? For example, the traffic supported by the free quotas -- is that generally higher or less than the traffic supported by a typical $5/mo shared hosting account?</p>
<p>Above the free quotas, Google charges $0.12 per GB outgoing traffic, $0.10 per GB incoming traffic, $0.10 per CPU-hour, $0.15 per GB storage per month.</p>
<p>How do those numbers translate to normal web hosting plans? For example, the traffic that can be supported by a $40/mo VPS plan and $200/mo dedicated server plan, what would they cost on Google App Engine?</p>
<p>I know it depends on a lot of factors, but if anyone has any ballpark estimates or experiences they're willing to share I'd really appreciate it.</p>
<p>I'm trying to decide between App Engine and standard web hosting for a DB-backed Python site. The site will start small, but if the traffic grows I want to see which would be a better option long term.</p>
| <p>As you say, it depends on a lot. Not just the site you want to host, but who, specifically, you're comparing it to. To give you a rough idea, I host a site that gets from 20k to 30k pageviews a day on App Engine, and it costs me 17c a week. That's for extra storage over the default quota - all other quotas are well within the free zone.</p>
<p>As far as specific comparisons go, if we look at <a href="http://www.linode.com/index.cfm">Linode</a>, for example, their base plan is $20 for 12GB of storage and 120GB transfer per month. At App Engine prices, that would cost you at most $16.20 per month - assuming it was all outgoing traffic. If you do less than that in a month, it costs you less. Obviously, you don't have all the versatility on App Engine that you have with a VPS, but you also have better scalability and reliability.</p>
<p>The comparison is fairly easy to other hosting services. I think App Engine will generally come out ahead, so mostly the decision comes down to if your app is suitable for App Engine.</p>
|
Executable dll loading (x32, x64): pick the right one <p>I have a large project with several 3rd party libraries. I want to build everything for 32 and for 64 bit architecture. Several libraries create shared libs (dlls). What is the best way to provide those dlls to the compiled executables from my project? I thought off I can put all those dlls into a directory which is added to the PATH variable. But most dlls created from the 3rd party libs are named in the same way under 32 and 64 bit compilation, so I cannot put them in one directory. Can I create two directories, one for the 32 bit dlls and one for the 64 bit dlls and the executable picks the right dlls?
Or have you a better idea to let my executable load the right dlls?
Thanks!</p>
| <p>Since a 32-bits executable cannot pick 64-bits DLLs and vice-versa. You just have one directory with everything 32-bits (executable + DLLs) and another one with everything 64-bits.</p>
|
readv(), writev(), WSARecv(), WSASend() <p>I hope you can help me out. </p>
<p>I'm trying to send packets of 1000 bits across a network via TCP/IP and I was hoping to be able to use the Overlapped I/O technique in both Cygwin and Windows as well.</p>
<p>In Cygwin, I am trying to use the "readv() and writev()" function calls to send 1000 bits across while in Windows, I am trying to use the WSASend() and WSARecv() APIs in the winsock2.h header file. </p>
<p>It seems that I can ONLY send 1000 bits from Cygwin(client.cpp) to Windows(server.cpp). More than 1000 bits, and I encounter unexpected results. It seems as though the bits get wrapped around or overwritten.</p>
<p>I've search all over the internet but it seems that no one has ever tried using this approach to things as I did and thus I am seeking your help in this, please.</p>
<p>Thank you and best regards,
Cornelius</p>
| <p>If you want to use overlapped I/O on windows then you might like to take a look at some articles I wrote over at The Code Project which might provide you with a starting point. These use IO Completion Ports which are the most efficient way of doing overlapped I/O on Windows and come with complete source code. There's a link to the articles and the latest source <a href="http://www.serverframework.com/products---the-free-framework.html" rel="nofollow">here</a>.</p>
<p>From your brief problem description it's hard to tell exactly what might be going wrong. It's most likely that you are assuming that your reads will read the same amount of data that you are writing and this just isn't the case with TCP; TCP is a stream of bytes and your reads need to take that into account and loop accordingly until you have reassembled a complete 'message'.</p>
|
mysql dump tables only <p>In my database I have some tables and views.
How can I export all the tables (and not the views) from my database from command line?</p>
| <p>The current implementation mysqldump won't create dumps without views -- and furthermore, (last time I checked) views are actually created twice -- once as a table, then the table is dropped and replaced with a view. So you can't just filter out the "CREATE VIEW" command, unless that behavior has been modified.</p>
<p>However, mysqldump will take a list of tables as parameters following the database name. Something like this:</p>
<pre><code>mysqldump -ujoe -pmysecret joesdb posts tags comments users
</code></pre>
|
how to get the MS word screen position from the Ribbon control? <p>I want to get the word position, so that I can position my dialogs relative to the word on the screen in the event handler in the ribbon control</p>
<p>private void button1_Click(object sender, RibbonControlEventArgs e)</p>
<p>How to get that? I mean there is no location or Point property which tells the screen coordinates.</p>
| <p>I've come across this same issue. Not sure why, but the RibbonControl class didn't provide a Location property.</p>
<p>It's possible that coordinates are housed somewhere within the COM objects, but I'm no Excel expert.</p>
<p>Anyone else come across this?</p>
|
Showing big images by DirectX faster? <p>as developer of industrial vision applications I frequently have rather clunky images like 6000x4000Pixels and bigger.</p>
<p>While the camera and imageprocessing is working on a steady stream of new images (and this processing is the main task) I would like to allow the user to comfortably view some other image in parallel.</p>
<p>Doing this on the processor (GDI etc.) steals way too much performance. For example it takes us 0.2 seconds to analyse the image but 0.8 seconds to show it with a single zoom (resized to fit some control), let alone let the user move on and dive into it.</p>
<p>Since Photoshop allows to show and zoom by the help of the graphic card's very fast memory and processing I wondered if anyone can give me an idea if and how I can experiment on this in my own code:
push data to graphic card (how long may this take for my 76MB of rgb-data?) and let it show in some control without much effort to zoom and move in it by user to the control/card for user interaction.</p>
<p>No need for 3D looks, just moving and resizing in a 2D-rgb-image.
Aim is to enable fast and comfortable viewing with low processor load. </p>
<p>==> Is this possible (as texture or something the like)?
==> Are there limitations with current low-end-3D-cards of >=256MB?
==> can somebody suggest some durations to expect (copy data, zooming)?</p>
| <p>You're going to be limited by max texture size (which varies from card to card), so you'll have to subdivide your big image into several smaller textures. Getting the actual texture data to your video memory should be plenty fast as long as the card is AGP or PCI-E.</p>
|
How to search for one value in any column of any table inside one MS-SQL database? <p>Is there a way to search for one value (in my case it is a UID of the type char(64)) inside any column of any table inside one MS-SQL database?</p>
<p>I'm sitting in front of a huge database without any idea how the tables had to be linked together. To find that out I'd like to list all tables and there columns that contain a certain value in any row. Is that possible?</p>
<p><em>One way could be to just dump the entire database into a text file and than use any text-editor to search for the value - but this would be pure pain if the database is too huge.</em></p>
| <p>Thanks for the question as this is a really useful topic. I will use this myself also now for reasons including the one you put forward. :-)</p>
<blockquote>
<p>How to search all columns of all
tables in a database for a keyword?</p>
</blockquote>
<p><a href="http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm">http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm</a></p>
<p>Andrew</p>
<p>-Edit, here's the actual T-SQL, in case of link rot: </p>
<pre><code>CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
</code></pre>
|
Block elements inside a product list <p>I have a page which contains a products' list.</p>
<p>I decided to use an unordered list instead of divs to display the products but there is a problem with that, since I can't insert other block level elements in the <code><li></code> to achieve some specific design I want (an image with some background, bordered descriptions, floated links etc etc....).</p>
<p>My questions are:</p>
<ol>
<li>Is it possible and semantically correct to use inline elements in the <code><li></code> (such as <code><span></code>) to achieve such visualisations?</li>
<li>Is it semantically correct to use a div instead (and H2, P tags in it)?</li>
<li>Generaly, how would you markup a product list in which every product contains:
<ol>
<li>an image;</li>
<li>the product's name; and</li>
<li>a link "more".</li>
</ol></li>
</ol>
<p>Thanks in advance.</p>
| <ol>
<li>The most important part of your HTML is that it makes semantic sense. If you want to display an inline element as a block level element that's perfectly acceptable, provided the HTML behind it makes sense. This is an important part of being able to separate content from presentation.</li>
<li>Generally, if you can describe something as a list then it <em>should</em> be an HTML list, either a <code><ul></code>, <code><ol></code> or <code><dl></code>. It's not a strict rule, but a good guideline. If you don't want to follow that guideline then it's ok to use <code><div></code>s, as long as you don't put block level elements inside inline elements.</li>
<li><p>Keeping the markup as simple as possible I would say it should look as follows:</p>
<pre><code><dl>
<dt>Product name</dt>
<dd>
<img src="product.jpg" alt="Product name" />
Description.
<a class="read-more" href="#">Read more about Product name</a>
</dd>
</dl>
</code></pre></li>
</ol>
<p>For some additional information on styling <code><dl></code>s <a href="http://www.maxdesign.com.au/presentation/definition/" rel="nofollow">Max Design's "Definition lists - misused or misunderstood?"</a> has a list of different styles that might be useful.</p>
|
How to use Dojo in my Django application? <p>How do I use Dojo in my Django application? Please show me comprehensive examples on how to do this.<br />
Any links to sample code for this combination will be appreciated</p>
<p>NB: I also don't mind examples using Dojango.</p>
| <p>You may have seen this blog post:
<a href="http://blog.uxebu.com/2008/07/26/ajax-with-dojango/">http://blog.uxebu.com/2008/07/26/ajax-with-dojango/</a></p>
<p>You can also try the various examples, blog articles and docs here.
<a href="http://code.google.com/p/dojango/">http://code.google.com/p/dojango/</a></p>
|
Why does the UI thread get blocked when running something in a different thread? <p>Suppose I have normal <code>button.Click</code> event. </p>
<p>If I try to access UI elements from inside of this event I could potentially got unwanted behavior - or even an exception (when debugging). The usual exception in such a scenario is: <code>...cannot access UI elements from thread different than they were created in</code>.</p>
<p>Since this is another thread (different than the main) why my UI is blocked when I perform time consuming operations in an event?</p>
| <p>What is the framework here? winform? WPF?</p>
<p>In winform (for a click event), you <em>are</em> on the UI thread. So you <em>can</em> just talk to the UI from the click event. If something else is happening, then there is something wrong. Are you sure you aren't in a timer-callback?</p>
<p>In the more general sense, you can use <code>InvokeRequired</code>/<code>Invoke</code> etc to pass control to the UI thread.</p>
|
Time Zones <p>I know this isn't specific to PHP, but what's the point of using timezones listed like this :<a href="http://us2.php.net/manual/en/timezones.america.php" rel="nofollow">http://us2.php.net/manual/en/timezones.america.php</a>? For example "America/Indianapolis" and "America/New_York". What is the problem with EST, EDT, CST, CDT, &c?</p>
| <p><code>'America/New_York'</code> doesn't depend on the date. <code>EST</code> is only valid in winter, while in summer you have to change it to <code>EDT</code>. Other problem with 3 letter codes is, that there are conflicts. <code>EST</code> means Eastern Standard Time, but it might be in America or Australia. </p>
|
Java: Rationale of the Cloneable interface <p>Why wasn't the <code>.clone()</code> method specified in the <code>java.lang.Cloneable</code> interface ?</p>
| <p>Basically, it's a broken interface. Ken Arnold and Bill Venners discussed it in <a href="http://www.artima.com/intv/issues3.html">Java Design Issues</a>.</p>
<p>Arnold:</p>
<blockquote>
<p>If I were to be God at this point, and many people are probably glad I am not, I would say deprecate <code>Cloneable</code> and have a <code>Copyable</code>, because <code>Cloneable</code> has problems. Besides the fact that it's misspelled, <code>Cloneable</code> doesn't contain the <code>clone</code> method. That means you can't test if something is an instance of <code>Cloneable</code>, cast it to <code>Cloneable</code>, and invoke <code>clone</code>. You have to use reflection again, which is awful. That is only one problem, but one I'd certainly solve. </p>
</blockquote>
|
Tweaking asp.net mvc <p>I really love the "one model in - one model out" idea of Fubu MVC. A controller would look something like this</p>
<pre><code>public class MyController
{
public OutputModel MyAction(InputModel inputModel)
{
//..
}
}
</code></pre>
<p>and the service locator would automagically fill in all the required dependencies in the constructor.</p>
<p>This makes the controller very easy to test.</p>
<p>So my question is: How would you go about tweaking asp.net mvc to allow this simplicity in the controllers ?</p>
| <p>What you're looking for the is the ControllerActionInvoker. You'll have to implement your own and override/take over handling a lot of the pipeline work that ASP.NET MVC.</p>
<p>For reference, check out Jonathon Carter's 2-part post on doing ControllerActionInvokers:
<a href="http://lostintangent.com/2008/07/03/aspnet-mvc-controlleractioninvoker-part-1/" rel="nofollow">http://lostintangent.com/2008/07/03/aspnet-mvc-controlleractioninvoker-part-1/</a></p>
<p>and</p>
<p><a href="http://lostintangent.com/2008/07/07/aspnet-mvc-controlleractioninvoker-part-2/" rel="nofollow">http://lostintangent.com/2008/07/07/aspnet-mvc-controlleractioninvoker-part-2/</a></p>
<p>Also, the Oxite team did this in the 2nd release of Oxite, you can check out their source here:</p>
<p><a href="http://oxite.codeplex.com/SourceControl/changeset/view/30544" rel="nofollow">http://oxite.codeplex.com/SourceControl/changeset/view/30544</a></p>
<p>Here's a link directly to their ControllerActionInvoker implementation:
<a href="http://oxite.codeplex.com/SourceControl/changeset/view/30544#442766" rel="nofollow">http://oxite.codeplex.com/SourceControl/changeset/view/30544#442766</a></p>
|
python code convention using pylint <p>I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (<code>const-rgx</code>) instead of the variable name regex (<code>variable-rgx</code>). How to match the variable name with <code>variable-rgx</code>? Or should I extend <code>const-rgx</code> with my <code>variable-rgx</code> stuff?</p>
<p>e.g.<br />
<code>C0103: 31: Invalid name "settings" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)</code></p>
| <blockquote>
<p>Somehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx).</p>
</blockquote>
<p>Are those variables declared on module level? Maybe that's why they are treated as constants (at least that's how they should be declared, according to PEP-8).</p>
|
Capture multiple key downs in C# <p>How can I capture multiple key downs in C# when working in a <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow">Windows Forms</a> form?</p>
<p>I just can't seem to get both the up arrow and right arrow at the same time.</p>
| <p>A little proof-of-concept code for you, assuming <code>Form1</code> contains <code>label1</code>:</p>
<pre><code>private List<Keys> pressedKeys = new List<Keys>();
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
pressedKeys.Add(e.KeyCode);
printPressedKeys();
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
pressedKeys.Remove(e.KeyCode);
printPressedKeys();
}
private void printPressedKeys()
{
label1.Text = string.Empty;
foreach (var key in pressedKeys)
{
label1.Text += key.ToString() + Environment.NewLine;
}
}
</code></pre>
|
How to respond with a custom error response in Apache 2.2 (c++)? <p>I am currently trying to have my Apache module respond with custom error messages, so that a 400 for example contains additional information like "The coordinates are out of bounds".</p>
<p>I found multiple sources on Google saying that it is possible, but none could tell me how. So is there some function that would allow me something like:</p>
<pre><code>return apache_error( 400, "Coordinate %d is out of bounds.", coord.x );
</code></pre>
<p>?</p>
<p>Thanks in advance.</p>
| <p>You can set it on the status_line member of request_rec.</p>
<pre><code>snprintf(buf, buf_size, "%d Coordinate %d is out of bounds", 400, coord.x);
req->status_line = buf;
req->status = 400;
</code></pre>
|
LINQ In Line Property Update During Join <p>I have two obects, A & B for this discussion. I can join these objects (tables) via a common relationship or foreign key. I am using linq to do this join and I only want to return ObjectA in my result set; however, I would like to update a property of ObejctA with data from ObjectB during the join so that the ObjectAs I get out of my LINQ query are "slightly" different from their original state in the storage medium of choice.</p>
<p>Here is my query, you can see that I would just like to be able to do something like objectA.SomeProperty = objectB.AValueIWantBadly</p>
<p>I know I could do a new in my select and spin up new OBjectAs, but I would like to avoid that if possible and simply update a field.</p>
<pre><code>return from objectA in GetObjectAs()
join objectB in GetObjectBs()
on objectA.Id equals objectB.AId
// update object A with object B data before selecting it
select objectA;
</code></pre>
| <p>Add an update method to your ClassA</p>
<pre><code>class ClassA {
public ClassA UpdateWithB(ClassB objectB) {
// Do the update
return this;
}
}
</code></pre>
<p>then use</p>
<pre><code>return from objectA in GetObjectAs()
join objectB in GetObjectBs()
on objectA.Id equals objectB.AId
// update object A with object B data before selecting it
select objectA.UpdateWithB(objectB);
</code></pre>
<p><strong>EDIT</strong>:</p>
<p>Or use a local lambda function like:</p>
<pre><code>Func<ClassA, ClassB, ClassA> f = ((a,b)=> { a.DoSomethingWithB(b); return a;});
return from objectA in GetObjectAs()
join objectB in GetObjectBs()
on objectA.Id equals objectB.AId
select f(objectA , objectA );
</code></pre>
|
How can I generate a client proxy for a WCF service with an HTTPS endpoint? <p>Might be the same issue as this previuos question: <a href="http://stackoverflow.com/questions/703698/generating-wcf-proxy-against-untrusted-ssl-endpoint">WCF Proxy</a> but not sure...</p>
<p>I have an HTTPS service connfigured to use transport security and, I hope, Windows credentials. The service is only accessed internally (i.e. within the intranet). The configuration is as follows:</p>
<pre><code><configuration>
<system.serviceModel>
<services>
<service name="WCFTest.CalculatorService" behaviorConfiguration="WCFTest.CalculatorBehavior">
<host>
<baseAddresses>
<add baseAddress = "https://localhost:8000/WCFTest/CalculatorService/" />
</baseAddresses>
</host>
<endpoint address ="basicHttpEP" binding="basicHttpBinding" contract="WCFTest.ICalculatorService" bindingConfiguration="basicHttpBindingConfig"/>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBindingConfig">
<security mode="Transport">
<transport clientCredentialType = "Windows"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="WCFTest.CalculatorBehavior">
<serviceAuthorization impersonateCallerForAllOperations="false" principalPermissionMode="UseWindowsGroups" />
<serviceCredentials >
<windowsAuthentication allowAnonymousLogons="false" includeWindowsGroups="true" />
</serviceCredentials>
<serviceMetadata httpsGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
</code></pre>
<p>When I run the service I can't see the service in IE. I get a "this page can not be displayed" error. If I try and create a client in VS2008 via the "add service reference" wizard I get this error:</p>
<blockquote>
<p>There was an error downloading
'https://localhost:8000/WCFTest/CalculatorService/'.
There was an error downloading
'https://localhost:8000/WCFTest/CalculatorService/'.
The underlying connection was closed:
An unexpected error occurred on a
send. Authentication failed because
the remote party has closed the
transport stream. Metadata contains a
reference that cannot be resolved:
'https://localhost:8000/WCFTest/CalculatorService/'.
An error occurred while making the
HTTP request to
https://localhost:8000/WCFTest/CalculatorService/.
This could be due to the fact that the
server certificate is not configured
properly with HTTP.SYS in the HTTPS
case. This could also be caused by a
mismatch of the security binding
between the client and the server. The
underlying connection was closed: An
unexpected error occurred on a send.
Authentication failed because the
remote party has closed the transport
stream. If the service is defined in
the current solution, try building the
solution and adding the service
reference again.</p>
</blockquote>
<p>I think I'm missing some fundamental basics here. Do I need to set up some certificates? Or should it all just work as it seems to do when I use NetTcpBinding?</p>
<p>Thanks</p>
| <p>ng5000,</p>
<p>Seems like you may have another issue here (maybe IIS). Do you have any issues with transport-level security off? I would also make sure you can get to the web address in IE before checking the WCF stuff. Sounds like a IIS setting that's not correct in the security tab.</p>
<p>If its still a problem try building the proxy with transport-level security off and then go back and change both configs to transport level windows security and see what happens.</p>
<p>-Bryan</p>
|
Append new JavaDoc to existing from super method <p>I have generated an Interface which is very well documented. Every method does have his own JavaDoc. The clases which implement this Interface can have little differents in their logic.</p>
<p>How can i add JavaDoc to the existing JavaDoc from the super class. The key word </p>
<pre><code>/**
* {@inheritDoc}
*/
</code></pre>
<p>only set the javaDoc of the super class to the current method. But when i try to add some words, the JavaDoc of the super method is gone, like</p>
<pre><code>/**
* {@inheritDoc}
* These value depends on...
*/
</code></pre>
<p>Does anybody have a idea how i can update the JavaDoc of a super method, without deleting.</p>
<p><strong>EDIT:</strong></p>
<p>Regarding to Brian Agnew answer, which is good but not a real answer ;)</p>
<p>You also can have the same problem when you want to overwrite an existing method, like paint() in Swing, and want to describ how to initialize or handle the draw behaviour from outside.
This is not only for interface description.</p>
| <p>I guess that when you need to add something to javadoc, you changed something. So maybe it will be correct to write javadoc in exactly same way.</p>
<pre><code>/**
* Enahnced swing paint for my cool component
* @see JButton.paint();
*/
public void paint(){
super.paint(){
//my stuff
}
</code></pre>
|
Short/quick explanation of .net mvc <p>What would be the shortest explanation for .net mvc (for a manager to understand at a high level, how it works, benefits etc).</p>
| <p>You might start <a href="http://www.asp.net/mvc/" rel="nofollow">here</a>.</p>
<blockquote>
<p><strong>ASP.NET MVC</strong> enables you to build Model
View Controller (MVC) applications by
using the ASP.NET framework. ASP.NET
MVC is an alternative, not a
replacement, for ASP.NET Web Forms
that offers the following benefits: </p>
<ul>
<li>Clear separation of concerns </li>
<li>Testability - support for Test-Driven Development</li>
<li>Fine-grained control over HTML and JavaScript</li>
<li>Intuitive URLs</li>
</ul>
</blockquote>
<p>As curtisk points out in his answer, <a href="http://en.wikipedia.org/wiki/Model-view-controller" rel="nofollow">wikipedia</a> has a good description as well:</p>
<blockquote>
<p><strong>Modelâviewâcontroller (MVC)</strong> is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other.</p>
</blockquote>
|
Why do I see HASH(0xABCDEF) in my Perl output? <p>I am running perl, v5.6.1 built for sun4-solaris-64int</p>
<p>I am calling print on an array:</p>
<pre><code>print "@vals\n";
</code></pre>
<p>and the output looks like:</p>
<pre><code>HASH(0x229a4) uid cn attuid
</code></pre>
<p>or another example:</p>
<pre><code>@foo = {};
push(@foo, "c");
print "@foo I am done now\n";
</code></pre>
<p>with output of:</p>
<pre><code>HASH(0x2ece0) c I am done now
</code></pre>
<p>Where is <code>HASH(0x2ece0)</code> coming from?</p>
| <p>Your braces in @foo = {} are creating it. The braces create an unnamed hash reference.</p>
<p>If you want to set @foo to an empty list, use @foo = ()</p>
|
Why are my drop downs not working in ie7? <p>If you view this page: <a href="http://www.sussexjewelers.com/product_search.php?cid=69" rel="nofollow">http://www.sussexjewelers.com/product_search.php?cid=69</a></p>
<p>The drop down menus (horizontal green bar) do not drop down in ie7. They do drop down in ie6, firefox, and chrome. Also if you view the homepage the same drop downs DO work in ie7. I cannot figure out why they are not working on this page in ie7. They are pure CSS drop down menus. </p>
<p>Any help is appreciated.</p>
<p>Thanks!</p>
| <p>Your <code><style></code> and <code><script></code> tags should be inside your <code><head></code> tag, not outside your <code><html></code> tag.</p>
<p>Also add a DOCTYPE</p>
<p>XHTML</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
</code></pre>
<p>HTML 4</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
</code></pre>
<p>Take your pick.</p>
|
How method hiding works in C#? <p>Why the following program prints</p>
<pre><code>B
B
</code></pre>
<p>(as it should)</p>
<pre><code>public class A
{
public void Print()
{
Console.WriteLine("A");
}
}
public class B : A
{
public new void Print()
{
Console.WriteLine("B");
}
public void Print2()
{
Print();
}
}
class Program
{
static void Main(string[] args)
{
var b = new B();
b.Print();
b.Print2();
}
}
</code></pre>
<p>but if we remove keyword 'public' in class B like so:</p>
<pre><code> new void Print()
{
Console.WriteLine("B");
}
</code></pre>
<p>it starts printing</p>
<pre><code>A
B
</code></pre>
<p>?</p>
| <p>When you remove the <code>public</code> access modifier, you remove any ability to call B's <code>new Print()</code> method from the <code>Main</code> function because it now defaults to <code>private</code>. It's no longer accessible to Main.</p>
<p>The only remaining option is to fall back to the method inherited from A, as that is the only accessible implementation. If you were to call Print() from within another B method you would get the B implementation, because members of B would see the private implementation.</p>
|
Adding NAPDEF on Nokia <p>I am trying to add a new access point on a Nokia S60 device, but I am a little bitt puzzled on how to do it.
According to the <a href="http://www.forum.nokia.com/info/sw.nokia.com/id/b5a43a09-2d4b-4ea9-ad76-ecee12913ac7/OMA%5FDM%5FManagement%5FObject%5Ffor%5FConnectivity%5FSettings%5Fv1%5F1%5Fen.pdf.html" rel="nofollow">spec</a> a node should be added at the following root:</p>
<pre><code>./AP/<X>
</code></pre>
<p>Whenever I try to add a node I get a status code 404 meaning that it could not be found. If I try to create an AP that already exists instead I get a status code 418 - it already exists.</p>
<p>The generated xml looks like this:</p>
<pre><code><Add>
<CmdID>17</CmdID>
<Item>
<Target>
<LocURI>./AP/testAP</LocURI>
</Target>
<Meta>
<Format>node</Format>
<Type>syncml:metinf</Type>
</Meta>
</Item>
</Add>
</code></pre>
<p>Using funambol I have also queried the whole ./AP tree and there exists a lot of access point already, all with names like APId00X.</p>
<p>I have tried using other names for my AP on the form APId00X with no luck either.</p>
<p>Does anyone know what it takes to create an AP on a S60 device?</p>
| <p>It's not exactly an answer to your question but you might want to run some Symbian C++ code on the device to add the access point, if you can't find a way to do it successfully with OMA-DM.</p>
<p>If that works better, you may still be able to work around the problem by using OMA-DM to install the .sis file containing your code, run it and uninstall it.</p>
<p>It's ugly but there is a higher probability that Nokia actually tests each steps before releasing phones.</p>
|
Building RAD7 project from command line <p>Hey
We have existing projects set with compilation dependencies in a RAD7 IDE.
Is it possible to create automated build script from the existing project structure?
We have IBM portal projects and regular WEB and enterprise projects.</p>
<p>Maven and Ant are possible solutions but can we use these tools to build existing projects
from command line without using the IDE itself? </p>
<p>Also is it possible to call RAD \ eclipse core compilation from command line or API?</p>
<p>Thanks </p>
| <p>You need to look into "headless mode". That's basically running the IDE to perform its work without the IDE showing up.</p>
<p>I don't have any direct experience but one of the teams in our lab used RAD in headless mode to automate builds for an Eclipse/System-z interface.</p>
|
How can I know the address of owner object in C++? <p>I would like to create in C++ a Notifier class that I will use in other objects to notify various holders when the object gets destroyed. </p>
<pre><code>template <class Owner>
class Notifier<Owner> {
public:
Notifier(Owner* owner);
~Notifier(); // Notifies the owner that an object is destroyed
};
class Owner;
class Owned {
public:
Owned(Owner* owner);
private:
Notifier<Owner> _notifier;
};
</code></pre>
<p>My point is that as I have a dense and complicated object graph, I'd like to avoid storing the address of the owned object in the notifier. Is there a way to change my notifier class so that it can deduce the owned object's address from its own address and an offset that would be computed at compile time?</p>
<p>Note also that any object may have to notify several 'owners', possibly from the same class.</p>
<p>Thanks.</p>
| <p>Take a look at the <a href="http://www.vincehuston.org/dp/observer.html" rel="nofollow">GoF Observer Design Patter</a>.</p>
|
open_basedir not having any effect <p>For my web hosting panel, users need to be blocked from accessing files outside their own directory (<code>/var/www/u/s/username</code>). I tried to use this line in <code>httpd.conf</code> to prevent people from going up a directory.</p>
<pre><code><Directory /var/www/users/>
php_admin_value open_basedir .:/usr/lib/php5
</Directory>
</code></pre>
<p>But in <code>php.ini</code>, it seems to have no effect. What am I doing wrong?</p>
| <p>It might be a silly suggestion, but have you restarted the webserver after making the php.ini changes?</p>
<p>Another method you might try using is to append a file using the "auto_prepend_file" directive to include a script to tighten up the open_basedir directive to the current users directory:</p>
<p>From PHP.net (<a href="http://www.php.net/manual/en/ini.sect.safe-mode.php" rel="nofollow">http://www.php.net/manual/en/ini.sect.safe-mode.php</a>)</p>
<blockquote>
<p>As of PHP 5.3.0 open_basedir can be tightened at run-time. This means that if open_basedir is set to /www/ in php.ini a script can tighten the configuration to /www/tmp/ at run-time with ini_set()</p>
</blockquote>
<p><strong>ADDITIONAL SUGGESTION:</strong></p>
<p>The Apache configuration will need to be set up properly for INI overrides to be effective. Ensure that you have "AllowOverride Options" or "AllowOverride All" set in the Apache config for your Server or Virtual Host. </p>
<p><a href="http://us2.php.net/configuration.changes" rel="nofollow">http://us2.php.net/configuration.changes</a></p>
<p><a href="http://httpd.apache.org/docs/2.0/mod/core.html#allowoverride" rel="nofollow">http://httpd.apache.org/docs/2.0/mod/core.html#allowoverride</a></p>
|
SharePoint domains and Content Query Web Part <p>I have created a new sharepoint site on our moss server at <a href="http://sharepoint:12345" rel="nofollow">http://sharepoint:12345</a> and added a CQWP to it without issue.</p>
<p>I have a domain name pointing at the same server. So I pointed to <a href="http://myinternaldomain.whatever:12345" rel="nofollow">http://myinternaldomain.whatever:12345</a> and for some reason the CQWP then breaks, saying unable to display this web part?</p>
<p>Any ideas appreciated.</p>
| <p>Have you set up an Alternate Access Mapping for the second domain?</p>
<p><a href="http://technet.microsoft.com/en-us/library/cc263208.aspx" rel="nofollow">AAM on TechNet</a></p>
|
Problem using @SecondaryTable in Hibernate <p>Abridged version of my schema:</p>
<pre><code>utility_company
id int not null -- PK
name varchar(255) not null
utility_settings
utility_id -- FK to utility
use_magic tinyint(1) not null default 0
</code></pre>
<p>There is a one-to-one mapping between these two tables. Setting aside the fitness of this design, I want to Map the data in both of these tables to one object. In Hibernate/JPA, this is allegedly done as follows:</p>
<pre><code>@Entity
@Table(name = "utility_company")
@SecondaryTables({
@SecondaryTable(
name = "utility_settings",
pkJoinColumns = {
@PrimaryKeyJoinColumn(
name="utility_id", referencedColumnName="id")
})
})
public class UtilityCompany extends AbstractEntity {
</code></pre>
<p>And so forth.</p>
<p>Every <code>@Column</code> includes the appropriate table name.</p>
<p>When I deploy, I get this error:</p>
<pre><code>Cannot find the expected secondary table:
no utility_company available for poscore.model.UtilityCompany
</code></pre>
<p>The <code>utility_company</code> table is definitely there (a previous version only maps <code>UtilityCompany</code> to the <code>utility_company</code> table; I'm adding the <code>utility_settings</code>).</p>
<p>Found numerous forum posts with this exact problems and no answers. I've also tried various allegedly legal forms of specifying the <code>@SecondaryTable</code> all of which have the same effect.</p>
<p>Anyone successfully use <code>@SecondaryTable</code>, and, if so, seen this?</p>
| <p>Your mappings are correct IMHO, and runs fine with <a href="http://www.datanucleus.org/products/accessplatform" rel="nofollow">DataNucleus AccessPlatform</a> as the JPA implementation. Maybe Hibernates log tells you more ?</p>
<p>--Andy <a href="http://www.datanucleus.org" rel="nofollow">DataNucleus</a></p>
|
Programmatically determine if a COM library (.DLL) is installed <p>Is there a programmatic way in C# to determine whether a particular COM DLL has been installed? Or is this a matter of scanning the registry for the classId?</p>
| <p>What I usually did (and would do, if I needed this again) is try to create an object instance of a class you know is in the COM library - either by ProgID or GUID - and checking for failure.</p>
|
Timeout Pattern - How bad is Thread.Abort really? <p>I've read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I've read that MS uses the pattern below (which I've wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I'm worried about the Thread.Abort. Does anyone have a better way?</p>
<pre><code> public static bool CallandWait(this Action action, int timeout)
{
Thread subThread = null;
Action wrappedAction = () =>
{
subThread = Thread.CurrentThread;
action();
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
{
if (subThread != null)
{
subThread.Abort();
}
return false;
}
else
{
wrappedAction.EndInvoke(result);
return true;
}
}
</code></pre>
| <p>Basically you're talking about aborting an action which (as far as we know) has no graceful way of aborting.</p>
<p>That means there's going to be no <em>safe</em> way of aborting it. <code>Thread.Abort</code> is just not a nice thing to do - there are various race conditions and ugly situations you can get into (see the link in <a href="http://stackoverflow.com/questions/710070/timeout-pattern-how-bad-is-thread-abort-really/710094#710094">Richard's answer</a>). I would try desperately hard to avoid wanting to cancel actions that don't know about cancellation - and if you absolutely <em>have</em> to do it, consider restarting the whole app afterwards, as you may no longer be in a sane state.</p>
|
'for' loop through form fields and excluding one of the fields with 'if' <p>The problem I'm struggling with is as follows:</p>
<p>I have:</p>
<pre><code>{% for field in form %}
{{Â field }}
{% end for %}
</code></pre>
<p>What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:</p>
<pre><code>{% for field in form%}
{% if field == title %}
{% else %}
{{ field }}
{% endif %}
{% endfor %}
</code></pre>
<p>Is it possible? I have to many fields to write them one by one and only one or two to exclude.</p>
<p>Thank you for any tips.</p>
<p>BR,
Czlowiekwidmo.</p>
| <p>Yes, this should be possible:</p>
<pre><code>{% for field in form %}
{% ifnotequal field.label title %}
{{ field }}
{% endifnotequal %}
{% endfor %}
</code></pre>
<p>Django's <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ref-templates-builtins">template tags</a> offer <code>ifequal</code> and <code>ifnotequal</code> variants, and you can test the field.label against either a context variable, or a string.</p>
|
How can I su from root to db2inst1 and invoke a SQL script, in one line? <p>How can I <code>su</code> from <code>root</code> to <code>db2inst1</code> and invoke a SQL script all in 1 line? I am thinking about something like this:</p>
<pre><code>su db2inst1 | db2 CONNECT TO myDatabase USER db2inst1 USING mypw; db2 -c -i -w -td@ -f /tmp/deploy/sql/My.sql | exit;
</code></pre>
<p>Any ideas?</p>
| <p>You can use the <code>-c</code> or <code>--command=<command></code> option to execute a command with <code>su</code>. In your case, something like this:</p>
<pre><code>su -c 'db2 CONNECT TO myDatabase USER db2inst1 USING mypw; db2 -c -i -w -td@ -f /tmp/deploy/sql/My.sql' db2inst1
</code></pre>
|
Sql Query To get data <p>i have a table called DrTimings ,in which Doctors time for each day is this.</p>
<pre><code>DrID(int identity) StartTime(DateTime) EndTime(DateTime)
1 3/31/2009 8:00:00 AM 3/31/2009 10:30:00 AM
</code></pre>
<p>I have another table called TimeList which contain 3 fields</p>
<pre><code>SlotID SlotStartTime(varchar) SlotEndTime(varchar)
1 8:00AM 8:15AM
2 8:15AM 8:30AM
3 8:30AM 8:45AM
</code></pre>
<p>and goes on till 7:00PM </p>
<p>I have another table DrDutyDetails in which DrTiming is set for whole month like this.</p>
<pre><code>DrID StartTime EndTime DateOfAllocation
1 4/5/2009 8:00:00 AM 4/5/2009 9:30:00 AM 4/5/2009 12:00:00 AM
2 4/12/2009 8:00:00 AM 4/12/2009 9:30:00 AM 4/12/2009 12:00:00 AM
likewise
</code></pre>
<p>I have another table called AppointmentSchedule which gets filled when patient requests appointment</p>
<pre><code>AppointmentID SlotID AppointmentDate
1 1 4/5/2009
2 3 4/12/2009
</code></pre>
<p>i have a appointment schedule form in which i selects DrID and Appointment date.Then slots corresponding to date that has not been in Appointmentschedule,but slots should be in between starttime and endtime that in DrTimings and in TimeSlots should get filled in a dropdownlist.I need a query to implement this.
for eg:If Patient enters '4/5/2009' Then slots other than 1 and 3 but biw DrTimings i want to get.</p>
<p>Similarly i want to search by time.Means if Patient enters any time b/w DrTimings for eg:8:30AM,Then available first date has to be displayed in textbox</p>
| <p>You are going to need to look at doing some Casting/COnverting of date values. This <a href="http://msdn.microsoft.com/en-us/library/ms187928.aspx" rel="nofollow">MSDN article</a> gives you a bit of information on what you need to work with. </p>
<p>There are a number of ways that you can do this, but ideally you can do something like <code>CONVERT(VARCHAR(50), StartTime)</code> to get the fully formatted time. Then, since you know that the ending format of that is 08:00AM, you can do a <code>RIGHT(CONVERT(VARCHAR(50), StartTime), 7)</code>, which will get you just the time value.</p>
<p>Now, with that you know how to manipulate the date into parts, you can from here, do the various things needed to query your items.</p>
<p>For comparison sake, I would be storing the "TimeList" data as DateTime values, that way you can use standard time comparisons to actually allow you to use functions such as "Between" and similar. You could store them as 1/1/1900 08:00AM or similar. But this would require a data model change. If you want some helpful SQL for this type of thing, here is a great article on "<a href="http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx" rel="nofollow">Essential SQL Server Date, Time, and DateTime Functions</a>".</p>
|
Registering bugs by email <p>What is a best way to parse an email with bug description. One client decided recently that it would be nice for user to be able to send an email to known mailbox and a bug would be registered in bug tracker (not exactly bu close). </p>
<p>The problem is bug description has lot of fields like dates, times, descriptions, comments, losses, attachments etc. Relying on user to use some specific mail format is not the smartest thing to do. </p>
<p>The question is how could one parse email to get all needed information. The format should be not to strict, but enough to guess what fields mean what. I would also be interested to hear both correct and easiest solutions for this. </p>
<p>P.S.
Actually this feature was requested by a bank. They have a public mailbox where clients would sends discovered issues. The problem is to get as much information from these letters before bank employee will actually look at it.</p>
| <p>We do something similar to this with RT, however the email isn't really parsed. All the emails go into a single queue where it is evaluated by our IT staff. Basically, the parsing is done by humans - they modify the ticket to have as much information as they can glean from the email.</p>
<p>You're unlikely to get users to adhere (correctly) to any special syntax or formatting you come up with - unless they are employees, highly trained, or have some incentive to follow your rules.</p>
<p>Another option would be to have the initial email respond with an email that is formatted as a questionaire. In other words, the user writes an initial bug report and immediately (or as soon as your email server can respond) gets back a "thank you - can you provide more info" message with prompts for more info. You could then parse that email and have it populate your bug tracking system with more accurate info,</p>
<p>Good luck! Sounds like a cool idea!</p>
|
Branch from the past in mercurial <p>I'm a single developer using Mercurial to create a program. I have so far committed at every step of developing, and I have messed things up and want to work on something else.</p>
<p>How shall I go to a previous state (ie. rollback) and then create a branch, maintaining the newer states?</p>
<p>Does rollback ever delete anything? Should that be all I do? Just rollback untill I'm at the place where I want, edit, then commit? Will I be able to merge the changesets later, or at least look at them? Of course I can just save this repository, rollback, and then create new changesets, then merge the two repositories?</p>
<p>I'm new to SCM and of course DSCM, so be gentle :)</p>
| <p>You don't want to use <code>hg rollback</code>, that only erases <strong>exactly one</strong> change (the most recent). See <a href="http://hgbook.red-bean.com/read/finding-and-fixing-mistakes.html#id519728" rel="nofollow">You Can Only Roll Back Once</a> in the hg book.</p>
<p>To make a branch from an earlier revision, you need to find the revision number you want to branch from and run:</p>
<pre><code>hg clone -r <revnum> <source repository> <destination repository>
</code></pre>
<p>You can then do your changes in the newly-cloned repository (which will not contain any of the history that came after the revision number you specified) and then merge those changes back into the original later, if you wish.</p>
|
ORACLE - Exporting Procedures / Packages to a file <p>I would like to programmatically export my Procedures / Functions and Packages into individual files (as a backup) and using Oracle 9.2.</p>
<p>The closest solution i found was using DBMS_METADATA.GET_DDL , but how do i output the CLOB to a text file, without losing any parts (due to length or indentation) ?</p>
<p>Or maybe do you have other solutions to backup packages or other functions individually (only the one i want, not all of them) ?</p>
<p>Thanks</p>
| <p>Trying to get CLOBS (and LONGS) from command line utilities like SQL*Plus always seems to give me formatting/truncation problems. My solution was to write a simple utility in a non- type checking language (Perl) that uses <code>DBMS_METADATA</code> to bring the CLOB back into a string.</p>
<p>Snippet:</p>
<p>...</p>
<pre><code>$sthRef = $dbhRef->prepare("select dbms_metadata.get_ddl(?,?) from dual");
$sthRef->execute('PACKAGE', $thisName);
while (($thisDDL) = $sthRef->fetchrow()) {
print $thisDDL;
}
$sthRef->finish;
</code></pre>
<p>...</p>
|
Tiles won't parse Struts tags <p>I'm tried using tiles but it seems that it's not parsing the Struts tags, It outputs them directly e.g. instead of ...
What seems to be the problem?</p>
| <p>You need to include the taglib library header in each JSP file, regardless of whether it's a tile or not:</p>
<pre><code><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
</code></pre>
<p>etc...</p>
<p>Without this the tags will not be parsed.</p>
|
How do I get rid of the unknown property name errors in Visual Studio? <p>When using jQuery UI and ThemeRoller the CSS files created contain several CSS properties that are not known by Visual Studio, such as <code>zoom</code> and <code>opacity</code>. How can I keep these from showing up as errors in the error list when the CSS file is open in the editor pane?</p>
<p>In the spirit of SO, I'll add the solution I found as a response.</p>
| <p>Go to Tools --> Options --> Text Editor --> CSS --> CSS Specific (or Validation) and uncheck the <code>Detect unknown properties</code> checkbox.</p>
|
Dynamically created expressions <p>I'm creating a dynamic expression, which will order items in a list by some rule (lambda exp.). This is the code:</p>
<pre><code>Expression<Func<String, String>> exp = o => o;
MethodCallExpression orderByExp = Expression.Call(typeof(Enumerable), "OrderBy",
new Type[] { typeof(String), exp.Body.Type }, Expression.Parameter(typeof(IEnumerable<String>), "list"), exp);
</code></pre>
<p>Now I want to execute previously created expression on specific data to sort it, but it fails because of some strange exceptions like "Lambda Parameter not in scope" or "Argument expression is not valid".</p>
<pre><code>var data = new String[] { "asdasdasd", "asdads", "123", "xcvxcvs", "ASDSD" };
// one of attempts: doesn't work
var result = data.AsQueryable().Provider.CreateQuery<String>(orderByExp);
</code></pre>
<p>Can somebody help me with this?</p>
| <p>order any enumerable by a property(no reflection):</p>
<pre><code>public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> items, string property, bool ascending)
{
var MyObject = Expression.Parameter(typeof (T), "MyObject");
var MyEnumeratedObject = Expression.Parameter(typeof (IEnumerable<T>), "MyEnumeratedObject");
var MyProperty = Expression.Property(MyObject, property);
var MyLamda = Expression.Lambda(MyProperty, MyObject);
var MyMethod = Expression.Call(typeof(Enumerable), ascending ? "OrderBy" : "OrderByDescending", new[] { typeof(T), MyLamda.Body.Type }, MyEnumeratedObject, MyLamda);
var MySortedLamda = Expression.Lambda<Func<IEnumerable<T>, IOrderedEnumerable<T>>>(MyMethod, MyEnumeratedObject).Compile();
return MySortedLamda(items);
}
</code></pre>
|
Autosizing departure board using Html, CSS and JQuery <p>I've got to develop an auto scaling arrivals and departures board at work.</p>
<p>It's started out easily enough with me creating a table with percentage based column widths (and the overall table being 100% width).</p>
<p>For now, I've got a small piece of JQuery letting me change the scale of my text but its only to prove the concept.</p>
<p>I'm really after being able to automatically scale the font and table cell sizes according to the available screen width and height. I do know the maximum string length allowed for each column cell so I could, potentally, automatically set the em/px size based on some calculation.</p>
<p>However, I'm a bit stuck as where to start. I'm actively developing this now but my initial thoughts are:</p>
<p>scale = maxstringwidth_inpx / currentcellwidth_inpx</p>
<p>Where I'd calculate maxstringwidth by having a lookup table and the font metrics for a character 1em in size on the screen.</p>
<p>The cells are all assigned screen percentages so I should be able to read those directly.</p>
<p>Then I can set the font size, ie:</p>
<pre><code>$("body").css("font-size", currentfontsize_px * scale);
</code></pre>
<p>Does this sound a feasible approach? It also raises questions about the padding above and below each string in each cell but I'm sure I can do someting similar there too.</p>
<p>To qualify where I'm stuck:</p>
<ol>
<li>Are there examples of this kind of
thing out in the wild (I couldn't
find any) </li>
<li>Does my approach have
pitfalls? </li>
<li>Have you done it before
and can share wisdom/techniques?</li>
<li>Have I shot myself in the foot
already and should consider a
different approach?</li>
</ol>
<p>I have mentioned using Flash to the PM as a means of autoscaling the text as we can then do a lot of the font metrics in ActionScript. However, I'm only just starting out with that using the .NET flash IDE so I'd be limited to that as a development platform.</p>
<p>Thanks for any tips, examples and advice!</p>
<p>Simon</p>
| <p>CSS and HTML can be very finicky when it comes to this sort of thing especially since font-size can be very different on different computers. Case in point, if you are using the font, say, Verdana. It's a pretty common font. Unfortunately the way Macs, Windows, and Linux renders it is slightly different. There's really no way to guarantee the width/height of a 'nice' (non-monospaced) font, unless the application will be used in a very strictly controlled environment.</p>
<p>I'm not normally a proponent of using Flash, but, if that's an option, it's really the only way to guarantee something will look as expected since you can embed fonts and, like you mentioned, there is a lot more control over typography in Flash than there is in CSS. You're going to be doing some pretty heavy development in CSS and jQuery to achieve the same effects--and even then, you will still have difficulties between browsers and OSes.</p>
<p>But, if you do decide to do this in CSS/jQuery/HTML, make sure you use ems everywhere--no pixels.</p>
<p>Good luck, and let us know what you decide to do in the end.</p>
|
Reload UITableViewController <p>I'm trying to reload data in a <code>UITableViewController</code> after a location is found. This also means after the <code>viewDidLoad</code> method. My class is extending a <code>UITableViewController</code> with this interface:</p>
<pre><code>@interface RootViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate>
</code></pre>
<p>in the implementation I try to reload data using </p>
<pre><code>[self.view reloadData];
</code></pre>
<p><code>reloadData</code> doesn't seem to be a method of UITableViewController or the view because I get an error: </p>
<pre><code>Messages without a matching method signature will be assumed to return 'id' and accept '...' as arguments
</code></pre>
<p>Can someone please post some code of how to reload a table view extended like in my case?</p>
| <p>you have to do it on the <code>UITableView</code> over <code>[self.tableView reloadData];</code></p>
|
WinMM Library Issues <p>I wrote a WinMM library wrapper library that exposes WaveOut and WaveIn classes for the purpose of recording and playing raw audio streams.</p>
<p>Everything works great, but in order to follow the operating system specs on how to handle the finished buffers, I added a thread that unprepares the buffers and frees the memory. I also got all of the synchronization down, so that the classes are solid and thread-safe.</p>
<p>However, there seems to be a rare issue where I add a buffer to the WaveOut device and the operating system returns a success code, but if the device is reset immediately afterwords, the OS does not mark the buffer as finished and return it to the application.</p>
<p>It seems that it is loosing the buffers. So, the problem is, I'm keeping track of the count of individual buffers sent to the device and blocking joining the Close() function to the thread that cleans them up.</p>
<p>Any ideas, or known bugs?</p>
<p>PS: This does NOT seem to happen on a Quad Core in Vista, but does happen on my Dual Core in XP pro.</p>
<p><strong>EDIT1: I'm totally willing to expose the full source code, once I get it uploaded and propery licensed on codeplex, if that would help anybody.</strong></p>
<p><strong>EDIT2: Posted library to CodePlex: <a href="http://winmm.codeplex.com/" rel="nofollow">http://winmm.codeplex.com/</a></strong></p>
<p>Here is an idea of what causes the issue:</p>
<pre><code>public partial class MainView : Form
{
private WaveIn waveIn = new WaveIn(WaveIn.WaveInMapperDeviceId);
private WaveOut waveOut = new WaveOut(WaveOut.WaveOutMapperDeviceId);
public MainView()
{
InitializeComponent();
WaveFormat format = WaveFormat.Pcm44Khz16BitMono;
waveOut.Open(format);
waveIn.DataReady += new EventHandler<DataReadyEventArgs>(WaveIn_DataReady);
// Tweaking these values affects the internal buffering thread.
// Setting too small of a QueueSize with too small of a BufferSize
// will cause buffer underruns, which will sound like choppy audio.
waveIn.BufferQueueSize = 200;
waveIn.BufferSize = 64;
waveIn.Open(format);
waveIn.Start();
}
void WaveIn_DataReady(object sender, DataReadyEventArgs e)
{
if (waveOut != null)
{
lock (waveOut)
{
// We have to check for null after the lock,
// because waveOut may have been disposed
// inside another lock.
if (waveOut != null)
{
waveOut.Write(e.Data);
}
}
}
}
private void MainView_FormClosed(object sender, FormClosedEventArgs e)
{
if (waveIn != null)
{
lock (waveIn)
{
waveIn.Dispose();
waveIn = null;
}
}
if (waveOut != null)
{
lock (waveOut)
{
waveOut.Dispose();
waveOut = null;
}
}
}
}
</code></pre>
| <p>I would first create a separate <code>object</code> on which to lock. That should simplify a lot of your null-checking logic (by about half since you check before and after the lock).</p>
<p>Second, <code>Dispose</code> will not set your variable to <code>null</code>, so your other checks will still pass through because the object is not null, only disposed. So I would do</p>
<pre><code>waveOut.Dispose();
waveout = null;
</code></pre>
<p>to make sure that it is explictly set to null.</p>
|
C# Permutation of an array of arraylists? <p>I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.</p>
<p>EXAMPLE: (all values are strings)</p>
<pre><code>myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };
</code></pre>
<p>The count of myList can be varied so its length is not known beforehand. </p>
<p>I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).</p>
<pre><code>1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93
</code></pre>
<p>Does this make sense of what I am trying to accomplish? I can't seem to come up with a good method for doing this, (if any).</p>
<p>Edit:<br />
I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.</p>
<p>I want to end up building a string[] array of all the combinations that follows the format like below:</p>
<p>for the "1 2 93" permutation</p>
<p>I want the output to be "val0=1;val1=2;val2=93;"</p>
<p>I will experiment with recursion for now. Thank you DrJokepu</p>
| <p>I'm surprised nobody posted the LINQ solution.</p>
<pre><code>from val0 in new []{ "1", "5", "3", "9" }
from val1 in new []{ "2", "3" }
from val2 in new []{ "93" }
select String.Format("val0={0};val1={1};val2={2}", val0, val1, val2)
</code></pre>
|
Unique record in Asp.Net SQL <p>I asked this question previously but the answers weren't what I was looking for. </p>
<p>I created a table in Asp.net without using code. It contains two columns.</p>
<p>YourUserId and FriendUserId</p>
<p>This is a many to many relationship. </p>
<p>Heres what I want:</p>
<p>There can be multiple records with your name as the UserId, there can also be multiple records with FriendUserId being the same...but there cannot be multiple records with both being the same. For example:</p>
<p>Dave : Greg</p>
<p>Dave : Chris</p>
<p>Greg : Chris</p>
<p>Chris : Greg</p>
<p>is good</p>
<p>Dave : Greg</p>
<p>Dave : Greg</p>
<p>is not good.</p>
<p>I right clicked on the table and chose Indexes/Keys. I then put both columns in the columns section and chose to make the unique. I thought this would make them unique as a whole but individually not unique.</p>
<p>If you go to the Dataset, it show keys next to both columns and says that there is a constraint with both columns being checked.</p>
<p>Is there a way of just making sure that you are not inserting a duplicate copy of a record into the table without individual columns being unique?</p>
<p>I tried controling it with my sql insert statement but that did not work. This is what I tried.</p>
<p>INSERT INTO [FriendRequests] ([UserId], [FriendUserId]) VALUES ('"+UserId+"', '"+PossibleFriend+"') WHERE NOT EXIST (SELECT [UserId], [FriendUserId] FROM [FriendRequests])</p>
<p>That didn't work for some reason.
Thank you for your help!</p>
| <p>You should create a compound primary key to prevent duplicate rows.</p>
<pre><code>ALTER TABLE FriendRequests
ADD CONSTRAINT pk_FriendRequests PRIMARY KEY (UserID, FriendUserID)
</code></pre>
<p>Or select both columns in table designer and right click to set it as a key.</p>
<p>To prevent self-friendship, you'd create a <code>CHECK</code> constraint:</p>
<pre><code>ALTER TABLE FriendRequests
ADD CONSTRAINT ck_FriendRequests_NoSelfFriends CHECK (UserID <> FriendUserID)
</code></pre>
<p>You can add the check constraint in the designer by right clicking anywhere in the table designer, clicking "Check constraints", clicking "add", and setting expression to <code>UserID <> FriendUserID</code></p>
<p>You might want to look at <a href="http://stackoverflow.com/questions/669483/modeling-friends-and-followers-in-an-rdbms">this question</a></p>
|
The referenced component 'System' could not be found. (or any other component for that matter) <p>The issue was reported as a bug to the VS team <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=355654">here</a>
but was closed as not reproducible since the original poster didn't reply I guess. I added my validation to the case, but I still can't find a workaround to fix this.</p>
<p><strong>Issue:</strong> Just started today, all references to any assembly outside of the solution fails to resolve, with "The referenced component 'SomeComponent' could not be found." when trying to build. This happens for both 3rd party components (all 15 or so of them) as well as all .NET Framework assemblies, basically anything that isn't another project in the same solution.</p>
<p>Trying to load some other solutions produced the same issue. Creating a new WinForms project worked without a problem however. (Scratch that, it worked before reinstalling VS, now that doesn't work either. Created new WinForms app as well as WPF app and the Designer can't load the assemblies either. Tried targetting 3.5 and 2.0 and no luck)</p>
<p><strong>Things I've tried:</strong> </p>
<ul>
<li>Repair Visual Studio installation</li>
<li>Rebooting computer</li>
<li>Started VS with /resetsettings flag</li>
<li>System Restore to 2 days ago when it was known to be working</li>
<li>Uninstalling VS and reinstalling</li>
<li>Fresh checkout from SVN</li>
</ul>
<p>Does anyone have any experience with this and knows of a way to get this working again? My strongest Google-fu has failed me, so I'm asking here. Can mark community wiki if requested.</p>
<p>Update:
Tried "Upgrading" Windows (to the same version) since I didn't see a repair option for Vista and still no go. Reinstalled everything that seemed relevant. So far looking like I'm just gonna have to backup and reformat I guess unless a solution comes up some time before tomorrow.</p>
<p>Update2:
Already just backed up data and reformatted, so I'm no long able to verify any ideas I haven't tried yet, so I'll just leave the bounty to expire on it's own to top voted answer and as a reference to anyone else who may have this problem later</p>
| <p>In my case, the solution was completely different. It looked like it was an issue with NuGet paths (caused by my moving the project to a different solution and then back again.</p>
<p>I edited the .csproj and removed all references to NuGet and associated packages. I also removed the packages folder from the solution folder. </p>
<p>The system components then magically reappeared. </p>
|
What are your web development standards? <p>I am trying to come up with a clear standard to present to my web team so that the frontend HTML/CSS developers and the backend developers can get on the same page. Currently, we all have our own coding styles, and we tend to end up creating more work for each other when we have to dive into each others' code.</p>
<p>What sort of CSS/HTML and backend coding standards do you or your team adhere to so that the code is easily and predictably readable between frontend HTML/CSS development and back-end server development? What processes do you use in hand-offs to ensure everyone knows what is what?</p>
| <p>Do you have a css framework chosen out or developed? It's hard to create a system of standards a priori. I would work with your developers to choose a common CSS/Layout framework (such as, <a href="http://www.blueprintcss.org/" rel="nofollow">Blueprint</a>, <a href="http://960.gs" rel="nofollow">960 Grid System</a>, or your own custom framework). </p>
<p>CSS is often developed after the HTML is written, however having a set of reusable CSS already in place informs every party involved of the kind of stuff that has to be in place. There are a million ways to implement layout using CSS/HTML, and a predetermined method of implementation chosen from the start is great; you know what kind of cross browser challenges will exist (or even eliminated!), instead of having to hash those out every time.</p>
<p>Additionally, the other cool consequence of a css framework is that you can then have graphic design people use the grid system utilized by the framework and speed development even more. </p>
<p>So choose the common css framework/vocabulary and then move from there to get something working that you'll all love.</p>
|
C# WebBrowser control not firing the DocumentCompleted event <p>I have a program that is using the C# WebBrowser control and it needs to detect which page is loaded to determine what to do next. The program works fine on most of the employee's computers at the office, but it does not work on some.</p>
<p>I have determined the problem is that the <code>documentCompleted</code> event is not firing on those computers it does not work on.</p>
<p>This program does use threads to process data, and the <code>webbrowser.navigate</code> call is made through a delegate. But I have also changed the code to not use delegates for the navigate action with no change in the result.</p>
<p>I also made a separate program that has just a basic <code>WebBrowser</code> and debug <code>textfield</code>, and the <code>DocumentCompleted</code> event <strong>does</strong> fire when using that program.</p>
<p>NOTE: The computers that it is not firing on are older PCs with single core/thread processors.</p>
<p>I am out of ideas on this one, any help would be appreciated.</p>
| <p>As explained by CodeBlock, this seems to be related by the installation state of <code>Microsoft.mshtml.dll</code></p>
<p>We've got customers where the <code>Microsoft.mshtml.dll</code> is not present in GAC (nor in computer), and then the <code>WebBrowser</code> component never fires any event.</p>
<p>By using Reflector in the <code>WebBrowser</code> class, the <code>DocumentComplete</code> event is raised by a subclass named <code>WebBrowserEvent</code>, which implement a private interface <code>DWebBrowserEvents2</code>.</p>
<p>This interface is a <code>ComImport</code> of <code>{34A715A0-6587-11D0-924A-0020AFC7AC4D}</code>, which, I suppose, is related to Microsoft.mshtml.dll.</p>
<p>So our solution was to install <a href="http://www.microsoft.com/downloads/details.aspx?familyid=3C9A983A-AC14-4125-8BA0-D36D67E0F4AD&displaylang=en">the Office 2003 Redistributable Primary Interop Assemblies</a>, which install the DLL on Program Files then register it on the GAC.</p>
<p>Note : Don't pay attention to the .NET Framework 1.1 required or office required, it just copies some dlls.</p>
<p>Note 2 : The <a href="http://www.microsoft.com/downloads/details.aspx?familyid=59DAEBAA-BED4-4282-A28C-B864D8BFA513&displaylang=en">2007 package</a> seems to include the same dll.</p>
|
Database replication from SQLserver 2000 to SQLserver 2008 <p>I'm trying to replicate a rather large database from SQLServer 2000 to SQLServer 2008, located on two different servers. I found an article about attempting this and have been trying to follow its direction. Here is the article.</p>
<blockquote>
<p><a href="http://www.vinodunny.com/blog/post/Mixed-Mode-Bi-Directional-Transactional-Replication-between-SQL-2000-and-SQL-2008.aspx" rel="nofollow">Mixed Mode Bi-Directional Transactional Replication between SQL 2000 and SQL 2008</a></p>
</blockquote>
<p>Here is the part I'm stuck on:</p>
<blockquote>
<p>"So, to create a publication, you will
need to NOT use the publication wizard
that you get in SQL 2008. Instead, use
a generated publication script and for
each <code>sp_addarticle</code> line that you have
in it, make sure that the <code>@ins_cmd</code>,
<code>@upd_cmd</code> & <code>@del_cmd</code> parameters point
to the appropriate stored procedures
and run it on the SQL Server 2000
server. Once this is done, go ahead
and create a subscription to SQL
Server 2008âs database normally."</p>
</blockquote>
<p>I was able to get the stored procedures in place for all of the tables but need some direction on creating a generated publication script. Does anyone have some direction or a good example of a generated publication script?</p>
| <p>On the final step of the publication wizard you will have the two options:
1. Create the publication
2. Generate a script file with steps to create the publication</p>
<p>The article referenced here is suggesting that you do not let the wizard create the publication but instead only choose to generate the script file. At that point you can edit the script file as instructed in the article.</p>
|
Is NAS / SAN + HTTP server a good match? <p>Is NAS / SAN + HTTP server a good solution for serving large number of static files over the internet?</p>
| <p>Add some memory caching on your server, and you should be good. Apache has a couple of modules that do that.</p>
<p>You could also take a look at static distributed caching services, if you want to improve latency for your users and reduce your bw costs, like Akamai and PantherExpress. The latter can be a good investment, depending on your bw costs.</p>
|
Best client/server UDP and TCP debugging tool? <p>I'm trying to find a simple TCP/UDP debugging tool. The tool should act like a client or a server, display incoming messages, allow sending messages, etc. Ideally, the tool would have a GUI and be extremely easy to use.</p>
<p>For the life of me I can't find anything adequate. All tools I tried either truncate messages, inject dummy messages in the stream, etc. This is frustrating given how easy such a tool is easy to implement. I can't believe this wheel hasn't been reinvented 100 times, yet 3 hours of Googling got me nowhere...</p>
<p>Any help appreciated. Thanks,</p>
| <p>TCPIP Builder (Windows)</p>
|
How to use constant var in SSIS <p>I have defined a variable as:</p>
<pre><code> DateSecondsOffset Int default as 1
</code></pre>
<p>in a SQL Server Integration Service project. I use it as constant.</p>
<p>In a task, I have the following SQL to set another var NextDT:</p>
<pre><code> SELECT dateadd(s, max(timestamp), 1) DT from myTable
</code></pre>
<p>I would like to replace the 1 with DateSecondOffset so that I can change it when needed. Can I just type in the var name there or prefix it with @ or something else?</p>
| <p>If you're in a Script..</p>
<pre><code>Dts.Variables("DateSecondOffset").Value
</code></pre>
<p>If you're referring to it in a field..</p>
<pre><code>Scope::DateSecondOffset
</code></pre>
<p>Replace Scope with your scope which can be found in the "package explorer" tab under variables.</p>
<p>If you're referring to it in a SQL...</p>
<blockquote>
<p>SELECT @DateSecondOffset</p>
</blockquote>
<p>Be sure to setup your input/output parameters in a SQL Task and ReadOnly/ReadWrite Variables on a script task.</p>
|
Why isn't Smalltalk popular? <p>Iâve been looking at Smalltalk (VisualWorks) for the past couple of months - and the more I learn the more Iâm impressed. However, I think I must be missing something as Smalltalk doesnât seem to be popular these days - and perhaps it never was. </p>
<p>What do the people who have dropped Smalltalk in favor of Java, C++, Ruby, etc. know that I donât or in other words âWhy isnât Smalltalk more popular?â</p>
| <p>There are a number of reasons that Smalltalk didn't "catch fire", most of them historical:</p>
<ul>
<li><p>when Smalltalk was introduced, it was too far ahead of its time in terms of what kind of hardware it really needed</p></li>
<li><p>In 1995, when Java was released to great fanfare, one of the primary Smalltalk vendors (ParcPlace) was busy merging with another (Digitalk), and that merger ended up being more of a knife fight</p></li>
<li><p>By 2000, when Cincom acquired VisualWorks (ObjectStudio was already a Cincom product), Smalltalk had faded from the "hip language" scene</p></li>
<li><p>Since then, Smalltalk has been a small player on the language space, but it's back to having a growing market. There are both commercial offerings (Cincom being the largest player there), and open source (<a href="http://www.squeak.org">Squeak</a> and <a href="http://www.pharo-project.org">Pharo</a> which are mostly under the MIT license, and <a href="http://smalltalk.gnu.org/">GNU Smalltalk</a>, which is GPL). </p></li>
</ul>
<p>Not all Smalltalk implementations require an image; while those of us who are sold on an image environment love it, you can use GNU Smalltalk with your favorite text editor easily enough. </p>
<p>Ultimately, Smalltalk peaked early, and then had damage done to it by the stupidity of the early vendors in the space. At this point in time, that's all in the past, and I'd say that the future looks pretty bright.</p>
|
Opensource C/C++ decompiler <p>Duplicate of <a href="http://stackoverflow.com/questions/193896/whats-a-good-c-decompiler">http://stackoverflow.com/questions/193896/whats-a-good-c-decompiler</a> and <a href="http://stackoverflow.com/questions/205059/is-there-a-c-decompiler">http://stackoverflow.com/questions/205059/is-there-a-c-decompiler</a> taken together.</p>
<p>Does somebody know any opensource <strong>C/C++</strong> decompiler? I don't want to use any commercial solution like <strong>IDA Pro</strong>.</p>
| <p>Check out <a href="http://boomerang.sourceforge.net/">Boomerang</a>.</p>
|
Basic ActiveRecordStore updated_at field not being updated on every request <p>I'm using the standard active_record_store in my app. In <code>environment.rb</code> I have:</p>
<pre><code>config.action_controller.session_store = :active_record_store
</code></pre>
<p>And my <code>sessions</code> table was created with <code>rake db:sessions:create</code>:</p>
<pre><code>create_table :sessions do |t|
t.string :session_id, :null => false
t.text :data
t.timestamps
end
add_index :sessions, :session_id
add_index :sessions, :updated_at
</code></pre>
<p>However the <code>updated_at</code> column isn't being updated on each request. It is being updated upon session creation (to the same value as <code>created_at</code>, as expected) but not for any subsequent requests. </p>
<p>Oddly, if I declare the following explicit call in <code>environment.rb</code> then the field <em>is</em> updated on each request:</p>
<pre><code>class CGI::Session::ActiveRecordStore::Session
def before_save
self.updated_at = Time.now
end
end
</code></pre>
<p>Can anyone explain why this doesn't work by default? </p>
<p>I'm running Rails 2.1.0 -- and no, I can't upgrade Rails at the moment! :)</p>
| <p>Are you updating the session? If you aren't updating the values, then I believe the session won't be saved to disk.</p>
<pre><code>class WhateverController < ActionController
def index
session[:whatever] = true
end
end
</code></pre>
|
Learning to work with audio in C++ <p>My degree was in audio engineering, but I'm fairly new to programming. I'd like to learn how to work with audio in a programming environment, partly so I can learn C++ better through interesting projects.</p>
<p>First off, is C++ the right language for this? Is there any reason I shouldn't be using it? I've heard of Soundfile and some other libraries - what would you recommend?</p>
<p>Finally, does anyone know of any good tutorials in this subject? I've learnt the basics of DSP - I just want to program it!</p>
<p>EDIT: I use Windows. I'd like to play about with real-time stuff, a bit like Max/MSP but with more control.</p>
| <p>It really depends on what kind of audio work you want to do, If you want to implement audio for a game, C++ is sure the right language. There are many libraries around, OpenAL is great, free and multiplatform. I also used DirectSound and Fmod with great sucess. Check them out, it all depends on your needs.</p>
|
Launch .jar files with command line arguments (but with no console window) <p>I have to do a demo of an application, the application has a server.jar and client.jar. Both have command line arguments and are executable. I need to launch two instances of server.jar and two instances of client.jar.</p>
<p>I thought that using a batch file was the way to go, but, the batch file executes the first command (i.e. >server.bat [argument1] [argument2]) and does not do anything else unless I close the first instance, in which case it then runs the 2nd command. And also the I do not want a blank console window to open (or be minimized)</p>
<p>What I really need is a batch script that will just launch these apps without any console windows and launch all instances that I need.</p>
<p>Thanks in Advance!</p>
<p>EDIT:</p>
<p><strong>javaw</strong>: </p>
<blockquote>
<p>works if I type the command
into the console window individually.
If I put the same in the batch file,
it will behave as before. Console
window opens, one instance starts
(whichever was first) and it does not
proceed further unless I close the
application in which case it runs the 2nd command. I want it to run all commands silently</p>
</blockquote>
| <p>Try:</p>
<pre><code>javaw <args>
</code></pre>
|
ASP.net AJAX Control Toolkit will not recognise my specified css classes in the autocomlete extender? <p>I am trying to specify CSS classes for the <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx" rel="nofollow">autocomplete</a> control:</p>
<pre><code>CompletionListCssClass="completionListElement"
CompletionListItemCssClass="listItem"
CompletionListHighlightedItemCssClass="highlightedListItem"
</code></pre>
<p>When I try this, it returns this error:</p>
<blockquote>
<p>Parser Error Message: Type 'AjaxControlToolkit.AutoCompleteExtender' does not have a public property named 'CompletionListCssClass'.</p>
</blockquote>
<p>Those properties come right from the ACT website. Why won't it recognize them?</p>
| <p>are you sure you have the most recent version of the ajax control toolkit?</p>
|
Are custom facelet functions dirty? <p>I have several places in my facelets web app where we are using custom facelet functions. For some reason they feel dirty and I can't quite peg why. What is StackOverflow's view of custom facelet functions?</p>
| <p>I can see how you might think that. I think excessive use of such functions is probably poor design. However, there are cases where your life is just easier defining a custom facelet function; therefore you shouldn't dismiss them out of hand.</p>
|
Silverlight Design Resources for the Inept <p>I'm steadily progressing on Silverlight from a programming standpoint. I believe I'm to the point where I want my application to look decent to begin demo'ing. Doesn't have to look awesome, but not like a 2 year old did it (although a 2 year old might be a step above my current design skills). With HTML, you could typically find some designs, credit the author and off you go with a reasonably decent looking web application. I guess Silverlight is too young to have these sorts of resources, or perhaps I'm just having trouble locating them.</p>
<p>Are there any starting points that a lowly developer like me can mold into my application? I don't need anything fancy, just something clean and visually appealing. If the answer is 'sorry chump, ya gotta pay a pro', I can live with that. But wanted to see if there were other avenues I hadn't considered to create a decent looking proof of concept.</p>
| <p>Check out the free icons at famfam:
<a href="http://famfamfam.com/lab/icons/silk/" rel="nofollow">http://famfamfam.com/lab/icons/silk/</a></p>
<p>The silk ones especially are really slick and have helped me a lot in the past.
Good looking icons and buttons go a long way towards polishing the look of your app.</p>
|
Permissions problem using SyncToy to synchronize ClearCase with SharePoint 3.0 <p>So I am trying to setup a simple one way synch from a dynamic ClearCase view over to a MOSS document library. I'm using SyncToy 1.4 as my sync tool and it seems to work fine when it's copying new documents from ClearCase to SharePoint but it's throwing an error when I try to overwrite a file with a new version or try to delete an existing file in SharePoint because it's deleted in ClearCase. I'm using the "Echo" sync setting so SharePoint should always mirror changes in ClearCase. </p>
<p>I've created a custom active directory user for this process and have given that user Full Control on the SharePoint document library and can manually do these edits/deletes from the explorer view of the doc library when I'm logged into a server as that "sync user" however when I run the synctoy it fails saying the document in SharePoint is "read-only". My questions is shouldn't synctoy be running as that "sync user" and shouldn't it behave the same as when I manually manipulate the documents in SharePoint in explorer view as that "sync user"?</p>
| <p>Is this similar to <a href="http://support.microsoft.com/kb/870853" rel="nofollow">Office 2003 and 2007 Office documents open read-only in Internet Explorer</a>, where SharePoint might considering synctoy access to its files as "browsing access" (always opened as <a href="http://spsstuff.blogspot.com/2006/07/office-2003-documents-open-in-read.html" rel="nofollow">read-only</a>) ?</p>
<p>If not, the trick is to make sure your synctoy process does run as "sync user".</p>
<p>Using ClearCase on a regular basis, I do not see any side-effect with having for a source repository a dynamic view.</p>
<p>According to <a href="http://msdn.microsoft.com/en-us/library/ms442695.aspx" rel="nofollow">Managing Data in Windows SharePoint / Updating Child Content Types</a>, </p>
<blockquote>
<p>If you attempt to perform a push-down operation on a child content type that is marked as read-only, the push-down operation fails unless you set the parent content type to be read/write as part of the push-down operation.</p>
</blockquote>
<p>Meaning: you might want to check the rights associated with the parent directory (in Sharepoint) containing the file you try to delete.</p>
|
Programmatically Controlling Windows Media Player, Preferably From Java <p>I'm adding functionality to an existing Java application that's already been deployed extensively. (So there are some design decisions that I can't touch unless I have a <i>seriously</i> compelling reason.) The app controls a PC broadcasting audio and visual to a small local TV network. Right now, it mostly broadcasts static slides, but it can also do background music at the client's discretion. The background music (CD, local music files, internet radio, whatever) is handled by Windows Media Player.</p>
<p>My current project is adding narration to the static slides. When the narration plays, I need to send some kind of STFU signal that temporarily either quiets or mutes the WMP output. So my core question is: What's the best way to accomplish this?</p>
<p>I know WMP has an ActiveX interface, but I'm not experienced with ActiveX/COM. I can (and probably will) learn, certainly, but at this point, I'm not well positioned to distinguish between solutions that are easy, solutions that are technically feasible but painful, and "solutions" that are actually blind alleys.</p>
<p>Would a Java-based solution require me to make use of a Java->ActiveX bridge like Jacob? Or is that overkill?</p>
<p>Or, am I barking up the wrong tree entirely? I'm certainly willing to deploy small command-line executables written in another language entirely and then access them via Runtime.exec(). Is this the sort of thing that (say) VisualBasic makes dirt simple? (VB isn't in my skillset either, but if it's the right tool for this job, I'll learn. I just don't know if it's the right tool. Google gave me plenty of examples of incorporating WMP into a VB GUI; VB command line script, not so much.)</p>
<p>Finally, one last point: the WMP instance would be started by the user, not started by the Java app. Don't know if that makes a difference, but figured it was worth mentioning.</p>
<p>My thanks in advance for any insight anybody can offer me.</p>
| <p>Your best bet is to use Jacob (or some other Java/COM bridge); I assume you don't want to just mute the system volume.</p>
|
HTML Class with <select> <p>I'm trying to design a Form class in PHP. So far, I have the <code><input></code> buttons pretty well working. But the <code><select></code> boxes have me stymied. I'm trying to figure out a "generic" way of adding the <code><option></code> tags, and am lacking the creativity.</p>
<p>I'm not asking for teh codez, but implementation ideas are welcome.</p>
| <p>This is my implementation of it from my bare-bones framework that I use in super simple projects:</p>
<pre><code>function select($name, $options = array(), $attrs = array(), $showEmpty = false) {
$attrs['name'] = $name;
$attrs['class'] = isset($attrs['class']) ? $attrs['class'] . ' input' : 'input';
if(isset($this->validation->invalid[$name])) {
$attrs['class'] .= ' errorinput';
}
$opts = array();
foreach($attrs as $key => $value) {
$opts[] = $key . '="' . $value . '"';
}
$htmloptions = array();
$hasSelected = false;
foreach($options as $option => $value) {
if(isset($this->validation->post[$name]) && $this->validation->post[$name] == $option) {
$hasSelected = true;
$htmloptions[] = '<option value="' . $option . '" selected>' . $value;
} else {
$htmloptions[] = '<option value="' . $option . '">' . $value;
}
}
if($showEmpty) {
$emptyoption = '<option value=""' . (($hasSelected) ? '' : ' selected') . '>';
$htmloptions = array_merge($emptyoption, $htmloptions);
}
return '<select ' . implode(' ', $opts) . '>' . implode("\n", $htmloptions) . '</select>';
}
</code></pre>
|
Debugging exception thrown in Objective C and XCode <p>I am a long time Microsoft developer and I am new to iPhone development using XCode. So, I am reading a book and going through examples trying to teach myself how to write an iPhone application using Objective-C. All has been good so far, however, once in a while I run into the generic '<code>objc_exception_throw</code>' message at runtime. When this happens, the source of this exception is very difficult to find. After some trial and error I found my answer. One of the parameters was misspelled. </p>
<p>As you can see below, I misspelled the 'otherButtonTitles' parameter by leaving out the second 't' in button. </p>
<pre><code>UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Date and Time Selected"
message:message
delegate:nil
cancelButtonTitle:@"Cancel"
otherButonTitles:nil];
</code></pre>
<p>The reason this took me time to find is that the code built successfully. Is this normal behavior for the Objective-C compiler? I am used to having the build fail in the .NET compiler when I make a common syntax error like this. Is there a compiler setting I can change to make the built fail when I make these mistakes? </p>
| <p>First and foremost, open <code>~/.gdbinit</code> (that's the file called <code>.gdbinit</code> in your home directory - yes, starts with a dot) and put this in it:</p>
<pre><code>fb -[NSException raise]
fb objc_exception_throw
fb malloc_error_break
</code></pre>
<p>That'll initialize GDB with three default breakpoints, when they occur, GDB will halt your application and show you the stack trace. This is very well integrated with Xcode so you'll be able to nicely walk through your code by clicking stack trace elements as soon as an exception occurs somewhere or a malloc fails.</p>
<p>Then, open the <code>Get Info</code> panel on your project (or select your project (top item in the <code>Groups & Files</code>) and hit <code>cmd-i</code>), go to the <code>Build</code> tab and set your project's <code>Base SDK</code> to <code>Device - iPhone OS [someversion]</code>. Scroll all the way to the bottom and find the <code>GCC 4.0 - Warnings</code> section. There; turn on as many warnings as you feel comfortable with, but make sure to turn on <code>Treat Warnings as Errors</code> (this is the equivalent of <code>GCC_TREAT_WARNINGS_AS_ERRORS</code>). Personally, I have it set to this:</p>
<p><img src="http://lhunath.lyndir.com/stuff/gcc%5Fwarnings.png" alt="GCC Warning Build Settings" /></p>
<p>You should now be getting compiler warnings for most things you can do wrong in code and the compiler won't let you run the code until you fix them. When things do get past the compiler's nose, you should be able to find the problem easily with GDB breaking at a convenient spot.</p>
<p>You should also look into <code>NSZombie*</code>. These are environment variables that are very handy for early breaking on bad memory allocation or access situations. For instance; wih <code>NSZombieEnabled</code> nothing will truly be released; on dealloc it'll get overwritten with <code>_NSZombie</code> and should you try to access this dealloced memory again (dereferencing a dealloced pointer) you'll get something to break on in GDB, instead of the call going through like normal, only being issued on random data (which, of course, isn't what you wanted). For more info on this, see <a href="http://www.cocoadev.com/index.pl?NSZombieEnabled">http://www.cocoadev.com/index.pl?NSZombieEnabled</a>.</p>
|
Are there any rules regarding special characters/entities and innerHTML? <p>When I use innerHTML from javascript, the browser (Safari and Firefox at least) seem to replace certain characters and numeric entities with their named entities.</p>
<p>The character <code>\xa0</code> (non breaking space) gets replaced by <code>&nbsp;</code>,
<code>&#60;</code> (lesser than) gets replaced by <code>&lt;</code>. But for example the umlaut ü is not replaced with <code>&uuml;</code>.</p>
<p>I have not found any documentation for this behaviour.</p>
<p>A simple demo:</p>
<pre><code><h2 id="withoutnbsp">This does not use en be es pe (uses the \xa0 character)</h2>
<script>alert(document.getElementById("withoutnbsp").innerHTML);</script>
</code></pre>
<p>A more elaborate demonstration can be found here:</p>
<p><a href="http://gist.github.com/89434" rel="nofollow">http://gist.github.com/89434</a></p>
<p>You can use the "raw" link on the gist page, to view it in your browser.</p>
<p>I need to know exactly which characters innerHTML replaces. Any help is appreciated. Thanks.</p>
| <p>The HTML 5 spec has rules for serializing an HTML fragment when you call innerHTML on it, documented here: <a href="http://www.w3.org/TR/2009/WD-html5-20090212/serializing-html-fragments.html">Serializing HTML fragments</a> (note that innerHTML isn't in the HTML 4 spec, so the HTML 5 spec is the current reference).</p>
<p>TLDR version of the spec: Spaces, angle brackets, ampersands, equals signs and double quotes are the only chars that get escaped when innerHTML is called.</p>
|
Do organizations ever use SharePoint on a port other than 80? <p>Has anyone encountered SharePoint installations that are set up to use other than port 80? I'm not really concerned with test servers or administration interface usage.. just what users would be exposed to.</p>
<p>My application is currently set to leverage the WebDAV mini-redirector to assist with its SharePoint interface, and that software can't be used on SharePoint servers that use other than port 80. Trying to figure out how big a problem I might have when this application is deployed widely.</p>
| <p>I assume you're not referring to the admin interface of SharePoint?</p>
<p>Even so, yes, people use different ports, even multiple IP addresses, host headers, etc. Your application should handle this, or it won't get very much use.</p>
|
Fast implementation of Rolling hash <p>I need a Rolling hash to search for patterns in a file. (I am trying to use the rabin-Karp string search algorithm).</p>
<p>I understand how a good hash works and how a good rolling hash should work but I am unable to figure out how to efficiently implement the 'divide' (or inverse multiplication) when rolling the hash. I also read rsync uses rolling version of adler32 but that doesn't looks like a random enough hash.</p>
<p>Ideally it will be great if you can point me to an optimized C/C++ implementation, but any pointers in the right direction will help.</p>
| <p>Cipher's "prime base" idea should work decently - though the solution he posted looks a bit sketchy.</p>
<p>I don't think there's any need for inverse multiplication in this method.
Here's my solution:</p>
<p>Say the string we currently have hashed is "abc", and we want to append "d" and remove "a".</p>
<p>Just like Cipher, my basic hash algorithm will be:</p>
<pre><code>unsigned hash(const string& s)
{
unsigned ret = 0;
for (int i = 0; i < s.size(); i++)
{
ret *= PRIME_BASE; //shift over by one
ret += s[i]; //add the current char
ret %= PRIME_MOD; //don't overflow
}
return ret;
}
</code></pre>
<p>Now, to implement sliding:</p>
<pre><code>hash1 = [0]*base^(n-1) + [1]*base^(n-2) + ... + [n-1]
</code></pre>
<p>We'd like to add something at the end and remove the first value, so</p>
<pre><code>hash2 = [1]*base^(n-1) + [2]*base^(n-2) + ... + [n]
</code></pre>
<p>First we can add the last letter:</p>
<pre><code>hash2 = (hash1 * PRIME_BASE) + newchar;
=> [0]*base^n + [1]*base^(n-1) + ... + [n-1]*base + [n]
</code></pre>
<p>Then simply subtract the first character:</p>
<pre><code>hash2 -= firstchar * pow(base, n);
=> [1]*base^(n-1) + ... + [n]
</code></pre>
<p>An important note: you have to be careful about overflow. You can choose to just let it overflow unsigned int, but I think it's much more prone to collision (but also faster!)</p>
<p>Here's my implementation:</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
const unsigned PRIME_BASE = 257;
const unsigned PRIME_MOD = 1000000007;
unsigned hash(const string& s)
{
long long ret = 0;
for (int i = 0; i < s.size(); i++)
{
ret = ret*PRIME_BASE + s[i];
ret %= PRIME_MOD; //don't overflow
}
return ret;
}
int rabin_karp(const string& needle, const string& haystack)
{
//I'm using long longs to avoid overflow
long long hash1 = hash(needle);
long long hash2 = 0;
//you could use exponentiation by squaring for extra speed
long long power = 1;
for (int i = 0; i < needle.size(); i++)
power = (power * PRIME_BASE) % PRIME_MOD;
for (int i = 0; i < haystack.size(); i++)
{
//add the last letter
hash2 = hash2*PRIME_BASE + haystack[i];
hash2 %= PRIME_MOD;
//remove the first character, if needed
if (i >= needle.size())
{
hash2 -= power * haystack[i-needle.size()] % PRIME_MOD;
if (hash2 < 0) //negative can be made positive with mod
hash2 += PRIME_MOD;
}
//match?
if (i >= needle.size()-1 && hash1 == hash2)
return i - (needle.size()-1);
}
return -1;
}
int main()
{
cout << rabin_karp("waldo", "willy werther warhol wendy --> waldo <--") << endl;
}
</code></pre>
|
ASP.NET Page Base Class with OnLoad event not allowing Derived Class to fire OnLoad <p>I have a custom PageBase class that I am using for all of the pages in my project. In my BaseClass I have a <code>protected override void OnLoad(EventArgs e)</code> method declared. This method seems to make my derived classes unable to throw their own OnLoad event. What is the preferred way of making both OnLoad events able to work?</p>
| <p>In your derived class:</p>
<pre><code>protected override void OnLoad(EventArgs e)
{
//do the specific work
//....
//
base.OnLoad(e);
}
</code></pre>
|
ASP.NET Error when trying to access page <p>Im getting this odd error:</p>
<p>Any help would be great? </p>
<p><strong>This is the error:</strong></p>
<blockquote>
<h2>Server Error in '/Rugby' Application.</h2>
<p><strong>Configuration Error</strong></p>
<p><strong>Description:</strong> An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. </p>
<p><strong>Parser Error Message:</strong> It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.</p>
<p><strong>Source Error:</strong> </p>
<pre><code>Line 33:
Line 34:
Line 35: <roleManager enabled="true">
Line 36:
Line 37: <providers>
</code></pre>
<p><strong>Source File:</strong> C:\Websites\ADHS\andyhollis.co.uk\rugby\admin\web.config
<strong>Line:</strong> 35 </p>
<p>Show Additional Configuration Errors:</p>
<p>It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.</p>
<p>(C:\Websites\ADHS\andyhollis.co.uk\rugby\admin\web.config
line 43) </p>
<p>It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.</p>
<p>(C:\Websites\ADHS\andyhollis.co.uk\rugby\admin\web.config
line 67)</p>
<p><hr /></p>
<p>Version Information: Microsoft .NET
Framework Version:2.0.50727.3053;
ASP.NET Version:2.0.50727.3053</p>
</blockquote>
| <p>This sometimes happens when you have a Web.config in a subdirectory of the application's root.</p>
<p>Alternatively, you may need to go into the virtual directory and configure it correctly as an application (as noted by the error message).</p>
|
What's the right way to check for inheritance from a class/interface? <p>The code below is looping through a dictionary of strings and <strong>IMyCompanySettings</strong> looking for values that implement <strong>IMyCompanyProductSetting</strong>. Clearly, trying to cast and raising an exception is a very expensive way to do this.</p>
<pre><code> public static List<IMyCompanyProductSetting> GetProductSettings(ConfigurationManager cfm)
{
List<IMyCompanyProductSetting> ret = new List<IMyCompanyProductSetting>();
foreach(IMyCompanySetting setting in cfm.Values)
{
try
{
IMyCompanyProductSetting prod = (IMyCompanyProductSetting)setting;
ret.Add(prod);
}
catch
{
// Do nothing.
}
}
return ret;
}
</code></pre>
<p>What's a better way to do this?</p>
| <h2>Casting 101 [general info on casting stuff]:</h2>
<p>Use <code>[object] is [interface/class]</code> expression:</p>
<pre><code>if (setting is IMyCompanyProductSetting) {
...
}
</code></pre>
<p>Alternatively you can use the <code>as</code> keyword which tries to cast the object and if it fails, instead of throwing exception, it'll return <code>null</code>. Note that the target type must be a reference type in the <code>as</code> keyword:</p>
<pre><code>var prod = setting as IMyCompanyProductSetting;
if (prod != null) {
...
}
</code></pre>
<p>You should always use the above code instead of the equivalent exception handling.</p>
<h2>Filtering an <code>IEnumerable</code> by type (LINQy):</h2>
<p>As Jon Skeet pointed out, you should use <code>OfType</code> extension method to filter a sequence easily (assuming you got LINQ):</p>
<pre><code>var filteredSequence = sequence.OfType<TargetType>();
</code></pre>
<h2>Casting an <code>IEnumerable</code> to type (LINQy):</h2>
<p>If you want to try casting each element to the target type (as opposed to filtering by type), you can use the <code>Cast</code> extension method:</p>
<pre><code>var castedSequence = sequence.Cast<TargetType>();
</code></pre>
|
Object Instance in C# <p>Why do I get "Object Reference Not Set to Instance of an Object"</p>
<pre><code>protected void GetData()
{
...
id = this.GetTabControl().ID; //<---------here
}
...
protected ASPxPageControl GetTabControl()
{
return (ASPxPageControl)this.FindControl("DetailTab");
}
</code></pre>
<p>---------I assume the FindControl is not working.</p>
| <p>Presumably because <code>GetTabControl()</code> is returning <code>null</code>. We can't tell <em>why</em> without more code though.</p>
|
Use DisplayNameAttribute in ASP.NET <p>I want to bind a List to a GridView on a web page, but override the way the property names display via annotation. I thought System.ComponentModel would work, but this doesn't seem to work. Is this only meant for Windows Forms?:</p>
<pre><code>using System.ComponentModel;
namespace MyWebApp
{
public class MyCustomClass
{
[DisplayName("My Column")]
public string MyFirstProperty
{
get { return "value"; }
}
public MyCustomClass() {}
}
</code></pre>
<p>Then on the page:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
IList<MyCustomClass> myCustomClasses = new List<MyCustomClass>
{
new MyCustomClass(),
new MyCustomClass()
};
TestGrid.DataSource = myCustomClasses;
TestGrid.DataBind();
</code></pre>
<p>}</p>
<p>This renders with "MyFirstProperty" as the column header rather than "My Column." Isn't this supposed to work?</p>
| <p>If all you care about is the header text in GridView, just use the HeaderText property of each field you bind. If you're autogenerating the columns, you just set the HeaderText after you've bound the GridView.</p>
<p>If you want a GridView that takes into account some attribute you placed on the properties of your bound class, I believe you'll need to create your own GridView. </p>
<p>I may be wrong, but I've not seen any ASP.NET Grid from control vendors (at least Telerik , Janus Systems and Infragistics) do that. If you do it, maybe sell the idea to them.</p>
|
Sharepoint List Definition that binds only to my Custom Content Type <p>I am developing a Sharepoint Solution, that implements a new list. This list has an event receiver attached to a Custom Content type. </p>
<p>I am using VSeWSS 1.3 for this task and it's going ok (the content type gets created, a list is created and bound to the content type, the event receiver triggers successfully.</p>
<p>My only concern is that in the created list, it always show the base Content Type (Item CT with Title field). Through the Web GUI I can hide this content type, but I can't find where to do that in my XML definitions, or make it on the solution to avoid double tasks when deploying.</p>
<p>Any suggestions??</p>
| <p>You will have to edit the Schema.xml for your custom list. Find the <code><ContentTypes></code> tag and remove any you do not wish to be shown.</p>
<p>Your list definition will have a guid (eg. <code><Elements Id="0a8594c8-5cf1-492e-88ce-df943830c88c"</code>) that will specify the list from the schema xml (e.g.<code><List Name="... ...Id="0a8594c8-5cf1-492e-88ce-df943830c88c"></code>)</p>
<p>I am not sure what the implementation is for, usually there is a feature.xml to combine the previous xml files together (e.g.<code><ElementManifests><ElementManifest Location="MyFeature\ListDefinition.xml" /><ElementFile Location="MyFeature\schema.xml" /></code>)</p>
|
List all Tests Found by Nosetest <p>I use <code>nosetests</code> to run my unittests and it works well. I want to get a list of all the tests <code>nostests</code> finds without actually running them. Is there a way to do that?</p>
| <p>Version 0.11.1 is currently available. You can get a list of tests without running them as follows:</p>
<pre><code>nosetests -v --collect-only
</code></pre>
|
A copyright / license comment for common utility apps while do contract work <p>I'm doing some contract work who need the source code for the application I'm writing. For the new files I'm writing for the customer, I'm giving them the copyright. However, there are some utility files (for OS abstractions like threading) I'm using that I've developed on my own (not on the customer's dime). I want to keep the right to use these files for my own future projects or future contracting jobs.</p>
<p>My question is, what type of license and copyright statement do I provide at the top of the source code file? I am considering something similar to the Boost Software License:</p>
<blockquote>
<p>Copright (c) 2009 [my legal name]</p>
<p>Permission is hereby granted to [customer legal name], free of charge, to
use, reproduce, modify, display, distribute, execute, and transmit the Software,
and to prepare derivative works of the Software, and to permit third-parties
to whom the Software is furnished to do so, all subject to the following:</p>
<p>The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.</p>
<p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.</p>
</blockquote>
<p>Is this license and copyright notice sufficient? Is there anyone in a similar situation that can post their license?</p>
<p><strong>EDIT</strong></p>
<p>The files that I'm concerned about right now are pretty simple -- just thin wrappers around OS-specific stuff (such as threading and mutexes). This isn't a library that I'd sell as a stand alone product, and is not something I'm concerned about the customer using or distributing in the future.</p>
<p>If I were to produce a library that I would intend to sell, I'd use a different license (for which I would most likely contact a lawyer).</p>
<p>It's just convenient to use these files on projects and I would hate to have the customer claim I could not use the software on future projects without paying them a royalty fee.</p>
| <p>Not to sound trite, but your best option is to ask a lawyer. Shouldn't be more than a few hundred dollars.</p>
|
Need help to decide what is the best solution to tracking system (.NET) <p>That is my first question around here, my name is Anna!</p>
<p>My problem:
My client has several personal devices (blackbox with gps) to locate people/car... There are about 12000 people/car using that device... It sends their location to specified IP/Port... I can´t do anything on that side...</p>
<p>My job?
Devolope a listener to catch all data sended by devices and load that in database using .NET...</p>
<p>My idea:
A Window Service using threads (maybe ThreadPool?). So the service will catch all incoming messages, create a thread and put into DB...</p>
<p>Is that the best solution for the problem?
I was reading here about Message Queue (MSMQ)... Do you think should I use that?</p>
<p>Anna</p>
| <p>The number of locations / time, as well as the way the location information is transmitted (is it TCP, UDP, etc) will help determine the optimal approach.</p>
<p>Some questions:</p>
<ul>
<li>How frequently do the 12000 devices send a message?</li>
<li>How are the locations transmitted? UDP? TCP?</li>
<li>What reliability requirements do you have?</li>
</ul>
<p>From the sounds of it, having a service that can capture the requests and just maintain a queue internally of things to save to the database should work fine. I don't believe MSMQ will be of use to you unless you can change the transmission side, and even then, it may or may not be necessary.</p>
<p><hr /></p>
<p>EDIT: Given the comments below, I would suggest something where you have a TCP listener pass requests off to the threadpool to handle.</p>
<p>I would take a look at <a href="http://www.java2s.com/Tutorial/CSharp/0580%5F%5FNetwork/ThreadPoolbasedTcpserver.htm" rel="nofollow">this tutorial</a> about setting up a TCP listening server using the thread pool. The biggest potential problem I see is the number of requests - from what you're saying, you're going to have roughly 400 requests / second. This is going to be a bit of a challenge to handle without a pretty good system in place. The threadpool will probably perform better than trying to do your own threading, since you'll want to avoid the overhead of having to create new threads constantly. You'll definitely want to have very little delay in the main processing loop (like Sleep(0), or no sleep at all), since you'll have one request per 2.5 ms on average. A single Sleep tends to time slice at 14-15 ms minimum, so you probably won't want any sleep in the loop.</p>
<p>I would say, though, that you may find this doesn't work too well, since the raw amount of connections may be problematic. If there is any way you could convert to UDP packets being sent, it may get you better throughput (at the expense of some reliability).</p>
|
What's your choice for your next ASP.NET project: Web Forms or MVC? <p>Let's say that you will start a new ASP.NET web site/application tomorrow. Would you chose Web Forms or MVC, and why?</p>
| <p>MVC baby! And JQuery!</p>
<p>Edit: OK, it's fair enough to say my response warrants a little more info. </p>
<p>I'd choose MVC for the following reasons:</p>
<ol>
<li>I have worked in Rails and found it highly productive. ASP MVC has borrowed so much from Rails that it feels like a direct port in some ways (and that's a good thing in my mind).</li>
<li>AJAX is important, but I <em>hate</em> the Microsoft "Atlas" approach to AJAX (whatever the product name is these days). If you're going to do AJAX, you need to understand the HTML and the JavaScript. Frameworks that hide that from you are hurting you more than they are helping you (IMO).</li>
<li>JQuery has taken over the world it seems in terms of JavaScript frameworks. ASPMVC is well-integrated with it. I want to learn it, so there's great alignment here.</li>
<li>The whole "control" model is a neat idea, but it is more complicated than it appears on the surface. For example, look around on SO for questions about how a UserControl can find its highest level containing control and so forth. The control hierarchy abstraction has leaks in it. Grids are great if they do what you want out of the box, but it's very very hard to customize them to do something they weren't made to do. And the best grid controls on the market (the ones that are highly customizable) are large, bloated, overly complicated beasts. Maybe that shows us that we should drop back down to HTML and let loops in our views do that kind of thing for us.</li>
<li>I believe I can build complete, beautiful apps in ASPMVC much faster than in ASP.Net (and I've got some years of ASP.Net under my belt). Look at StackOverflow ... built quickly on ASPMVC with JQuery, and it's fast, scalable and a joy to use IMO.</li>
<li>Oh, and it's completely open source! It is ok to read the source code, blog about it, and even modify then redistribute it! </li>
</ol>
|
Weird error with Locale.getISOCountries() <p>I'm using this code:</p>
<pre><code> for (final String code : Locale.getISOCountries())
{
//stuff here
}
</code></pre>
<p>But on compile I get this error:</p>
<pre><code>[ERROR] Line 21: No source code is available for type java.util.Locale; did you forget to inherit a required module?
</code></pre>
<p>And then a stack trace of compiler errors.</p>
<p>I'm doing both of these imports at the beginning of the class:</p>
<pre><code>package com.me.example;
import java.util.Locale;
import java.util.*;
</code></pre>
<p>What can be wrong?</p>
<p>In Netbeans i see the autocomplete options and no syntax error for the Locale object...</p>
| <p>Something screwy with your setup, the folllowing program works fine for me.</p>
<pre><code>import java.util.*;
import java.util.Locale;
public class Donors {
public static void main (String [] args) {
for (final String code : Locale.getISOCountries()) {
System.out.println (code);
}
}
}
</code></pre>
<p>The fact that it's asking for <em>source</em> code leads me to believe that it's trying to compile or run it in some sort of debugging mode. You shouldn't need the source code for java.util.* to compile, that's just bizarre.</p>
<p>See if my simple test program works in your environment, then try looking for something along those lines (debugging options). Final step: compile <strong>your</strong> code with the baseline javac (not NetBeans).</p>
<p><strong>UPDATE:</strong></p>
<p>Actually, I have found something. If you are creating GWT applications, I don't think <code>java.util.Locale</code> is available on the client side (only the server side). All of the references on the web to this error message point to GWT and its limitations on the client side which are, after all, converted to Javascript goodies, so cannot be expected to support the entire set of Java libraries.</p>
<p>This page <a href="http://www.ociweb.com/mark/programming/GWT.html" rel="nofollow">here</a> shows how to do i18n on GWT apps and there's no mention of <code>java.util.Locale</code> except on the server side.</p>
|
GetTcpTable equivalent on Linux <p>Is there an API call on Linux which returns currently opened TCP connections on the system (like <a href="http://msdn.microsoft.com/en-us/library/aa366026%28VS.85%29.aspx" rel="nofollow">GetTcpTable</a> call on Windows)?</p>
<p>Thanks.</p>
| <p>As per UNIX philosophy of "everything is a file", you can get what you want from reading <code>/proc/net/tcp</code>.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.