instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>We're doing windows mobile development using the WM6 Professional emulator through visual studio 2008 for now. My question is, can you get the emulator image to simulate having a storage card? We run our SQLCE 3.5 database off the removable storage card in our devices and it'd be slick to just have the emulator simulate this situation as well. We've looked through the emulator configuration settings and didn't come across this option.</p>
<p>We've got the mobile devices sitting on the desk so we could always just deploy to them directly to solve this issue, but I figured it was worth polling the group anyhow.</p>
|
<p>Yes, it is possible to setup a storage card for the emulator.</p>
<p>In the emulator window, goto File/Configure. On the General tab there is a setting for Shared Folder. You can point this at a directory on your host machine. The directory will show up as a storage cord on the em.</p>
|
<p>As already mentioned, yes the Storage card is emulated. Thought its good to always test on a real hardware device before releasing. I have found that sometimes the Storage Card on the emulator is not 100% consistent with hardware access. Actually, the emulator can be a bit buggy in this regard.</p>
<p>For example, I use SQLITE extensively in my PDA applications. Sometimes I cant get the emulator to create a new database file, even though the same code works perfectly on a device.</p>
<p>Point: Its great for testing, but will fail occasionally and if some code is not executing that you think should.... run it on a hardware device before wasting hours troubleshooting it on the emulator.</p>
| 43,335
|
<p>When writing multi-threaded applications, one of the most common problems experienced are deadlocks. </p>
<p>My questions to the community are:</p>
<ol>
<li><p>What is a deadlock? </p></li>
<li><p>How do you detect them? </p></li>
<li><p>Do you handle them? </p></li>
<li><p>And finally, how do you prevent them from occurring?</p></li>
</ol>
|
<p>A <strong>lock</strong> occurs when multiple processes try to access the same resource at the same time.</p>
<p>One process loses out and must wait for the other to finish.</p>
<p>A <strong>deadlock</strong> occurs when the waiting process is still holding on to another resource that the first needs before it can finish.</p>
<p>So, an example:</p>
<p>Resource A and resource B are used by process X and process Y</p>
<ul>
<li>X starts to use A.</li>
<li>X and Y try to start using B</li>
<li>Y 'wins' and gets B first</li>
<li>now Y needs to use A</li>
<li>A is locked by X, which is waiting for Y</li>
</ul>
<p>The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can.</p>
<p>In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible.</p>
|
<p>Mutex in essence is a lock, providing protected access to shared resources. Under Linux, the thread mutex data type is pthread_mutex_t. Before use, initialize it.</p>
<p>To access to shared resources, you have to lock on the mutex. If the mutex already on the lock, the call will block the thread until the mutex is unlocked. Upon completion of the visit to shared resources, you have to unlock them.</p>
<p>Overall, there are a few unwritten basic principles:</p>
<ul>
<li><p>Obtain the lock before using the shared resources.</p></li>
<li><p>Holding the lock as short time as possible.</p></li>
<li><p>Release the lock if the thread returns an error.</p></li>
</ul>
| 5,479
|
<p>I want to send an email from my iPhone application. I have heard that the iOS SDK doesn't have an email API. I don't want to use the following code because it will exit my application:</p>
<pre><code>NSString *url = [NSString stringWithString: @"mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
</code></pre>
<p>So how can I send an email from my app?</p>
|
<p>On iOS 3.0 and later you should use the <code>MFMailComposeViewController</code> class, and the <code>MFMailComposeViewControllerDelegate</code> protocol, that is tucked away in the MessageUI framework.</p>
<p>First add the <a href="https://developer.apple.com/documentation/messageui" rel="nofollow noreferrer">framework</a> and import:</p>
<pre><code>#import <MessageUI/MFMailComposeViewController.h>
</code></pre>
<p>Then, to send a message:</p>
<pre><code>MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"My Subject"];
[controller setMessageBody:@"Hello there." isHTML:NO];
if (controller) [self presentModalViewController:controller animated:YES];
[controller release];
</code></pre>
<p>Then the user does the work and you get the delegate callback in time:</p>
<pre><code>- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
</code></pre>
<p>Remember to check if the device is configured for sending email:</p>
<pre><code>if ([MFMailComposeViewController canSendMail]) {
// Show the composer
} else {
// Handle the error
}
</code></pre>
|
<p>I wrote a simple wrapper called KRNSendEmail that simplify sending email to one method call.<br><br>
The KRNSendEmail is well documented and added to CocoaPods.
<br><br>
<a href="https://github.com/ulian-onua/KRNSendEmail" rel="nofollow noreferrer">https://github.com/ulian-onua/KRNSendEmail</a></p>
| 40,068
|
<p>I tried committing files with CRLF-ending lines, but it failed.</p>
<p>I spent a whole work day on my Windows computer trying different strategies and was almost drawn to stop trying to use Git and instead try <a href="http://en.wikipedia.org/wiki/Mercurial" rel="noreferrer">Mercurial</a>.</p>
<p>How to properly handle CRLF line endings?</p>
|
<p>Almost four years after asking this question, I have finally
found <strong>an answer that completely satisfies me</strong>!</p>
<p>See the details in <strong>github:help</strong>'s guide to
<a href="https://help.github.com/articles/dealing-with-line-endings/">Dealing with line endings</a>.</p>
<blockquote>
<p>Git allows you to set the line ending properties for a
repo directly using the <a href="http://git-scm.com/docs/gitattributes#_checking-out_and_checking-in">text attribute</a> in the
<strong><code>.gitattributes</code></strong> file. This file is committed into
the repo and overrides the <code>core.autocrlf</code> setting,
allowing you to ensure consistent behaviour for all
users regardless of their git settings.</p>
</blockquote>
<p>And thus</p>
<blockquote>
<p>The advantage of this is that your end of line
configuration now travels with your repository and you
don't need to worry about whether or not collaborators
have the proper global settings.</p>
</blockquote>
<p>Here's an example of a <strong><code>.gitattributes</code></strong> file</p>
<pre class="lang-sh prettyprint-override"><code># Auto detect text files and perform LF normalization
* text=auto
*.cs text diff=csharp
*.java text diff=java
*.html text diff=html
*.css text
*.js text
*.sql text
*.csproj text merge=union
*.sln text merge=union eol=crlf
*.docx diff=astextplain
*.DOCX diff=astextplain
# absolute paths are ok, as are globs
/**/postinst* text eol=lf
# paths that don't start with / are treated relative to the .gitattributes folder
relative/path/*.txt text eol=lf
</code></pre>
<p>There is a convenient <a href="https://github.com/Danimoth/gitattributes">collection of ready to use .gitattributes files</a> for the most popular programming languages. It's useful to get you started.</p>
<p>Once you've created or adjusted your <strong><code>.gitattributes</code></strong>, you should perform a once-and-for-all <a href="https://help.github.com/articles/dealing-with-line-endings/#refreshing-a-repository-after-changing-line-endings">line endings re-normalization</a>.</p>
<p>Note that the <a href="https://desktop.github.com">GitHub Desktop</a> app can suggest and create a <strong><code>.gitattributes</code></strong> file after you open your project's Git repo in the app. To try that, click the gear icon (in the upper right corner) > Repository settings ... > Line endings and attributes. You will be asked to add the recommended <strong><code>.gitattributes</code></strong> and if you agree, the app will also perform a normalization of all the files in your repository.</p>
<p>Finally, the <a href="http://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/">Mind the End of Your Line</a> article
provides more background and explains how Git has evolved
on the matters at hand. I consider this <em>required reading</em>.</p>
<p>You've probably got users in your team who use EGit or JGit (tools like Eclipse and TeamCity use them) to commit their changes. Then you're out of luck, as @gatinueta explained in this answer's comments:</p>
<blockquote>
<p>This setting will not satisfy you completely if you have people working with Egit or JGit in your team, since those tools will just ignore .gitattributes and happily check in CRLF files <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372">https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372</a></p>
</blockquote>
<p>One trick might be to have them commit their changes in another client, say <a href="http://www.sourcetreeapp.com">SourceTree</a>. Our team back then preferred that tool to Eclipse's EGit for many use cases.</p>
<p>Who said software is easy? :-/</p>
|
<p>This is just a <strong>workaround</strong> solution:</p>
<p>In normal cases, use the solutions that are shipped with git. These work great in most cases. Force to LF if you share the development on Windows and Unix based systems by setting <strong>.gitattributes</strong>.</p>
<p>In my case there were >10 programmers developing a project in Windows. This project was checked in with CRLF and <strong>there was no option to force to LF.</strong></p>
<p>Some settings were internally written on my machine without any influence on the LF format; thus some files were globally changed to LF on each small file change.</p>
<p>My solution:</p>
<p><strong>Windows-Machines:</strong>
Let everything as it is. Care about nothing, since you are a default windows 'lone wolf' developer and you have to handle like this: "There is no other system in the wide world, is it?"</p>
<p><strong>Unix-Machines</strong></p>
<ol>
<li><p>Add following lines to a config's <code>[alias]</code> section. This command lists all changed (i.e. modified/new) files:</p>
<pre class="lang-sh prettyprint-override"><code>lc = "!f() { git status --porcelain \
| egrep -r \"^(\?| ).\*\\(.[a-zA-Z])*\" \
| cut -c 4- ; }; f "
</code></pre></li>
<li><p>Convert all those <strong>changed</strong> files into dos format:</p>
<pre class="lang-sh prettyprint-override"><code>unix2dos $(git lc)
</code></pre></li>
<li><p>Optionally ...</p>
<ol>
<li><p>Create a git <a href="http://git-scm.com/book/en/Customizing-Git-Git-Hooks" rel="nofollow noreferrer">hook</a> for this action to automate this process</p></li>
<li><p>Use params and include it and modify the <code>grep</code> function to match only particular filenames, e.g.: </p>
<pre class="lang-sh prettyprint-override"><code>... | egrep -r "^(\?| ).*\.(txt|conf)" | ...
</code></pre></li>
<li><p>Feel free to make it even more convenient by using an additional shortcut:</p>
<pre class="lang-sh prettyprint-override"><code>c2dos = "!f() { unix2dos $(git lc) ; }; f "
</code></pre>
<p>... and fire the converted stuff by typing</p>
<pre class="lang-sh prettyprint-override"><code>git c2dos
</code></pre></li>
</ol></li>
</ol>
| 20,619
|
<p>I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people.</p>
<pre><code>int Until = 20000000;
BitArray PrimeBits = new BitArray(Until, true);
/*
* Sieve of Eratosthenes
* PrimeBits is a simple BitArray where all bit is an integer
* and we mark composite numbers as false
*/
PrimeBits.Set(0, false); // You don't actually need this, just
PrimeBits.Set(1, false); // remindig you that 2 is the smallest prime
for (int P = 2; P < (int)Math.Sqrt(Until) + 1; P++)
if (PrimeBits.Get(P))
// These are going to be the multiples of P if it is a prime
for (int PMultiply = P * 2; PMultiply < Until; PMultiply += P)
PrimeBits.Set(PMultiply, false);
// We use this to store the actual prime numbers
List<int> Primes = new List<int>();
for (int i = 2; i < Until; i++)
if (PrimeBits.Get(i))
Primes.Add(i);
</code></pre>
<p>Maybe I could use multiple <code>BitArray</code>s and <a href="http://msdn.microsoft.com/en-us/library/system.collections.bitarray.and.aspx" rel="noreferrer">BitArray.And()</a> them together?</p>
|
<p>You might save some time by cross-referencing your bit array with a doubly-linked list, so you can more quickly advance to the next prime.</p>
<p>Also, in eliminating later composites once you hit a new prime p for the first time - the first composite multiple of p remaining will be p*p, since everything before that has already been eliminated. In fact, you only need to multiply p by all the remaining potential primes that are left after it in the list, stopping as soon as your product is out of range (larger than Until).</p>
<p>There are also some good probabilistic algorithms out there, such as the Miller-Rabin test. <a href="http://en.wikipedia.org/wiki/Primality_test" rel="noreferrer">The wikipedia page</a> is a good introduction.</p>
|
<pre><code> void PrimeNumber(long number)
{
bool IsprimeNumber = true;
long value = Convert.ToInt32(Math.Sqrt(number));
if (number % 2 == 0)
{
IsprimeNumber = false;
MessageBox.Show("No It is not a Prime NUmber");
return;
}
for (long i = 3; i <= value; i=i+2)
{
if (number % i == 0)
{
MessageBox.Show("It is divisible by" + i);
IsprimeNumber = false;
break;
}
}
if (IsprimeNumber)
{
MessageBox.Show("Yes Prime NUmber");
}
else
{
MessageBox.Show("No It is not a Prime NUmber");
}
}
</code></pre>
| 5,073
|
<p>Returning to WinForms in VS2008 after a long time.. Tinkering with a OOD problem in VS2008 Express Edition.</p>
<p>I need some controls to be "display only" widgets. The user should not be able to change the value of these controls... the widgets are updated by a periodic update tick event. I vaguely remember there being a ReadOnly property that you could set to have this behavior... can't find it now.</p>
<p>The <strong>Enabled</strong> property set to false: grays out the control content. I want the control to look normal.
The <strong>Locked</strong> property set to false: seems to be protecting the user from accidentally distorting the control in the Visual Form Designer.</p>
<p>What am I missing? </p>
|
<p>For some typical winforms controls:</p>
<p><a href="http://jquiz.wordpress.com/2007/05/29/c-winforms-readonly-controls/" rel="noreferrer">http://jquiz.wordpress.com/2007/05/29/c-winforms-readonly-controls/</a></p>
<p>This is also a good tip to preserve the appearance:</p>
<pre><code> Color clr = textBox1.BackColor;
textBox1.ReadOnly = true;
textBox1.BackColor = clr;
</code></pre>
|
<p>I was given this same requirement at work yesterday. Except instead of a textbox I had to make an entire form disabled without changing it's color.</p>
<p>So I replaced a call to</p>
<pre><code>form->Enabled = false;
</code></pre>
<p>with</p>
<pre><code>IntPtr hWnd = form->Handle;
HWND window_handle = (HWND)hWnd.ToPointer();
::EnableWindow(window_handle, aEnable ? TRUE:FALSE);
</code></pre>
<p>Which worked well. You can see above that I am using managed C++. The entire form is now disabled, but not greyed out.</p>
| 31,941
|
<p>I have a binary file - Windows static library (*.lib).<br>
Is there a simple way to find out names of the functions and their interface from that library ?</p>
<p>Something similar to <code>emfar</code> and <code>elfdump</code> utilities (on Linux systems) ?</p>
|
<p>Assuming you're talking about a static library, <code>DUMPBIN /SYMBOLS</code> shows the functions and data objects in the library. If you're talking about an import library (a <code>.lib</code> used to refer to symbols exported from a DLL), then you want <code>DUMPBIN /EXPORTS</code>.</p>
<p>Note that for functions linked with the "C" binary interface, this still won't get you return values, parameters, or calling convention. That information isn't encoded in the <code>.lib</code> at all; you have to know that ahead of time (via prototypes in header files, for example) in order to call them correctly.</p>
<p>For functions linked with the C++ binary interface, the calling convention and arguments are encoded in the exported name of the function (also called "name mangling"). <code>DUMPBIN /SYMBOLS</code> will show you both the "mangled" function name as well as the decoded set of parameters.</p>
|
<p>1) Open a Developer Command Prompt for VS 2017 (or whatever version you have on your machine)(It should be located under: Start menu --> All programs --> Visual Studio 2017 (or whatever version you have on your machine) --> Visual Studio Tools
--> Developer Command Prompt for VS 2017.</p>
<p>2) Enter the following command:</p>
<p><code>dumpbin /EXPORTS my_lib_name.lib</code></p>
| 39,257
|
<p>I have a simple message box in a WPF application that is launched as below:</p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Howdy", "Howdy");
}
</code></pre>
<p>I can get <a href="http://www.codeplex.com/white" rel="nofollow noreferrer" title="white">white</a> to click my button and launch the message box. </p>
<p>UISpy shows it as a child of my window I couldn't work out the method to access it.</p>
<p>How do I get access to my MessageBox to verify its contents?</p>
|
<p>Found it! The window class has a MessageBox method that does the trick:</p>
<pre><code> var app = Application.Launch(@"c:\ApplicationPath.exe");
var window = app.GetWindow("Window1");
var helloButton = window.Get<Button>("Hello");
Assert.IsNotNull(helloButton);
helloButton.Click();
var messageBox = window.MessageBox("Howdy");
Assert.IsNotNull(messageBox);
</code></pre>
|
<p>Contained in the White source code are some UI tests projects (to test White itself).</p>
<p>One of the test includes MessageBox tests, which includes a way to obtain the displayed message.</p>
<pre><code>[TestFixture, WinFormCategory, WPFCategory]
public class MessageBoxTest : ControlsActionTest
{
[Test]
public void CloseMessageBoxTest()
{
window.Get<Button>("buttonLaunchesMessageBox").Click();
Window messageBox = window.MessageBox("Close Me");
var label = window.Get<Label>("65535");
Assert.AreEqual("Close Me", label.Text);
messageBox.Close();
}
[Test]
public void ClickButtonOnMessageBox()
{
window.Get<Button>("buttonLaunchesMessageBox").Click();
Window messageBox = window.MessageBox("Close Me");
messageBox.Get<Button>(SearchCriteria.ByText("OK")).Click();
}
}
</code></pre>
<p>Evidently, the label used to display the text message is owned by the window displaying the messagebox, and its primary identification is the max word value (65535).</p>
| 17,340
|
<p>Is it acceptable to submit from an http form through https? It seems like it should be secure, but it allows for a man in the middle attack (<a href="http://ask.metafilter.com/48531/are-http-forms-posted-thru-https-secure" rel="noreferrer">here is a good discussion</a>). There are sites like <a href="http://www.mint.com" rel="noreferrer">mint.com</a> that allow you to sign-in from an http page but does an https post. In my site, the request is to have an http landing page but be able to login securely. Is it not worth the possible security risk and should I just make all users go to a secure page to login (or make the landing page secure)?</p>
|
<p>Posting a form from an http page to an https page does encrypt the data in the form when it is transmitted in the most simple terms. If there is a man-in-the-middle attack, the browser will warn you.</p>
<p>However, if the original http form was subjected to man-in-the-middle and the https post-back address was modified by the attacker, then you will get no warning. The data will still actually be encrypted, but the man-in-the-middle attacker would be able to decrypt (since he sent you the key in the first place) and read the data.</p>
<p>Also, if the form is sending things back through other means (scripted connections) there may be a possibility of unencrypted data being sent over the wire before the form is posted (although any good website would never do this with any kind of sensitive data).</p>
|
<p>I think the main consideration of this question has to do with the URL that users know and the protocol scheme (http:)that browsers substitute by default.</p>
<p>In that case, the normal behavior of a site that wants to ensure an encrypted channel is to have the <a href="http://home-page" rel="nofollow noreferrer">http://home-page</a> redirect to <a href="https://home-page" rel="nofollow noreferrer">https://home-page</a>. There is still a spoofing / MitM opportunity, but if it is by DNS poisoning, the risk is no higher than if one starts out with the https: URL. If a different domain name comes back, you need to worry then.</p>
<p>This is probably safe enough. After all, if you are subject to a targetted MitM, you might as well start worrying about keyboard loggers, your local HOSTS file, and all sorts of other ways of finding out about your secure transactions involving your system already being owned.</p>
| 34,548
|
<p>Other than <code>self.class.send :method, args...</code>, of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code.</p>
<hr>
<p><strong>UPDATE:</strong> </p>
<p>@Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that <code>private</code> doesn't work on class methods, though this will declare a private class method:</p>
<pre><code>class Foo
class <<self
private
def bar
puts 'bar'
end
end
end
Foo.bar
# => NoMethodError: private method 'bar' called for Foo:Class
</code></pre>
|
<p>Here is a code snippet to go along with the question. Using "private" in a class definition does not apply to class methods. You need to use "private_class_method" as in the following example.</p>
<pre><code>class Foo
def self.private_bar
# Complex logic goes here
puts "hi"
end
private_class_method :private_bar
class <<self
private
def another_private_bar
puts "bar"
end
end
public
def instance_bar
self.class.private_bar
end
def instance_bar2
self.class.another_private_bar
end
end
f=Foo.new
f=instance_bar # NoMethodError: private method `private_bar' called for Foo:Class
f=instance_bar2 # NoMethodError: private method `another_private_bar' called for Foo:Class
</code></pre>
<p>I don't see a way to get around this. The documentation says that you cannot specify the receive of a private method. Also you can only access a private method from the same instance. The class Foo is a different object than a given instance of Foo.</p>
<p>Don't take my answer as final. I'm certainly not an expert, but I wanted to provide a code snippet so that others who attempt to answer will have properly private class methods.</p>
|
<p>Unless I'm misunderstanding, don't you just need something like this:</p>
<pre><code>class Foo
private
def Foo.bar
# Complex logic goes here
puts "hi"
end
public
def bar
Foo.bar
end
end
</code></pre>
<p>Of course you could change the second definition to use your self.class.send approach if you wanted to avoid hardcoding the class name... </p>
| 4,099
|
<p>I've got a tomcat 6 web app running with Apache httpd as the front end. I'm using mod_proxy and mod_proxy_ajp to forward the requests to tomcat. My server is running Ubuntu. Now I'm trying to use mod_rewrite to remove the leading www, so that my canonical website URL is <code>http://example.com</code> rather than <code>http://www.example.com</code></p>
<p>I've read a number of tutorials on using mod_rewrite, but I can't get any rewriting to work. I've tried putting the rewrite rule in an <code>.htaccess</code> file (after modifying my <code>/etc/apache/sites-available/default</code> file to set AllowOverride all). I've tried putting the rewrite rule in <code>apache2.conf</code>, <code>httpd.conf</code>, and <code>rewrite.conf</code>. I've tried all of these with rewrite logging turned on. The log file gets created, but Apache has written nothing to it. I thought maybe mod_proxy was somehow preventing the rewrite rules from being used, so I tried disabling that as well...and I still get no rewrite, and nothing to the log.</p>
<p>At this point I have absolutely no idea what to try next. How do I go about troubleshooting why Apache isn't using my rewrite rules?</p>
<p>For reference, here are my rewrite directives:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
</IfModule>
</code></pre>
<p>the responses below are helpful to my particular case, but probably not as helpful to the community-at-large as answers about how you troubleshoot Apache directives in general. For example, is there a way to enable logging to the point where it would tell me which directives are being applied in which order as the request comes in?</p>
<p><strong>Edit 2</strong>: I've gotten things to work now. My virtual hosts weren't quite set up right, and I also didn't quite have the rewrite regex right. Here is the final rewrite directives I got to work:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com$1 [L,R=301]
</IfModule>
</code></pre>
|
<p><strong>Trying to answer your question</strong>: To debug Apache operation you can adjust the <a href="http://httpd.apache.org/docs/2.2/mod/core.html#loglevel" rel="nofollow noreferrer">LogLevel</a> to a lower level (maybe <code>debug</code>). But even if you put <code>debug</code> if you disable the Log for the module in question you dont get any messages from it. For instance, the default <code>[RequestLogLevel][2]</code> is 0, e.g., the module dont write any messages. I see you setted it to 3 but like <a href="https://stackoverflow.com/questions/215316/how-do-i-troubleshoot-why-my-rewrite-rules-arent-being-applied-by-apache#215345">RoBorg</a> said change it to <code>9</code> that maybe is too low for your case.</p>
<p><strong>Trying to sove your problem</strong>: Try to change the way you rewrite the hostname using the inverse form - look if the hostname is what you want and, if not, change it to the hostname you want. Like stated in the <a href="http://httpd.apache.org/docs/2.2/misc/rewriteguide.html" rel="nofollow noreferrer">URL Rewriting Guide - Apache HTTP Server</a> at the Apache Site:</p>
<blockquote>
<p><strong>Canonical Hostnames</strong></p>
<p><strong>Description</strong>:
The goal of this rule is to force the use of a particular hostname, in
preference to other hostnames which
may be used to reach the same site.
For example, if you wish to force the
use of www.example.com instead of
example.com, you might use a variant
of the following recipe. Solution:</p>
<pre><code># To force the use of
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://www.example.com/$1 [L,R]
</code></pre>
</blockquote>
<p>In their example, they change from <code>example.com</code> to <code>www.example.com</code> but you got the idea. Just adjust it for your case.</p>
|
<p>Try increasing the logging level up to 9 (the maximum).<br>
Be sure apache has the proper rights to the log file (although if it created it, it seems likely it could write to it too).<br>
Try a different rewrite rule, with no condition, for example <code>RewriteRule .* www.google.com [RL]</code></p>
| 26,465
|
<p>Can I expose a class from another .net namespace as a class in my namespace? I use a class - antlr.collections.AST - as the return type for a function belonging to a class in my namespace; as a result, the user has to have</p>
<pre><code>using antlr.collections;
using myNamespace;
</code></pre>
<p>at the top of their files in order to use my function. Can I make myNamespace.AST an alias for antlr.collections.AST, such that the user only has to have</p>
<pre><code>using myNamespace;
</code></pre>
<p>at the top of their files?</p>
|
<p>Bear in mind that the consumers of your code won't actually <em>need</em> to have using statements. Those are there to make their lives easier, so they don't have to type antlr.collections.Foo and antlr.collections.Bar all over their source.</p>
<p>The bigger "impact" (if indeed there really is a severe one) is that the consumer of your code will need a hard reference to the assembly where antlr.collections is defined. </p>
<p>However, if that's documented up front, I honestly don't see it being that big of a problem. It's no different than the consumer of a SubSonic-generated DAL needing references both to the generated DAL assembly and the original SubSonic assembly. (And, quite possibly, using statements as well.)</p>
<p>Dependencies are what they are. There's a reason classes are broken into namespaces -- primarily for organization and to reduce naming conflicts. Not knowing what classes are in the namespace you mention, I don't know how likely such a conflict actually is in your scenario ... But attempting to move the class from one namespace to another, or to hide the fact that such is needed by deriving a blank class from it, is probably not the best idea. It won't kill the consumers of your class to have another reference and using statement.</p>
|
<p>No, you can't.</p>
<p>The full path to and name of a class is part of its identity.</p>
| 16,793
|
<p>I have an excel file which has more than 65536 rows. However, I can see only first 65536 of them. Is it possible to see all of them in Excel 2007?</p>
|
<p>Here is an interesting <a href="http://blogs.msdn.com/excel/archive/2005/09/26/474258.aspx" rel="noreferrer">blog entry about numbers / limitations of Excel 2007</a>. According to the author the new limit is approximately <strong>one million rows</strong>.</p>
<p>Sounds like you have a <strong>pre-Excel 2007 workbook open in Excel 2007 in compatibility mode</strong> (look in the title bar and see if it says compatibility mode). If so, the workbook has 65,536 rows, not 1,048,576. You can save the workbook as an Excel workbook which will be in Excel 2007 format, close the workbook and re-open it. </p>
|
<p>Yes, the new limit is approximately 1 million rows.</p>
<p><a href="http://blogs.msdn.com/excel/archive/2005/09/26/474258.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/excel/archive/2005/09/26/474258.aspx</a></p>
| 24,069
|
<p>I was curious what the differences are between the debug and release modes of the .NET compiler and came across these questions about <a href="https://stackoverflow.com/questions/90871/debug-vs-release-in-net">debug vs release in .NET</a> and <a href="https://stackoverflow.com/questions/312312/what-are-some-reasons-a-release-build-would-run-differently-than-a-debug-build">reasons that release will behave differently than debug</a>. Up to this point I really haven't paid much attention to these compiler modes. Now I will. </p>
<p>My question is, assuming that I am using a testing framework (NUnit) and TDD, would I run into any issues if I simply always compiled in release mode?</p>
|
<p>You're using TDD. You write your test. The test fails. You write the code to pass the test. The code fails. You look at the code you wrote and can't see any obvious reason why it fails. Do you reason some more or start up the test in the debugger (using TestDriven.Net) and step through the test? Maybe I'm just not smart enough to always figure out why my code doesn't work, but I usually do the latter when I'm stumped.</p>
|
<p>For debugging.</p>
<p>Like tvanfosson said, even if you usually don't use the debugger (I know I don't), sometimes you need to.</p>
| 45,129
|
<p>Is it worth learning the convention or is it a bane to readability and maintainability?</p>
|
<p>Considering that most people that use <em>Hungarian Notation</em> is following the misunderstood version of it, I'd say it's pretty pointless.</p>
<p>If you want to use the original definition of it, it might make more sense, but other than that it is mostly syntactic sugar.</p>
<p>If you read the <a href="http://en.wikipedia.org/wiki/Hungarian_notation" rel="noreferrer">Wikipedia article</a> on the subject, you'll find two conflicting notations, <em>Systems Hungarian Notation</em> and <em>Apps Hungarian Notation</em>.</p>
<p>The original, good, definition is the <em>Apps Hungarian Notation</em>, but most people use the <em>Systems Hungarian Notation</em>.</p>
<p>As an example of the two, consider prefixing variables with l for length, a for area and v for volume.</p>
<p>With such notation, the following expression makes sense:</p>
<pre><code>int vBox = aBottom * lVerticalSide;
</code></pre>
<p>but this doesn't:</p>
<pre><code>int aBottom = lSide1;
</code></pre>
<p>If you're mixing the prefixes, they're to be considered part of the equation, and volume = area * length is fine for a box, but copying a length value into an area variable should raise some red flags.</p>
<p>Unfortunately, the other notation is less useful, where people prefix the variable names with the type of the value, like this:</p>
<pre><code>int iLength;
int iVolume;
int iArea;
</code></pre>
<p>some people use n for number, or i for integer, f for float, s for string etc.</p>
<p>The original prefix was meant to be used to spot problems in equations, but has somehow devolved into making the code slightly easier to read since you don't have to go look for the variable declaration. With todays smart editors where you can simply hover over any variable to find the full type, and not just an abbreviation for it, this type of hungarian notation has lost a lot of its meaning.</p>
<p>But, you should make up your own mind. All I can say is that I don't use either.</p>
<hr>
<p><strong>Edit</strong> Just to add a short notice, while I don't use <em>Hungarian Notation</em>, I do use a prefix, and it's the underscore. I prefix all private fields of classes with a _ and otherwise spell their names as I would a property, titlecase with the first letter uppercase.</p>
|
<p>I've been working for IBM for the past 6 months and I haven't seen it anywhere (thank god because I hate it.) I see either camelCase or c_style.</p>
<pre><code>thisMethodIsPrettyCool()
this_method_is_pretty_cool()
</code></pre>
| 2,734
|
<p>I need to develop a system for storing large numbers (10's to 100's of thousands) of objects. Each object is email-like - there is a main text body, and several ancillary text fields of limited size. A body will be from a few bytes, to several KB in size. </p>
<p>Each item will have a single unique ID (probably a GUID) that identifies it. </p>
<p>The store will only be written to when an object is added to it. It will be read often. Deletions will be rare. The data is almost all human readable text so it will be readily compressible.</p>
<p>A system that lets me issue the I/Os and mange the memory and caching would be ideal. </p>
<p>I'm going to keep the indexes in memory, using it to map indexes to the single (and primary) key for the objects. Once I have the key, then I'll load it from disk, or the cache.</p>
<p>The data management system needs to be part of my application - I do not want to depend on OS services. Or separately installed packages. Native (C++) would be best, but a manged (C#) thing would be ok. </p>
<p>I believe that a database is an obvious choice, but this needs to be super-fast for look up and loading into memory of an object. I am not experienced with data base tech and I'm concerned that general relational systems will not handle all this variable sized data efficiently. </p>
<p>(Note, this has nothing to do with my job - its a personal project.)</p>
<p>In your experience, what are the viable alternatives to a traditional relational DB? Or would a DB work well for this? </p>
|
<p>Look at <a href="http://www.sqlite.org" rel="nofollow noreferrer">SQLite</a>, it has bindings for many programming languages and environments available and is, like the <a href="http://en.wikipedia.org/wiki/Berkeley_DB" rel="nofollow noreferrer">Berkeley DB</a>, a database on disk without the need for a database engine installation.</p>
<p>If you just add the right indexes, lookups will be very fast, and since it is a set-based database at heart, you can still do bulk queries and similar.</p>
|
<p>Have a look at <a href="http://webglimpse.net/" rel="nofollow noreferrer">Glimpse</a>.</p>
| 32,619
|
<p>There's an in-house program we use and it's stored on a UNC share so that updates are transparent. I'd like to supply it some command line parameters like so:</p>
<pre><code>\\server\share\in_house_thingy.exe myusername mypassword
</code></pre>
<p>But I can't seem to get it to work in either CMD or PowerShell or via a shortcut.</p>
<p>Anyone got any ideas?</p>
|
<p>You could use:</p>
<pre><code>$app = '\\server\share\in_house_thingy.exe'
$arguments = 'myusername mypassword'
$process = [System.Diagnostics.Process]::Start($app, $arguments)
</code></pre>
<p>The $process object will give you a live process object if you want to get an exit code or other information from that process.</p>
|
<p>I just noticed that there's a .CMD file that's copying the file from the share to the temp directory and running it locally.</p>
<p>If y'all could just vote this answer up if there's no better solution, that'll work.</p>
| 38,824
|
<p>I am trying the FDT editor on a project that previously ran successfully in Flash CS3.</p>
<p>FDT builds and runs it successfully but the SWF is blank (white). I've tried a few viewers on the output file and it is actually blank.</p>
<p>One difference is that now my project doesn't seem to include my entry <code>.fla</code> file. I'm new to Flash/ActionScript and am wondering whether that FLA file included some magic akin to a <code>public static void Main</code> method in other languages.</p>
<p>So, if I'm building an application purely in ActionScript 3 (no <code>.fla</code> files) how do I specify the entrypoint, canvas size, etcetera?</p>
<p>Of course, it's possible that I have set up FDT incorrectly :)</p>
<p><strong>EDIT:</strong> Newbie alert!</p>
<p>Turns out that the white stage I was seeing via FDT was because my FLA was running in a different folder and I couldn't load any of my resources, so nothing was ready to display. I also had FDT configured in such a way that I wasn't seeing the error via the debugger.</p>
<p>This question is a bit dumb. Is it normal to delete questions like this?</p>
<p>For anyone else coming at Flash/ActionScript from a solid programming background, I found this to be a pretty good overview of the display model:</p>
<p><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=05_Display_Programming_02.html#152593" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=05_Display_Programming_02.html#152593</a></p>
|
<p>The equivalent would be the constructor of the main class. That's the class that you specify for compiling (in principle, the rest of the classes are compiled only if they are referenced in code being compiled, be it the main class or any class reference by it).</p>
<p>In the Flash IDE, it would be the constructor of the Document class (if you happen to use one, it's not mandatory) or just the first keyframe in the main timeline.</p>
|
<p>You can ONLY publish fla based content from the Flash IDE, so if you're not going to use that anymore you'll need to publish an assets swf of your graphics, etc.</p>
<p>I presume you're using the MXML compiler? If so check adobe live docs on how to set the stage size etc. </p>
| 28,386
|
<p>I'm using a native DLL (FastImage.dll) in a C# ASP.NET Web Service that sometimes locks (can't delete it---says access denied); this requires stopping IIS to delete the DLL. The inability to delete this DLL in the bin folder of my published Web Service prevents me from publishing successfully (even though it thinks it published successfully!), which makes development and fixing the bug difficult (especially when it just happily runs old code since my changes may not be reflected on the server!). Note that the bug causing the Web Service to bomb and lock up the DLL is in my code, which is outside of said DLL, so I think this is a more general problem than just the FreeImage library (not to bring them any heat).</p>
<ol>
<li>Has anyone experienced this?</li>
<li>Is there a way to make sure that when it says "Publish succeeded" from the VS IDE that it really means it, or to run sort of script to check that the files are really deleted before it attempts to Publish (like a pre-build step in VC++). (Right now I manually delete the files before publishing to make sure that I know the DLLs were replaced, instead of running old DLLs. It's still a problem, though if I can't delete the DLL.)</li>
<li>How would I detect whether a file was successfully deleted from a batch file? (so I can stop and start IIS if it fails)</li>
<li>Is it possible to stop and start IIS from a script (preferably from the Publish... action in the VS IDE) and if so, how?</li>
</ol>
|
<p>Using the IISReset command line tool will only restart IIS on the local machine, not on a remote server to which you are publishing.</p>
<p>Assuming that you are publishing to a Windows 2003 server, I'd suggest trying the slightly less drastic step of stopping and restarting the IIS AppPool in the web site or virtual folder in which the web service runs. (That way you are not taking all sites that run on the target server offline.) This too assumes that the web service runs in its own app pool. Ideally it should, so you keep it isolated.</p>
<p>I'd recommend getting away from using the Publishing process and to look into using a Web Deployment Project. Here is a post on ScottGu's blog detailing <a href="http://weblogs.asp.net/scottgu/archive/2005/11/06/429723.aspx" rel="nofollow noreferrer" title="VS 2005 Web Deployment Projects">VS 2005 Web Deployment Projects</a>.</p>
<p>The advantage to the Web Deployment Project approach is that it provides you with all the power and capability of MSbuild, as it is really just a convenience wrapper around MSBuild. Here's a post from the MSBuild team about <a href="http://blogs.msdn.com/msbuild/archive/2005/10/12/480212.aspx" rel="nofollow noreferrer">pre-build and post-build capabilities</a></p>
<p>Hope this helps.</p>
|
<p>You could use the IISReset command line tool to stop/restart iis. So you could write a simple batch file to stop iis, copy your files, and then restart iis. I'm not sure how to integrate this with the VS publish feature however.</p>
| 5,594
|
<p>I want To open Table By Sql 2008 Enterprise Manager Interface</p>
<p>As in Sql2005 Enterprise Manager Interface by Right Click then Click open Table.</p>
|
<p>Right-click on the table in question and select "Edit Top 200 Rows".</p>
<p>The "200" is configurable from the <strong>Tools\Options</strong> dialog under "<em>SQL Server Object Explorer</em>"</p>
<p>Changing the value for "<em>Value for Edit Top Rows command</em>" to <strong>0</strong> will return all rows for editing in a similar manner to "<em>Open Table</em>" in SSMS 2005.</p>
<p>You can also use <strong>Ctrl+3</strong> to display the underlying SQL after selecting "<em>Edit Top 200 Rows</em>" and manually change the query to customize which rows are show for editing.</p>
|
<p>I think this feature has been removed. Try the "Edit top 200 rows" command. It will do the same, but not fetch every row of a (potentially) huge table.</p>
| 48,445
|
<p>I just pasted some generated javadoc into an eclipse project, to discover none of the HTML is compliant.</p>
<p>There is even cases of closing tags that were never opened.</p>
<p>Is there some way to fix this? Maybe a "be compliant" option...</p>
|
<p>After some googling, I discovered <a href="http://linux.softpedia.com/get/Documentation/XHTML-Doclet-28836.shtml" rel="noreferrer">
XHTML Doclet 0.4</a>.</p>
<blockquote>
<p>XHTML Doclet is a standards-compliant
alternative to the Javadoc standard
HTML doclet. The project revises the
document structure to exclude outdated
tags and inline styles, creates valid
XHTML markup, and provides better
hooks for more flexible CSS
manipulation.</p>
</blockquote>
<p>Looks like someone made a plugin.</p>
<p>Any better options?</p>
<p><b>Edit:</b> Here's the plugin's <a href="http://xhtmldoclet.sourceforge.net/" rel="noreferrer">Official page</a> as linked to by <a href="http://java.sun.com/j2se/javadoc/faq/index.html#xhtmldoclet" rel="noreferrer">Sun's Javadoc FAQ</a>.</p>
|
<p>The short answer is that JavaDocs predate XHTML.</p>
<p>There was an interesting thread on the Java Posse group about this recently that you might find interesting:
<a href="http://groups.google.com/group/javaposse/browse_thread/thread/107ee3f67e0b7520" rel="nofollow noreferrer">why is javadoc stuck in 1997?</a></p>
| 33,500
|
<p>I am working with a legacy ASP Classic solution which is load balanced (via external hardware and has an IIS site the home directory of which is an UNC path. I've been told that the following issues with this setup currently exist: </p>
<ol>
<li>When using an UNC path as home directory, there is an "index" somewhere in IIS which "caches" up to a certain amount of files of certain types, and when the limit, which defaults to 50, has been reached, subsequent requests to pages not in the cache will return 404.</li>
<li>When using an UNC path as home directory, when starting the IIS site, the aforementioned "cache" will start filling, which will bog down the site IIS until the cache is filled, meaning that huge sites (15,000 .asp files) are unavailable for up to 30 minutes after the IIS site starts. </li>
<li>When using an UNC path as home directory, if more than a certain number of simultaneous requests are made to the site, Windows will reach the "Network BIOS command limit per server", and all requests above the limit will have to wait until IIS "closes the session" to the server. I am told the limit is 100 files and not configurable. </li>
</ol>
<p>Now, all this sounds a bit weird. If I set up a new Windows 2003 server with default settings, and use it to host an ASP Classic application with 15,000 .asp files, using a share on a server as the home directory for the IIS site, <strong>will I actually run into these problems? And if so, is there a way to counter them without changing the architecture?</strong></p>
<p>(To clarify, the only reason the "load balancing" is important is that load balancing is the reason the files are on a share on a server. If no load balancing was needed, the files could be on the local disk.) </p>
|
<p>Yes, it is possible, but yes, it can cause problems.</p>
<p>When ASP.NET compiles ASPX, ASCX, and other content pages into assemblies, it creates a lot of FileSystemWatchers in order to monitor the dependencies between them so that when files change, it can recompile. These eat up NetBIOS resources.</p>
<p>Additionally, every time you do a File.Exists or Directory.Exists call, or any other kind of IO to the site's serving path, that increases the demands on the NetBIOS limits as well.</p>
<p>It is possible to set the NetBIOS limits through the registry to above their defaults to a point.</p>
<p>For a small site, with relatively few directories and files, you could very successfully run off a UNC share because ASP.NET will continue to run after startup off of its compiled assemblies. However, the more directories and files you add, the more likely problems are to crop up.</p>
<p>We tried running a mammoth site (hundreds of directories and ASPX/ASCX files) and it would run fine for a few minutes until enough urls were accessed that the NetBIOS limits were reached, and then every subsequent page view resulted in an exception. We ended up forced to use a robocopy publishing solution.</p>
<p>In the end, you have to test to see if your site is small enough and your NetBIOS settings are high enough to run effectively. I would suggest using a spider on a test site so that you can be sure that everything that could be compiled or accessed is at least once.</p>
|
<p>For answer 3 you can change the Network BIOS command limit. Its a pretty easy registry edit fix: <a href="http://support.microsoft.com/kb/810886/en-us" rel="nofollow noreferrer">http://support.microsoft.com/kb/810886/en-us</a></p>
<p>I have run into that particular issue myself.</p>
| 15,037
|
<p>Using VB.NET, how do I toggle the state of Caps Lock? </p>
|
<p>From: <a href="http://www.vbforums.com/showthread.php?referrerid=61394&t=537891" rel="noreferrer">http://www.vbforums.com/showthread.php?referrerid=61394&t=537891</a></p>
<pre><code>Imports System.Runtime.InteropServices
Public Class Form2
Private Declare Sub keybd_event Lib "user32" ( _
ByVal bVk As Byte, _
ByVal bScan As Byte, _
ByVal dwFlags As Integer, _
ByVal dwExtraInfo As Integer _
)
Private Const VK_CAPITAL As Integer = &H14
Private Const KEYEVENTF_EXTENDEDKEY As Integer = &H1
Private Const KEYEVENTF_KEYUP As Integer = &H2
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles Button1.Click
' Toggle CapsLock
' Simulate the Key Press
keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0)
' Simulate the Key Release
keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)
End Sub
End Class
</code></pre>
|
<p>I use this</p>
<pre><code>Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)
Private Const KEYEVENTF_EXTENDEDKEY As Integer = &H1
Private Const KEYEVENTF_KEYUP As Integer = &H2
'put this where you want to turn caps lock on or off
keybd_event(VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0)
keybd_event(VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)
</code></pre>
| 8,339
|
<p>I'm venturing into web programming for the first time and would like a nice way to display a frequency indicator of some data, in the form of a <a href="http://en.wikipedia.org/wiki/Tag_cloud" rel="nofollow noreferrer">tag cloud</a>.</p>
<p>For example, pretend I have some simple data of three types of pets: Dog, Cat, Monkey.</p>
<p>There are <strong>5 Dogs</strong>, <strong>27 Cats</strong> and <strong>101 Monkeys</strong>. </p>
<p>Given this data, <strong>what's the best way to make a tag cloud</strong> to visually indicate that I have way too many monkeys, not as many cats, and that I definitely need obtain a few more dogs?</p>
<p><strong>Update</strong>: It would be great if the solution was actually discussed and answered on stackoverflow. Linking externally is good to help support the answer, but leaving the links as an answer is not necessarily what stackoverflow is about. Anyone can google to find what has been linked. The hope is that stackoverflow will be the place to find the answer. This is just a request to help make stackoverflow better. :)</p>
|
<p>I don't believe this is the answer you're looking for, but there is a Cloud Control for ASP.NET available at CodeProject:</p>
<p><a href="http://www.codeproject.com/KB/aspnet/cloud.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/aspnet/cloud.aspx</a></p>
<p>It's looks fairly easy to use.</p>
<p>--</p>
<p><strong>Edit:</strong> I should probably credit my source. The link above was found on the following web page:</p>
<p><a href="http://www.technacular.com/2007/04/22/how-to-create-a-tag-cloud/" rel="nofollow noreferrer">http://www.technacular.com/2007/04/22/how-to-create-a-tag-cloud/</a></p>
<p>This page contains some additional general information related to building a Tag Cloud. Best of luck!</p>
|
<p>I hope this would help. </p>
<p><a href="https://web.archive.org/web/20210616112719/https://aspnet.4guysfromrolla.com/articles/102506-1.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20210616112719/https://aspnet.4guysfromrolla.com/articles/102506-1.aspx</a></p>
| 21,635
|
<p>I had an idea for a client-side language other than JavaScript, and I'd like to look into developing a Firefox plugin that would treat includes of this new language in a page, like <script type="newscript" src="path/script.ns" />, just as if it were a natively supported language. The plugin would do all of the language parsing and ideally be able to perform every operation on the browser and the html and css within the web page just as JavaScript can.</p>
<p>I've done a bunch of Googling and have found some articles on writing basic Firefox plugins, but nothing as complicated as this.</p>
<p>Is this even possible?</p>
|
<p><a href="https://stackoverflow.com/questions/69982/writing-a-firefox-plugin-for-parsing-a-custom-client-side-language#70239">@Nathan de Vries</a>: no, actually, NPAPI plugins you suggested don't let one implement support for <code><script type=...></code>.</p>
<p>OP: this is not easy, but look for PyDOM and PyXPCOM - language bindings for Python. The former does exactly what you asked for - for Python, but I'm unsure about its current status. In any case, it's very likely that you need to create your own build of Firefox to support additional script types.</p>
|
<p>Do you really want to tie your pages to your own custom scripting language? Or are you just looking to write your client-side code in something that's not javascript? If the latter try <a href="http://milescript.org/" rel="nofollow noreferrer">MileScript</a>, <a href="http://haxe.org/" rel="nofollow noreferrer">Haxe</a>, or <a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">Google Web Toolkit</a></p>
| 9,541
|
<p>I am develop a medium system in ASP.net with MS SQL Server Database and I wonder <strong>what is the best way to create a model layer with LINQ or create own classes that dealing with database?</strong></p>
|
<p>The best way is subjective, but I think the easiest is to use <a href="http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx" rel="nofollow noreferrer">LINQ to SQL.</a></p>
|
<p>Using the LINQ designer is a great way to build your model in a UI avoiding the need to write any code. You can setup object hierarchy using the inheritance option and also have associated classes which you can access via the datacontext in code. All of the SQL is then handled for you and means you don't have to write anything, simply call SubmitChanges() on the datacontext. All of the generated code can be viewed, but there is a lot to take in.</p>
<p>I would suggest to try writing your own classes manually with the LINQ attributes etc so you get an idea of what it is doing behind the scenes. Then you will realise how the inheritance and association is implemented and actually makes the designer easier to understand too.</p>
| 37,487
|
<p>Attempting to insert an escape character into a table results in a warning. </p>
<p>For example:</p>
<pre><code>create table EscapeTest (text varchar(50));
insert into EscapeTest (text) values ('This is the first part \n And this is the second');
</code></pre>
<p>Produces the warning:</p>
<pre><code>WARNING: nonstandard use of escape in a string literal
</code></pre>
<p>(<em>Using PSQL 8.2</em>)</p>
<p>Anyone know how to get around this?</p>
|
<p>Partially. The text is inserted, but the warning is still generated.</p>
<p>I found a discussion that indicated the text needed to be preceded with 'E', as such:</p>
<pre><code>insert into EscapeTest (text) values (E'This is the first part \n And this is the second');
</code></pre>
<p>This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.</p>
<p>As such:</p>
<pre><code>insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
</code></pre>
|
<p>Really stupid question: Are you sure the string is being truncated, and not just broken at the linebreak you specify (and possibly not showing in your interface)? Ie, do you expect the field to show as</p>
<blockquote>
<p>This will be inserted \n This will not
be</p>
</blockquote>
<p>or</p>
<blockquote>
<p>This will be inserted</p>
<p>This will not be</p>
</blockquote>
<p>Also, what interface are you using? Is it possible that something along the way is eating your backslashes?</p>
| 2,336
|
<blockquote>
<p>Note that this question continues from <a href="https://stackoverflow.com/questions/15414/">Is it possible to coax Visual Studio 2008 into using italics for comments?</a></p>
</blockquote>
<p>If the long question title got you, here's the problem:</p>
<blockquote>
<p>How to convert the style property of the Consolas Italic font to Bold without actually modifying any of its actual glyphs? That is, we want the font to be still the same (i.e., Italic) we merely want the OS to believe that it's now a Bold font.</p>
</blockquote>
<p>Please just don't mention the name of a tool (Ex: fontforge), but describe the steps to achieve this or point to such a description.</p>
|
<p>Alright, I've successfully used FontForge to create a copy of Consolas (although this should work with any font) with the bold style actually being italics.</p>
<p>These are the steps that I followed:</p>
<ul>
<li>Install <a href="http://fontforge.sourceforge.net/" rel="noreferrer">FontForge</a>. It's a lot easier to do this on linux than on windows/cygwin. I used a Ubuntu VM ("sudo apt-get install fontforge").</li>
<li>Open Consola.ttf (the "normal" style font) in FontForge.</li>
<li>Select Element -> Font Info.</li>
<li>Change the Fontname, Family Name, and Name for Humans, all to the same thing. I used 'ConsolasVS'.</li>
<li>Click Ok. Click 'Yes' to let FontForge generate a new GUID for the font.</li>
<li>Select File -> Generate Fonts. Make sure you've got "TrueType" selected. Uncheck "Validate before saving". Click Save.</li>
<li>Now open Consolai.ttf (the italic style font) in FontForge.</li>
<li>Go back to Element -> Font Info.</li>
<li>Change the Font names as before, and where it currently says "Italic", change that to "Bold".</li>
<li>Go to the OS/2 tab, change the font weight to "700 Bold".</li>
<li>Go to the Mac tab, change the style set to Bold.</li>
<li>Click Ok. Allow a new GUID to be generated again.</li>
<li>File -> Generate Fonts, as before.</li>
</ul>
<p>Copy your two new ttf files into your \Windows\FONTS\ folder.</p>
<p>You can now have nice italic comments with Consolas in VS2008. Hooray!</p>
|
<p>I did the italics-as-bold trick on Consolas back in July 2007 and posted a <a href="http://damieng.com/blog/2007/07/11/italic-syntax-highlighting-in-visual-studio-2005" rel="nofollow noreferrer">screenshot of it on my blog</a>.</p>
<p>I used FontLab which does a great job but a custom tool to copy and set the header would be the best bet as you can't modify and redistribute Consolas and FontLab costs $699.</p>
<p>If you want to go down the FontLab route the open up the regular and italic versions and go into the File > Font Info... menu option and use the Names and Copyright section.</p>
<p>In there set them both fonts Family Name to a new name then flip the checkboxes on the italic version to indicate bold instead of italic and select Normal from the Weight list box and Italic in the Style Name list box.</p>
<p>Save and install :)</p>
| 3,814
|
<p>I have a local MINICPAN repository, but I want to remove a specific version of a module, and inject an older version.</p>
<p>This is the steps I've taken.</p>
<pre><code>- create the MINICPAN, not filtering any modules
- use mcpani --add for the module in question
- use mcpani --inject
</code></pre>
<p>At this point, I can see in the MINICPAN that it has both the version I want, and the newer version, if I issue install in cpan, then the newer version of the module is install. How can I get rid of the newer version from my minicpan?</p>
|
<p>Filter the modules that you are going to inject. The <a href="http://search.cpan.org/dist/CPAN-Mini" rel="nofollow noreferrer">CPAN::Mini</a> has the documentation for filtering, and I think I had some examples in the resources I pointed you toward earlier. :)</p>
<p>If you already have the minicpan, as you said in the comment to ysth, you can create <em>another</em> minicpan from that one. The "remote" CPAN in that case is the one that you have. I do that all the time: I have a canonical minicpan, but then for testing things, I filter from that to create new repositories just so I don't have to deal with the network.</p>
|
<p>Another strategy would be to use <a href="https://metacpan.org/pod/Pinto" rel="nofollow">Pinto</a>. Unlike a minicpan, a Pinto repository contains <em>only</em> the distributions you want (and their dependencies), so there is no need for filtering. This results in a much smaller and more manageable pile of files, so you can easily do things like check it into your SCM. Pinto also has some neat tools for handling upgrades without accidentally breaking your application.</p>
<p>Also, <a href="https://stratopan.com" rel="nofollow">Stratopan</a> hosts Pinto repositories in the cloud. You can manage the repository through your browser and install modules anywhere that has internet access. It doesn't yet support all the features Pinto has, but Stratopan really takes the hassle out of maintaining a local CPAN.</p>
<p><em>Disclaimer: I operate Stratopan.</em> </p>
| 33,047
|
<p>Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me. </p>
<ul>
<li><strong>include</strong>: mixes in specified module methods as <strong>instance methods</strong> in the target class</li>
<li><strong>extend</strong>: mixes in specified module methods as <strong>class methods</strong> in the target class</li>
</ul>
<p><em>So is the major difference just this or is a bigger dragon lurking?</em>
e.g.</p>
<pre><code>module ReusableModule
def module_method
puts "Module Method: Hi there!"
end
end
class ClassThatIncludes
include ReusableModule
end
class ClassThatExtends
extend ReusableModule
end
puts "Include"
ClassThatIncludes.new.module_method # "Module Method: Hi there!"
puts "Extend"
ClassThatExtends.module_method # "Module Method: Hi there!"
</code></pre>
|
<p>What you have said is correct. However, there is more to it than that.</p>
<p>If you have a class <code>Klazz</code> and module <code>Mod</code>, including <code>Mod</code> in <code>Klazz</code> gives instances of <code>Klazz</code> access to <code>Mod</code>'s methods. Or you can extend <code>Klazz</code> with <code>Mod</code> giving the <em>class</em> <code>Klazz</code> access to <code>Mod</code>'s methods. But you can also extend an arbitrary object with <code>o.extend Mod</code>. In this case the individual object gets <code>Mod</code>'s methods even though all other objects with the same class as <code>o</code> do not.</p>
|
<p>I came across a very useful <a href="https://dev.to/abbiecoghlan/ruby-modules-include-vs-extend-vs-prepend-4gmc" rel="nofollow noreferrer">article</a> that compares <code>include</code>, <code>extend</code> and <code>prepend</code> methods used <strong>inside a class</strong>:</p>
<p><code>include</code> adds module methods as instance methods to the class, whereas <code>extend</code> adds module methods as class methods. The module being included or extended must be defined accordingly</p>
| 18,914
|
<p>If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path?</p>
<p>I know of <pre>Path.Combine</pre> but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.</p>
<p>e.g:</p>
<pre>
string folder1 = "foo";
string folder2 = "bar";
CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")
</pre>
<p>Any ideas?
Does C# support unlimited args in methods?</p>
|
<blockquote>
<p>Does C# support unlimited args in methods?</p>
</blockquote>
<p>Yes, have a look at the params keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested):</p>
<pre><code>string CombinePaths(params string[] parts) {
string result = String.Empty;
foreach (string s in parts) {
result = Path.Combine(result, s);
}
return result;
}
</code></pre>
|
<p>Try this one:</p>
<pre><code>public static string CreateDirectoryName(string fileName, params string[] folders)
{
if(folders == null || folders.Length <= 0)
{
return fileName;
}
string directory = string.Empty;
foreach(string folder in folders)
{
directory = System.IO.Path.Combine(directory, folder);
}
directory = System.IO.Path.Combine(directory, fileName);
return directory;
}
</code></pre>
<p>The params makes it so that you can append an infinite amount of strings.</p>
<p>Path.Combine does is to make sure that the inputted strings does not begin with or ends with slashes and checks for any invalid characters.</p>
| 17,420
|
<p>In which cases would you use which? Is there much of a difference? Which I typically used by persistence engines to store booleans?</p>
|
<p>A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 bits, BIT(64). For a boolean values, BIT(1) is pretty common.</p>
|
<p>From my experience I'm telling you that BIT has problems on linux OS types(Ubuntu for ex).
I developped my db on windows and after I deployed everything on linux, I had problems with queries that inserted or selected from tables that had BIT DATA TYPE. </p>
<p>Bit is not safe for now.
I changed to tinyint(1) and worked perfectly. I mean that you only need a value to diferentiate if it's 1 or 0 and tinyint(1) it's ok for that</p>
| 36,986
|
<p>This might be a little hard to explain, but I will try.</p>
<p>I want to display a list of categories (stored in 1 table), and number of domains associated with each category (stored in another table). </p>
<p>The monkey wrench in this case is that each domain has a set of records associated with it (which are stored in a 3rd table). I only want to show the categories that have domains associated with them, and the count of domains should reflect only the domains that have records associated with them (from the 3rd table).</p>
<p>My current query</p>
<pre><code>SELECT r.rev_id, c.cat_id, c.cat_name, count(d.dom_id) As rev_id_count FROM reviews r
INNER JOIN domains d ON r.rev_domain_from=d.dom_id
INNER JOIN categories c ON d.dom_catid=c.cat_id
WHERE rev_status = 1
GROUP BY cat_name
ORDER BY cat_name
</code></pre>
<p>This selects the correct category names, but shows a false count (rev_id_count). If the category has 2 domains in it, and each domain has 2 records, it will show count of 4, when it should be 2.</p>
|
<pre><code>SELECT Categories.Name,count(DISTINCT categories.name) FROM Categories
JOIN Domains ON Categories.ID=Domains.CID
JOIN Records ON Records.DID=Domains.ID
GROUP BY Categories.Name</code></pre>
<p>Tested with following setup:</p>
<pre><code>
CREATE TABLE Categories (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1))
CREATE TABLE Domains (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1), CID int)
CREATE TABLE Records (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1), DID int)
INSERT INTO Records (DID) VALUES (1)
INSERT INTO Records (DID) VALUES (1)
INSERT INTO Records (DID) VALUES (2)
INSERT INTO Records (DID) VALUES (2)
INSERT INTO Records (DID) VALUES (3)
INSERT INTO Records (DID) VALUES (3)
INSERT INTO Domains (Name,CID) VALUES ('D1',1)
INSERT INTO Domains (Name,CID) VALUES ('D2',1)
INSERT INTO Domains (Name,CID) VALUES ('D5',1)
INSERT INTO Domains (Name,CID) VALUES ('D3',2)
INSERT INTO Domains (Name,CID) VALUES ('D4',2)
INSERT INTO Categories (Name) VALUES ('1')
INSERT INTO Categories (Name) VALUES ('2')
INSERT INTO Categories (Name) VALUES ('3')
</code></pre>
|
<p>Something like this?</p>
<pre><code>SELECT c.name, count(d.id)
FROM categories c
JOIN domains d ON c.id = d.cid
JOIN records r ON r.did = d.id
GROUP BY c.name;
</code></pre>
| 24,934
|
<p>I recently switched my hosting provider and due to the time zone that the server is now in, my code has stopped working. </p>
<p>The hosting server reports in Pacific time, However, my code needs to work with GMT as my site is for the UK market. So, all my displays and searches need to be in the format dd/MM/yyyy</p>
<p>How can I account for the difference? </p>
<p>For instance, when I do a DateTime.Parse("03/11/2008") it fail as I assume the 'Parse' is against the servers settings. I also get "String was not recognized as a valid DateTime." throughout my code. </p>
|
<p>In your web.config file add <code><globalization></code> element under <code><system.web></code> node:</p>
<pre><code><system.web>
<globalization culture="en-gb"/>
<!-- ... -->
</system.web>
</code></pre>
|
<p>I had this problem which the above answers didn't solve. So maybe this can help someone not to tear all their hair off..</p>
<p>I got NaN-NaN-Nan on the new server in my date-textbox. Found out that the new server had the internet explorer option "Display intranet sites in Compability Mode".
Workaround here was to put </p>
<pre><code><meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" / >
</code></pre>
<p>in the head of the aspx to force off compability mode.</p>
<p>This solved a lot of weird stuff that was going on.
Hope this helps someone! </p>
| 32,170
|
<p>Does anyone have a good way to build MSI (vdproj) projects using MsBuild or Nant? </p>
<p>I know <a href="http://forums.msdn.microsoft.com/en-US/msbuild/thread/6e213531-9d88-43ef-8262-fe0e4e7f479a/" rel="nofollow noreferrer">one answer</a> was to install Visual Studio on the build server and just use devenv.exe to build the project, but, I prefer not to install Visual Studio on our build servers.</p>
|
<p>Short of the method you mentioned above (devenv), there is no way to do this with the current version of MSBuild. </p>
<p>The method the Visual Studio team uses to run their MSI builds is with <a href="http://wix.sourceforge.net/" rel="noreferrer">Windows Installer XML</a>. You can learn more about using WiX to deploy setup packages <a href="http://msdn.microsoft.com/en-us/magazine/cc163456.aspx" rel="noreferrer">here</a>.</p>
<p>Please note WiX doesn't support vdproj files so it means you'll be recreating your installer projects.</p>
<p>Edit: Looks like I was beat to the chase when grabbing my references :)</p>
|
<p>We use <a href="http://wix.sourceforge.net/" rel="nofollow noreferrer">Wix</a> to automate MSI builds for IronPython and IronRuby.</p>
<p>EDIT: to clarify, this probably means starting over from scratch when building your installer. While Wix has a mechanism to create a configuration directly from a preexisting MSI file, I've never gotten a satisfactory result from using this tool</p>
| 4,444
|
<p>I have heard that this is what JavaRebel does but is there any other good way to deploy a new version of an EAR while allowing users to remain active on the previous version? We use JBoss for the application server...</p>
|
<p>It's not what JavaRebel does. JavaRebel (according to description) hot-replaces the classes in memory. It's not acceptable in the case of existing connections to the system, since the updated classes may break the client's logic.</p>
<p>Once a company I was working for had a similar problem, and it was solved this way:</p>
<ul>
<li>a smart router was used as a load-balancer</li>
<li>the new version was deployed to 50% of the nodes of the (new) cluster</li>
<li>new connections were delivered strictly to these updated nodes, old ones were balanced between old nodes</li>
<li>old nodes were took off-line (one-by-one, to keep number of clients per node within limits)</li>
<li>at the same time, new version was deployed to off-line "old" nodes and they were brought up as new nodes</li>
<li>due to EJB clustering, the sessions and beans were picked up by other old nodes</li>
<li>eventually (in a few hours), only one old node left, having a single instance of old version and all clients using old version were connected to it</li>
<li>when the last old client got disconnected, that node was too brought down</li>
</ul>
<p>Now, I'm not a networking guy, and cannot give you many details (like what was the router hardware and such). My understanding this can be set up pretty easy, except, if I remember right, we had to setup an additional Weblogic domain to deploy new versions of the application (otherwise it would be conflicting with the old one on JNDI names). </p>
<p>Hope that helps.</p>
<p>P.S. Ichorus provided a comment saying that the app is deployed on clients' servers. So the router trick may be not feasible. Now, I see only one viable solution right now ( it's 21:52 now, I may overlook things :) ) -- </p>
<ul>
<li>Develop new version with "versioned" JNDI names; e.g. if Customer bean was under ejb/Customer in version 1, in version 2 it would be under ejb/Customer2</li>
<li>Have a business facade in the application with a stable basic interface (Factory-style) which, when asked for Customer bean, tries to find the highest-versioned JNDI name (not on every call, of course, can cache for a hour or so). That facade could (and should) be deployed as a separate application -- and never or very rarely updated</li>
<li>Now every new client would get access to the latest application deployed, and the applications won't conflict.</li>
</ul>
<p>This approach takes a careful planning and testing, but should work IMHO.</p>
<p>I recently modified a few applications in a similar way to let them coexist in the same domain (before they used the same JNDI name for different data sources). </p>
|
<p>I think you might want to look into Spring using OSGI framework.
<a href="http://www.springframework.org/osgi" rel="nofollow noreferrer">http://www.springframework.org/osgi</a></p>
| 27,353
|
<p>I feel like I should know this, but I haven't been able to figure it out...</p>
<p>I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.</p>
|
<p>This seems to be the simplest way using module <code>inspect</code>:</p>
<pre><code>import inspect
def somefunc(a,b,c):
print "My name is: %s" % inspect.stack()[0][3]
</code></pre>
<p>You could generalise this with:</p>
<pre><code>def funcname():
return inspect.stack()[1][3]
def somefunc(a,b,c):
print "My name is: %s" % funcname()
</code></pre>
<p>Credit to <a href="http://stefaanlippens.net/python_inspect" rel="noreferrer">Stefaan Lippens</a> which was found via google.</p>
|
<p>I think the <a href="http://www.python.org/doc/2.5.2/lib/module-traceback.html" rel="nofollow noreferrer"><code>traceback</code></a> module might have what you're looking for. In particular, the <code>extract_stack</code> function looks like it will do the job.</p>
| 30,426
|
<p>Is there a 4 byte unsigned int data type in MS SQL Server?</p>
<p>Am I forced to use a bigint?</p>
|
<p>It doesn't seem so.</p>
<p>Here's an article describing how to create your own rules restricting an <code>int</code> to positive values. But that doesn't grant you positive values above <code>2^31-1</code>.</p>
<p><a href="http://www.julian-kuiters.id.au/article.php/sqlserver2005-unsigned-integer" rel="noreferrer">http://www.julian-kuiters.id.au/article.php/sqlserver2005-unsigned-integer</a></p>
|
<p>I used BINT(11) instead of INT(11), and it acts as UNSIGNED INT(11)</p>
| 39,403
|
<p>Our application commonly used an ActiveX control to download and install our client on IE (XP and prior), however as our user base has drifted towards more Vista boxes with "Protected Mode" on, we are required to investigate.</p>
<p>So going forward, is it worth the headache of trying to use the protected mode API? Is this going to result in a deluge of dialog boxes and admin rights to do the things our app needs to do (write to some local file places, access some other applications, etc)?</p>
<p>I'm half bent on just adding a non-browser based installer app that will do the dirty work of downloading and installing the client, if need be... this would only need to be installed once and in large corporate structures it could be pushed out by IT.</p>
<p>Are there some other ideas I'm missing?</p>
|
<p>This client, is it a desktop application and not some software that runs inside the browser? In that case, please just supply a regular download installer application. My personal experience with browser-hosted installers is that they are just confusing and the few I have seen seemed to be poorly coded in some way.</p>
<p>If you use an MSI based installer I'm sure lots of Windows domain administrators will love you too, as Microsoft has tools to deploy MSI based installations onto large sets of machines remotely.</p>
|
<p>Have you checked out Microsoft's <a href="http://msdn.microsoft.com/en-us/library/t71a733d(VS.80).aspx" rel="nofollow noreferrer">ClickOnce Deployment</a>?</p>
<p>If I remember correctly you can embed a manifests which would help with dealing with protected modes automatically, saving you those headaches with the APIs.</p>
<p>I believe ClickOnce is geared for the same thing your ActiveX installer was designed to do.</p>
<p>Since you say your IT dept could push this out, I assume you could use this kind of technology as well.</p>
<p>Even though you might not be writing applications on the .NET CLR, you can use Visual Studio to generate those manifest and installers for you.</p>
| 10,381
|
<p>An interface is a 100% abstract class, so we can use an interface for efficient programming. Is there any situation where an abstract class is better than an interface?</p>
|
<p>Abstract classes are used when you do intend to create a concrete class,
but want to make sure that there is some <strong>common state</strong> in all the subclasses
or a possible <strong>common implementation</strong> for some operations.</p>
<p>Interfaces cannot contain either.</p>
|
<p>In general, interfaces describe the public API that your code should use, whereas abstract base classes are best kept as an implementation detail, where common code or state can be kept, to reduce duplication in any implementing classes.</p>
<p>By using interfaces in your API, it becomes easier for people (including you) to write test code against your classes, since you can use test classes that, for example, don't depend on any external resources, or which exhibit explicit kinds of bad-but-difficult-to-simulate-in-real-life behaviour.</p>
<p>So java provides the List interface, and the AbstractList abstract base class to "minimize the effort needed to implement" the interface...</p>
| 41,800
|
<p>I'm inserting an img tag into my document with the new Element constructor like this (this works just fine):</p>
<pre><code>$('placeholder').insert(new Element("img", {id:'something', src:myImage}))
</code></pre>
<p>I would like to trigger a function when this image loads, but I can't figure out the correct syntax. I'm guess it's something like this (which doesn't work).</p>
<pre><code>$('placeholder').insert(new Element("img",
{id:'something', src:myImage, onload:function(){alert("MOO")}}))
</code></pre>
<p>I'm hoping to do this in the same line of code and not to have to attach an event observer separately.</p>
<p><strong>EDIT:</strong> The event needs to be registered when the element is <strong>created</strong>, not after. If the image loads before the event is attached, the event will never fire.</p>
|
<p>In this case, the best solution is to not use Prototype or at least not exclusively. This works:</p>
<pre><code>var img = new Element('img',{id:'logo',alt:'Hooray!'});
img.onload = function(){ alert(this.alt); };
img.src = 'logo.jpg';
</code></pre>
<p>The key is setting the onload directly instead of letting Prototype's wrapper do it for you, and set the src last (actually not sure about that, but I do it last to be safe).</p>
<p>One-liners are overrated. With proper use of local variables the above is just as good. If you must have a one-liner, create a wrapper function or hack the Prototype core to ensure proper assignment (submit a patch!).</p>
|
<p>You might have to move the function elsewhere and call it by name</p>
<pre><code>$('placeholder').insert(new Element("img",
{id:'something', src:myImage, onload:"javascript:moo()"}))
function moo() {
alert("MOO");
}
</code></pre>
<p>Of course, because <code>insert</code> returns the element, you could inline <code>Element.observe</code></p>
<pre><code>$('placeholder').insert(new Element("img",
{id:'something', src:myImage})).observe('load', function(){alert("MOO")});
</code></pre>
| 35,224
|
<p>I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks</p>
|
<p>Since Twisted is event driven, you don't need a timeout per se. You simply need to set a state variable (like datagramRecieved) when you receive a datagram and register a <a href="http://twistedmatrix.com/projects/core/documentation/howto/time.html" rel="nofollow noreferrer">looping call</a> that checks the state variable, stops the reactor if appropriate then clears state variable:</p>
<pre><code>from twisted.internet import task
from twisted.internet import reactor
datagramRecieved = False
timeout = 1.0 # One second
# UDP code here
def testTimeout():
global datagramRecieved
if not datagramRecieved:
reactor.stop()
datagramRecieved = False
l = task.LoopingCall(testTimeout)
l.start(timeout) # call every second
# l.stop() will stop the looping calls
reactor.run()
</code></pre>
|
<p>A better way to do this is with <code>twisted.protocols.policies.TimeoutMixin</code>. It's essentially doing a <code>callLater</code> but abstracted into a <code>Mixin</code>.</p>
| 27,338
|
<p>I have the following character string: </p>
<pre><code>"..1....10..20....30...40....50...80..."
</code></pre>
<p>and I need to extract all numbers from it into array. </p>
<p>What is the best way to do it in C? </p>
|
<p>Perhaps the easiest way is to use the <code>strtok()</code> function (or <code>strtok_r()</code> if reentrancy is a concern):</p>
<pre><code>char str[] = "..1...10...20";
char *p = strtok(str, ".");
while (p != NULL) {
printf("%d\n", atoi(p));
p = strtok(NULL, ".");
}
</code></pre>
<p>Once you have the results of calling <code>atoi()</code>, it should be a simple matter to save those integers into an array.</p>
|
<p>I prefer the use of strtok in a for loop. Makes it feel more natural, though the syntax looks a little weird.</p>
<pre><code>char str[] = "..1....10..20....30...40....50...80..."
for ( char* p = strtok( strtok, "." ); p != NULL; p = strtok( NULL, "." ) )
{
printf( "%d\n", atoi( p ) );
}
</code></pre>
| 23,560
|
<p>I have a C# program which uses a SQL Server database.I am already using it in a country that uses . as decimal separator.
Now I want to use it in another country that uses , as decimal separator.</p>
<p>in C# is there some application level setting that I can change or write some code so that I can use the same database and the same program ? or do I have to change my entire code to handle this new decimal separator?</p>
<p>I dont know how this works.Basically I think there would be problems in My Sql Queries.
example say one of my existing statements is
<br></p>
<pre><code>insert into tblproducts(productId,Price) values('A12',24.10)
</code></pre>
<p>now in new country it will become </p>
<pre><code>insert into tblproducts(productId,Price) values('A12',24,10)
</code></pre>
<p>this will raise an error</p>
<p>so do I have to change whole code to handle this situation ?</p>
<p>Thank you </p>
|
<p>If you built the query using string concatenation, use parameters instead.
So instead of writing:</p>
<pre><code> var query = "insert into tblproducts(productId,Price) values('" + article + "','"
+ price + ')';
</code></pre>
<p>use <a href="http://msdn.microsoft.com/library/yy6y35y8.aspx" rel="nofollow noreferrer">OleDbParameters</a>:</p>
<pre><code> var query = "insert into tblproducts(productId,Price) values(?,?)"
var cmd = new OleDbCommand(query, connection);
cmd.Parameters.Add("@article", OleDbType.VarChar).Value = article;
cmd.Parameters.Add("@price", OleDbType.Single).Value = price;
</code></pre>
<p>This will save you a lot of troubles, including localization issues.</p>
|
<p>you can do a couple of things to fix this.</p>
<p>first, if you are taking values in from the interface, then you are casting these values to a decimal. Decimal.parse is a culture dependant function and will use the current culture to parse values. Therefore if the CurrentCulture uses commas as decimal separators then your cast will work properly.
Then when you output the value from your variable, you can specify the decimal.ToString format to always output using a period as the separator.</p>
<p>Oh, forgot to add. You could also change your parsing to indicate Currency, which allows commas as well as $ signs. for example: decimal.parse(amount, NumberStyles.Currency)</p>
| 46,047
|
<p>I have to read invoice ascii files that are structured in a really convoluted way, for example:</p>
<pre><code>55651108 3090617.10.0806:46:32101639Example Company Construction Company Example Road. 9 9524 Example City
</code></pre>
<p>There's actually additional stuff in there, but I don't want to confuse you any further.</p>
<p>I know I'm doomed if the client can't offer a better structure. For instance 30906 is an iterative number that grows. 101639 is the CustomerId. The whitespaces between "Example Company" and "Construction Company" are of variable length The field "Example Company" could have whitespaces of variable length too however, for instance "Microsoft Corporation Redmond". Same with the other fields. So there's no clear way to extract data from the latter part.</p>
<p>But that's not the question. I got taken away. My question is as follows:</p>
<p>If the input was somewhat structured and well defined, how would you guard against future changes in its structure. How would you design and implement a reader. </p>
<p>I was thinking of using a simple EAV Model in my DB, and use text or xml templates that describe the input, the entity names, and their valuetypes. I would parse the invoice files according to the templates.</p>
|
<p>"If the input was somewhat structured and well defined, how would you guard against future changes in its structure. How would you design and implement a reader?"</p>
<p>You must define the layout in a way you can flexibly pick it apart.</p>
<p>Here's a python version</p>
<pre><code>class Field( object ):
def __init__( self, name, size ):
self.name= name
self.size = size
self.offset= None
class Record( object ):
def __init__( self, fieldList ):
self.fields= fieldList
self.fieldMap= {}
offset= 0
for f in self.fields:
f.offset= offset
offset += f.size
self.fieldMap[f.name]= f
def parse( self, aLine ):
self.buffer= aLine
def get( self, aField ):
fld= self.fieldMap[aField]
return self.buffer[ fld.offset:fld.offset+fld.size+1 ]
def __getattr__( self, aField ):
return self.get(aField)
</code></pre>
<p>Now you can define records</p>
<pre><code>myRecord= Record(
Field('aField',8),
Field('filler',1),
Field('another',5),
Field('somethingElse',8),
)
</code></pre>
<p>This gives you a fighting chance of picking apart some input in a reasonably flexible way.</p>
<pre><code>myRecord.parse(input)
myRecord.get('aField')
</code></pre>
<p>Once you can parse, adding conversions is a matter of subclassing Field to define the various types (dates, amounts, etc.)</p>
|
<p>I believe that a template describing the entity names and the value types is good one. Something like a "schema" for a text file.</p>
<p>What I would try to do is to separate the reader from the rest of the application as much as possible. So, the question really is, how to define an interface that will be able to accommodate for changes in the parameters list. This is may not be always possible, but still, if you are relying on an interface to read the data, you could change the implementation of the reader without affecting the rest of the system. </p>
| 48,524
|
<p>I want my client code to look somewhat like this:</p>
<pre><code> val config:Config = new MyConfig("c:/etc/myConfig.txt")
println(config.param1)
println(config.param2)
println(config.param3)
</code></pre>
<p>Which means that:</p>
<ul>
<li>The Config interface defines the config fields</li>
<li>MyConfig is a Config implementation -- all the wiring needed is the instantiation of the desired implementation</li>
<li>Data is loaded lazily -- it should happen on first field reference (config.param1 in this case)</li>
</ul>
<p>So, I want the client code to be friendly, with support for interchangeable implementations, with statically typed fields, hiding lazy loading. I also want it to be as simple as possible for making alternative implementations, so Config should somewhat guide you.</p>
<p>I am not satisfied with what I came up with so far:</p>
<pre><code>trait Config {
lazy val param1:String = resolveParam1
lazy val param2:String = resolveParam2
lazy val param3:Int = resolveParam3
protected def resolveParam1:String
protected def resolveParam2:String
protected def resolveParam3:Int
}
class MyConfig(fileName:String) extends Config {
lazy val data:Map[String, Any] = readConfig
// some dummy impl here, should read from a file
protected def readConfig:Map[String,Any] = Map[String, Any]("p1" -> "abc", "p2" -> "defgh", "p3" -> 43)
protected def resolveParam1:String = data.get("p1").get.asInstanceOf[String]
protected def resolveParam2:String = data.get("p2").get.asInstanceOf[String]
protected def resolveParam3:Int = data.get("p3").get.asInstanceOf[Int]
}
</code></pre>
<p>I'm sure there are better solutions, that's where you can help :)</p>
<p>One thing I especially don't like here is that MyConfig defines an intermediate container with some arbitrary keys, and since it is Map[String, <strong>Any</strong>], I need to cast the values.</p>
|
<p>There's nothing preventing you from just making the values abstract. You cannot enforce laziness in the super-trait, but that's ok since lazy-loading is really an implementation detail anyway:</p>
<pre><code>trait Config {
val param1: String
val param2: String
val param3: Int
}
class MyConfig extends Config {
lazy val param1 = readConfig().("p1")
...
def readConfig(): Map[String, String] = ...
}
</code></pre>
<p>On a stylistic note, <code>readConfig()</code> should be declared and called with parens (rather than without) as it is a side-effecting method. The no-parens syntax is designed to denote pure-functional methods.</p>
|
<p>If you just want to simplify it, the "param" fields could be methods...</p>
<pre><code>trait Config {
def param1:String
def param2:String
def param3:Int
}
class MyConfig(fileName:String) extends Config {
lazy val data:Map[String, Any] = readConfig
// some dummy impl here, should read from a file
protected def readConfig:Map[String,Any] =
Map[String, Any]("p1" -> "abc", "p2" -> "defgh", "p3" -> 43)
def param1:String = data.get("p1").get.asInstanceOf[String]
def param2:String = data.get("p2").get.asInstanceOf[String]
def param3:Int = data.get("p3").get.asInstanceOf[Int]
}
</code></pre>
<p>To get rid of the casting, you could have <code>MyConfig</code> wrap a non-lazy inner class that's lazy loaded by <code>MyConfig</code>.</p>
<pre><code>class MyConfig(fileName:String) extends Config {
private class NonLazyConfig(val p1:String, p2:String, p3:int) extends Config {
def param1 = p1
def param2 = p2
def param1 = p3
}
lazy val inner:Config = readConfig
// some dummy impl here, should read from a file
protected def readConfig:Config = {
return new NonLazyConfig("abc", "defgh", 43)
}
def param1:String = inner.param1
def param2:String = inner.param2
def param3:Int = inner.param3
}
</code></pre>
| 44,990
|
<p>There are a number of obfuscation programs out there for .Net and I've tried one, my exe seems much slower when obfuscated. Do all obfuscation programs have the same effect or have I chosen a bad one? I'm hoping some are better than others, if you know of a fast one let me know.</p>
|
<p>Obfuscation <em>shouldn't</em> change the runtime performance of your code. If it is then you've got a bad obfuscator that's doing much more than just obfuscating. All obfuscation should do is make your IL hard to read.</p>
|
<p>There are <a href="http://howtoselectguides.com/dotnet/obfuscators/1st#dp_methods" rel="nofollow noreferrer">different obfuscation methods</a> that tools can use. There are the simple rename methods that should not affect performance in any way. Other methods might change the flow of the code. That could have a negative impact on performance. You might want to check out other obfuscators and try out different settings.</p>
| 9,010
|
<p>Short version: What is the cleanest and most maintainable technique for consistant presentation and AJAX function across all browsers used by both web developers and web developers' end-users?</p>
<ul>
<li>IE 6, 7, 8</li>
<li>Firefox 2, 3</li>
<li>Safari</li>
<li>Google Chrome</li>
<li>Opera</li>
</ul>
<p>Long version: I wrote a <a href="http://con.appspot.com" rel="nofollow noreferrer">web app aimed at other web developers</a>. I want my app to support the major web browsers (plus Google Chrome) in both presentation and AJAX behavior.</p>
<p>I began on Firefox/Firebug, then added conditional comments for a consistent styling under IE 6 and 7. Next, to my amazement, I discovered that jQuery does not behave identically in IE; so I <a href="http://github.com/jhs/app-engine-console/commit/4fe7741ad1856208b565eeab4260a64933929c01" rel="nofollow noreferrer">changed my Javascript to be portable on FF and IE</a> using conditionals and less pure jQuery.</p>
<p>Today, I started testing on Webkit and Google Chrome and discovered that, not only are the styles inconsistant with both FF and IE, but Javascript is not executing at all, probably due to a syntax or parse error. I expected some CSS work, but now I have more Javascript debugging to do! At this point, I want to step back and think before writing piles of special cases for all situations.</p>
<p>I am <b>not looking for a silver bullet, just best practices</b> to keep things as understandable and maintainable as possible. I prefer if this works with no server-side intelligence; however if there is a advantage to, for example, check the user-agent and then return different files to different browsers, that is fine if the total comprehensibility and maintainability of the web app is lower. Thank you all very much!</p>
|
<p>I am in a similar situation, working on a web app that is targeted at IT professionals, and required to support the same set of browsers, minus Opera.</p>
<p>Some general things I've learned so far:</p>
<ul>
<li>Test often, in as many of your target browsers as you can. Make sure you have time for this in your development schedule.</li>
<li>Toolkits can get you part of the way to cross-browser support, but will eventually miss something on some browser. Plan some time for debugging and researching fixes for specific browsers.</li>
<li>If you need something that's not in a toolkit and can't find a free code snippet, invest some time to write utility functions that encapsulate the browser-dependent behavior.</li>
<li>Educate yourself about known browser bugs, so that you can steer your implementation around them.</li>
</ul>
<p>A few more-specific things I've learned:</p>
<ul>
<li>Use conditional code based on the user-agent only as a last resort, because different generations of the "same" browser may have different features. Instead, test for standards-compliant behavior first — e.g., <code>if(node.addEventListener)...</code>, then common non-standard functions — e.g., <code>if(window.attachEvent)...</code>, and then, if you must, look at the user-agent for a specific browser type & version number.</li>
<li>Knowing when the DOM is 'ready' for script access is different in just about every browser. A good toolkit will abstract this for you.</li>
<li>Event handlers are different in just about every browser. A good toolkit will abstract this for you.</li>
<li>Creating DOM elements, particularly form controls or elements with attributes, can be tricky with document.createElement and element.setAttribute. While not standard (and kinda yucky), using node.innerHTML with strings that contain bits of HTML seems to be more reliable across browser types. I have yet to find a toolkit that will let you use element.setAttribute to add a 'name' to a form element in IE.</li>
<li>CSS differences (and bugs) are just as important as JS differences.</li>
<li>The 'core' Javascript features (String, Date, RegExp, Array functions) seem to be pretty reliable and consistent across browsers, especially relative to the DOM/CSS/Window functions. There's some small joy in the fact that the language isn't entirely different on every platform. :-)</li>
</ul>
<p>I haven't really run into any Chrome-specific JS bugs, but it's always one of the first browsers I test.</p>
<p>HTH</p>
|
<p>If your very top priority is exactly consistent presentation on all the browsers listed with no disparities, you should probably be looking at AS3 and Flex.</p>
| 6,707
|
<p>I have an asp.net 2.0 page that contains 2 <code>UpdatePanels</code>.</p>
<p>The first panel contains a <code>TreeView</code> control, when I select a node in the three view control it triggers an update of the second <code>UpdatePanel</code> only. This much is behaving correctly.</p>
<p>There are two buttons on the page outside of an update panel (previous/next). These buttons trigger an update of both panels. The behaviour of the buttons is to select the adjacent node in the tree. The first time I click on one of these buttons I get the expected behaviour, and adjacent node is selected and the both panels are updated to reflect this change.</p>
<p>The problem happens when I click any of these buttons again. The selected node of the treeview seems to remember the previously selected node and the buttons act on this node. So the behaviour of the previous/next buttons is to do nothing or jump back two.</p>
<p><strong>Edit</strong> - Sample code that demonstrates my problem</p>
<p>The markup</p>
<pre><code> <asp:UpdatePanel ID="myTreeViewPanel" runat="server">
<ContentTemplate>
<asp:TreeView runat="server" ID="myTreeView" OnSelectedNodeChanged="myTreeView_SelectedNodeChanged">
<SelectedNodeStyle BackColor="#FF8000" />
</asp:TreeView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="myLabelPanel" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="myLabel" Text="myLabel"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myTreeView" EventName="SelectedNodeChanged" />
<asp:AsyncPostBackTrigger ControlID="myButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button runat="server" ID="myButton" Text="myButton" OnClick="myButton_Click" />
</code></pre>
<p>The code behind</p>
<pre><code> protected void Page_Load ( object sender, EventArgs e )
{
if ( !IsPostBack )
{
myTreeView.Nodes.Add( new TreeNode( "Test 1", "Test One" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 2", "Test two" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 3", "Test three" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 4", "Test four" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 5", "Test five" ) );
myTreeView.Nodes.Add( new TreeNode( "Test 6", "Test size" ) );
}
}
protected void myTreeView_SelectedNodeChanged ( object sender, EventArgs e )
{
UpdateLabel( );
}
protected void myButton_Click ( object sender, EventArgs e )
{
// here we just select the next node in the three
int index = myTreeView.Nodes.IndexOf( myTreeView.SelectedNode );
myTreeView.Nodes[ index + 1 ].Select( );
UpdateLabel( );
}
private void UpdateLabel ( )
{
myLabel.Text = myTreeView.SelectedNode.Value;
}
</code></pre>
<p>It is like the viewstate of the tree is not being saved?</p>
|
<p>From <a href="http://www.asp.net/ajax/documentation/live/overview/UpdatePanelOverview.aspx" rel="nofollow noreferrer">UpdatePanel Control Overview [asp.net]</a></p>
<blockquote>
<h3>Controls that Are Not Compatible with UpdatePanel Controls</h3>
<p>The following ASP.NET controls are not compatible with partial-page updates, and are therefore not supported inside an UpdatePanel control:</p>
<ul>
<li>TreeView and Menu controls.</li>
<li>...</li>
</ul>
</blockquote>
|
<p>I think you're right about the AJAX partial page postback that it doesn't update the hidden input __ViewState.</p>
<p>I have the same thing with my update panels when a user navigates back to the pages in my website application form. The normal inputs have updated the viewstate and so their values are repopulated but the state of the controls that were updated with AJAX isn't recorded and so they revert to the default state.</p>
| 25,124
|
<p>I know what <code>yield</code> does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem?</p>
<p>(Ideally some problem that cannot be solved some other way)</p>
|
<p>I realise this is an old question (pre Jon Skeet?) but I have been considering this question myself just lately. Unfortunately the current answers here (in my opinion) don't mention the most obvious advantage of the yield statement.</p>
<p>The biggest benefit of the yield statement is that it allows you to iterate over very large lists with much more efficient memory usage then using say a standard list.</p>
<p>For example, let's say you have a database query that returns 1 million rows. You could retrieve all rows using a DataReader and store them in a List, therefore requiring list_size * row_size bytes of memory.</p>
<p>Or you could use the yield statement to create an Iterator and only ever store one row in memory at a time. In effect this gives you the ability to provide a "streaming" capability over large sets of data. </p>
<p>Moreover, in the code that uses the Iterator, you use a simple foreach loop and can decide to break out from the loop as required. If you do break early, you have not forced the retrieval of the entire set of data when you only needed the first 5 rows (for example).</p>
<p>Regarding:</p>
<pre><code>Ideally some problem that cannot be solved some other way
</code></pre>
<p>The yield statement does not give you anything you could not do using your own custom iterator implementation, but it saves you needing to write the often complex code needed. There are very few problems (if any) that can't solved more than one way.</p>
<p>Here are a couple of more recent questions and answers that provide more detail:</p>
<p><a href="https://stackoverflow.com/questions/384392/yield-keyword-value-added">Yield keyword value added?</a></p>
<p><a href="https://stackoverflow.com/questions/317619/is-yield-useful-outside-of-linq">Is yield useful outside of LINQ?</a></p>
|
<p>Using yield can prevent downcasting to a concrete type. This is handy to ensure that the consumer of the collection doesn't manipulate it.</p>
| 3,783
|
<p>What is the best way to limit the amount of text that a user can enter into a 'textarea' field on a web page? The application in question is ASP .NET, but a platform agnostic answer is preferred.</p>
<p>I understand that some amount of javascript is likely needed to get this done as I do not wish to actually perform the 'post' with that amount of data if possible as ASP .NET does have an upper limit to the size of the request that it will service (though I don't know what that is exactly).</p>
<p>So maybe the real question is, what's the best way to do this in javascript that will meet the following criteria:</p>
<p>-Must work equally well for both users simply typing data and copy/paste'ing data in from another source.</p>
<p>-Must be as '508 compliance' friendly as possible.</p>
|
<p>use a RegularExpressionValidator Control in ASP.Net to validate number of character along with with usual validation</p>
|
<p>jQuery also provides some <a href="http://www.ajaxray.com/blog/2007/11/09/interactive-character-limit-for-textarea-using-jquery/" rel="nofollow noreferrer">options</a> here. Options, options, and options.</p>
| 49,544
|
<p>I want to log onto Stack Overflow using OpenID, but I thought I'd set up my own OpenID provider, just because it's harder :) How do you do this in Ubuntu?</p>
<p>Edit: Replacing 'server' with the correct term OpenID provider (Identity provider would also be correct according to <a href="http://en.wikipedia.org/wiki/Openid#Using_OpenID" rel="noreferrer">wikipedia</a>).</p>
|
<p>I personnally used <a href="https://siege.org/phpmyid.html" rel="nofollow noreferrer">phpMyID</a> just for StackOverflow. It's a simple two-files PHP script to put somewhere on a subdomain. Of course, it's not as easy as installing a .deb, but since OpenID relies completely on HTTP, I'm not sure it's advisable to install a self-contained server...</p>
|
<p>I totally understand where you're coming from with this question. I already had a OpenID at <a href="http://www.myopenid.com" rel="nofollow noreferrer">www.myopenid.com</a> but it feels a bit weird relying on a 3rd party for such an important login (a.k.a my permanent "home" on the internet).</p>
<p>Luckily, It is easy to move to using your own server as a openID server - in fact, it can be done with just two files with phpMyID.</p>
<ul>
<li>Download "phpMyID-0.9.zip" from <a href="http://siege.org/projects/phpMyID/" rel="nofollow noreferrer">http://siege.org/projects/phpMyID/</a></li>
<li>Move it to your server and unzip it to view the README file which explains everything.</li>
<li>The zip has two files: <em>MyID.config.php, MyID.php</em>. I created a directory called <code><mydocumentroot>/OpenID</code> and renamed <em>MyID.config.php</em> to <em>index.php</em>. This means my OpenID URL will be very cool: <code>http://<mywebsite>/OpenID</code></li>
<li>Decide on a username and password and then create a hash of them using: <code>echo -n '<myUserNam>:phpMyID:<myPassword>' | openssl md5</code></li>
<li>Open <em>index.php</em> in a text editor and add the username and password hash in the placeholder. Save it.</li>
<li>Test by browsing to <code>http://<mywebsite>/OpenID/</code></li>
<li>Test ID is working using: <a href="http://www.openidenabled.com/resources/openid-test/checkup/" rel="nofollow noreferrer">http://www.openidenabled.com/resources/openid-test/checkup/</a></li>
</ul>
<p>Rerefence info: <a href="http://www.wynia.org/wordpress/2007/01/15/setting-up-an-openid-with-php/" rel="nofollow noreferrer">http://www.wynia.org/wordpress/2007/01/15/setting-up-an-openid-with-php/</a> , <a href="http://siege.org/projects/phpMyID/" rel="nofollow noreferrer">http://siege.org/projects/phpMyID/</a> , <a href="https://blog.stackoverflow.com/2009/01/using-your-own-url-as-your-openid/">https://blog.stackoverflow.com/2009/01/using-your-own-url-as-your-openid/</a></p>
| 4,820
|
<p>I am creating a Windows service. When an exception occurrs, I handle it appropriately and create a log. I am using the <a href="http://en.wikipedia.org/wiki/Decorator_pattern" rel="nofollow noreferrer">decorator pattern</a>, as there are many different ways people will be looking at these logs. I have an email logger, a file logger, and a windows event logger, all which inherit from LoggingDecorator, which implements ILogger. So, no logger knows about any other logger.</p>
<p>My question is: How should I handle logging exceptions? </p>
<p>If writing to a file fails, or sending an email fails, what should I do? I want to log the initial log content with the other loggers, but what do I do with the logging exception? Doesn't it also depend on the order of the loggers in the constructor?</p>
<p>Right now, I'm just wrapping try/catch blocks with empty catch(Exception) statements, which just feels dirty and makes FxCop yell at me. However, is this one of those <a href="https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception">"it depends"</a> moments?</p>
<pre><code>[Flags]
public enum LoggingCategories
{
None = 0,
ServiceEvents = 1,
ProcessingInformation = 2,
ProcessingErrors = 4,
UnexpectedErrors = 8
}
public interface ILogger
{
void LogMessage(LoggingCategories category, string message);
}
public abstract class LoggerDecorator : ILogger
{
private ILogger _decoratedLogger;
private LoggingCategories _categories;
protected LoggerDecorator(ILogger logger, LoggingCategories categories)
{
this._decoratedLogger = logger;
this._categories = categories;
}
protected bool ShouldLogCategory(LoggingCategories category)
{
return ((this._categories & category) == category);
}
public virtual void LogMessage(LoggingCategories category, string message)
{
_decoratedLogger.LogMessage(category, message);
}
}
public class ControlLogger : ILogger
{
public ControlLogger()
{
}
public void LogMessage(LoggingCategories category, string message)
{
Console.WriteLine(LoggingHelper.ConstructLog(category, message));
}
}
</code></pre>
<p>(questionable code in WindowsEventLogger)</p>
<pre><code>try
{
this._eventLog.WriteEntry(log, type);
}
catch (Exception)
{
//Even if this logging fails, we do not want to halt any further logging/processing.
}
</code></pre>
<p>(code in service constructor)</p>
<pre><code>ILogger controlLogger = new ControlLogger();
ILogger windowsEventLogger = new WindowsEventLogger(controlLogger, windowsEventLogCategories, windowsEventLogSource);
ILogger emailLogger = new EmailLogger(windowsEventLogger, emailCategories, emailSubject, emailAddresses);
ILogger fileLogger = new FileLogger(emailLogger, fileCategories, logDirectory, logFileNamePrefix, logFileExtension);
this._logger = fileLogger;
</code></pre>
|
<p>Why don't put it in the actual Windows Event log if logger fails?</p>
|
<p>Create separate ping service on a well behaving machine which you trust to be very reliable. If your primary service fails then ping also fails and control service then should send you e-mail with warning.</p>
| 44,975
|
<p>I want to store a very large amount of vector data on a server and only poll the parts I need at a given point...</p>
<p>This shouldn't be a problem.</p>
<p>Is there any way to take a vector file like an svg file and import it into a database? I could always write an svg parser to import it into my database, but is there any standard way of doing this or storing vector data in a database ?</p>
|
<p>I don't think you can call it a standard, but here is an interesting link to an academic paper:</p>
<p><strong><a href="http://www.svgopen.org/2004/papers/ADesignandImplementationofSpatialDatabasebasedonxmlsvg/" rel="nofollow noreferrer">A Design and Implementation of Spatial Database Based on XML-SVG</a></strong></p>
<p>Abstract:</p>
<p><em>SVG, which stands for Scalable Vector Graphics, is an open standard in text that makes it possible to represent graphic information in compact, portable form and mostly faces on publishing the spatial vector graphics in network environment. In practice, it's impossible to avoid a great capacity of spatial data processing, which had made SVG document is too big to be implemented during publishing on the Internet.<br /><br />It is slowed down the executing speed of the system on client side and is weaken its advantages and superiority. Such SVG database has been proposed as the solution for managing all the graphics and its attributes in a Web server. SVG document is mapped into SVG database that works as a buffer in the server. The issuance efficiency has been improved to a great extent.</em></p>
|
<p>I could always put a giant svg document into a database, but I need to be able to look up vertices at lightning fast speed and I already have all the information in an svg document. I just need a rationalized way of implementing the information in a database.</p>
| 37,193
|
<p>I have really strange problem. Thing is that my print (first layer) started ok, not good nor perfect but ok and everything was going well but then all of a sudden, near the end of a print, quality drops drastically. I'm not really sure but I think this happened because of under extrusion. I'm not so good with English so here are pictures of finished print and some more details.</p>
<p><img src="https://imgur.com/avASUsS.jpg" alt="enter image description here"></p>
<p><img src="https://i.imgur.com/wRd9e5Y.jpg" alt="enter image description here"></p>
<p>I'm using custom build Delta printer with RepRap and Repetier firmware, CURA for slicing and Repetier-host for printing.</p>
<p>Slicing parameters in CURA are:<br>
- ABS 250 °C hotend and 70 °C heatbed<br>
- Layer height 0.2 mm (initial layer 0.18)<br>
- Printing speed 50 mm/s (30 mm/s outer walls)<br>
- Infill 40 %<br>
- Extrusion multiplayer 0.96 (96 %) </p>
<p>Do anyone have any ideas? What this can be? How can I fix this?</p>
|
<blockquote>
<p>Do anyone have any ideas? What this can be? How can I fix this?</p>
</blockquote>
<p>At least judging from the pictures, that <em>does</em> seem like under-extrusion. Some ideas for further investigating the issue.</p>
<p><strong>The problem may be due to the gcode being wrong</strong>. In this case, your printer is merely executing correctly... the wrong commands. To check if this is the case:</p>
<ul>
<li>The easiest, but inconclusive way, would be to re-slice a model that fails <em>consistently</em>, with a different slicer. If the second print came out good, than you would know that the problem is with the slicer. This method is <em>inconclusive</em> because you wouldn't not if the gcode is bad or if it simply happens that your printer cannot print well that specific sequence of commands (which may still be emitted by the other slicer under different conditions).</li>
<li>The more conclusive analysis would be to look at the gcode of a failed print where the fail happens between two geometrical identical layers. This seem to be the case for the print in the picture, btw. You should then compare the gcode of the layer that printed good with that of the layer that printed poorly. If the gcode differs... then you positively know the slicer doesn't work as it should.</li>
</ul>
<p><strong>The problem may be due to a mechanical fault with the printer</strong>. Here the only idea I have to offer is overheating of the steppers and/or their controllers. This may in turn make the extruder servo skip some steps and therefore extrude less filament. If you perform the conclusive test above, you will know if this is the case.</p>
<p><strong>The problem may be due to a firmware bug</strong>. This is difficult to investigate, my only suggestion would be: upgrade to the latest and greatest, if you haven't done it already.</p>
<p><strong>The problem may be filament-related</strong>. This could be a number of things, but since the problem seems to happen at towards the end of the print, and your are printing at relatively high temp, an idea could be that too much heat reaches the cold end of the extruder, interfering with its extrusion. The easiest test here would simply be to re-print a failed print with a different filament. In your case I would suggest some PLA, just to decrease the temperature and change the chemical composition too.</p>
<p>These are more or less all shots in the dark, but - together with asking here - it would be what I would do to debug, had I the same problem. Keep up posted! :)</p>
|
<p>You can try to reduce your retractions (try setting it to half what it is now and try again)</p>
<p>If your retraction is too big you can pull hot plastic into the cold area of the hotend and create a partial clog - this happened to me yesterday when I tried to intentionally print with way too much retraction to make demonstration photos for the retraction test model I uploaded to thingiverse.</p>
<p><em>note/disclaimer: that model I talked about above is <a href="https://www.thingiverse.com/thing:2753088" rel="nofollow noreferrer">here</a>, I'm the author of that model</em></p>
| 786
|
<p>I have integrated SRM 5.0 into Portal. Most of the iviews are IAC i.e., all are ITS based services.</p>
<p>The issue is that the Portal Theme does not get reflected on these services after integration.</p>
<p>When a BSP or Webdynpro is integrated then the application reflects the Portal Theme when executed from Portal but the ITS services are not getting this.</p>
<p>I tried using SE80 and editing EBPApplication.css. In BBPGLOBAL i changed all color attributes to custom colour but no effect.</p>
<p>Whch property should i change to remove the blue colour.</p>
|
<p>I think this would depend on how your product was sold to the customer.</p>
<p>If you only sell it in packages...</p>
<pre><code>PACKAGE 1 -> 3 reports, date entry, some other stuff.
PACKAGE 2 -> 6 reports, more stuff
PACKAGE 3 -> 12 reports, almost all the stuff
UBER PACKAGE -> everything
</code></pre>
<p>I would think it would be easier to setup a table of those packages and link to that.</p>
<p>If you sell each module by itself with variations...</p>
<pre><code>Customer wants 4 reports a week with an additional report every other tuesday if it's a full moon.
</code></pre>
<p>Then I would -- </p>
<pre><code>Create a table with all the product features.
Create a link table for customers and the features they want.
In that link table add an additional field for modification if needed.
</code></pre>
<p>CUSTOMERS</p>
<pre><code>customer_id (pk)
</code></pre>
<p>MODULES</p>
<pre><code>module_id (pk)
module_name (reports!)
</code></pre>
<p>CUSTOMER_MODULES</p>
<pre><code>module_id (pk) (fk -> modules)
customer_id (pk) (fk -> customers)
customization (configuration file or somesuch?)
</code></pre>
<p>This makes the most sense to me.</p>
|
<p>The key value pair table, but with everything is stored as a string and with another column (if necessary) saying which type should the value be casted to.</p>
<pre><code>CREATE TABLE configKVP(clientId int, key varchar, value varchar, type varchar)
</code></pre>
<p>If the value cannot be casted to the type, then you know it's a misconfiguration and there's no ambiguity.</p>
| 17,873
|
<p>How do I make <code>diff</code> ignore temporary files like <code>foo.c~</code>? Is there a configuration file that will make ignoring temporaries the default?</p>
<p>More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it...</p>
<p>EDIT: OK, the short answer is</p>
<pre><code>diff -ruN -x *~ ...
</code></pre>
<p>Is there a better answer? E.g., can this go in a configuration file?</p>
|
<p>This doesn't strictly answer your question, but you can avoid the problem by configuring Emacs to use a specific directory to keep the backup files in. There are different implementations for Emacs or XEmacs.</p>
<p>In GNU Emacs</p>
<pre>
(defvar user-temporary-file-directory
(concat temporary-file-directory user-login-name "/"))
(make-directory user-temporary-file-directory t)
(setq backup-by-copying t)
(setq backup-directory-alist
`(("." . ,user-temporary-file-directory)
(,tramp-file-name-regexp nil)))
(setq auto-save-list-file-prefix
(concat user-temporary-file-directory ".auto-saves-"))
(setq auto-save-file-name-transforms
`((".*" ,user-temporary-file-directory t)))
</pre>
<p>In XEmacs</p>
<pre>
(require 'auto-save)
(require 'backup-dir)
(defvar user-temporary-file-directory
(concat (temp-directory) "/" (user-login-name)))
(make-directory user-temporary-file-directory t)
(setq backup-by-copying t)
(setq auto-save-directory user-temporary-file-directory)
(setq auto-save-list-file-prefix
(concat user-temporary-file-directory ".auto-saves-"))
(setq bkup-backup-directory-info
`((t ,user-temporary-file-directory full-path)))
</pre>
<p>You can also remove them all with a simple find command</p>
<pre>
find . -name “*~” -delete
</pre>
<p>Note that the asterisk and tilde are in double quotes to stop the shell expanding them.</p>
<p>By the way, these aren't strictly <em>temporary</em> files. They are a backup of the previous version of the file, so you can manually "undo" your last edit at any time in the future. </p>
|
<p>You can create a small sunction/script to it, like:</p>
<pre><code>#!/bin/bash
olddir="/tmp/old"
newdir="/tmp/new"
pushd $newdir
for files in $(find . -name \*.c)
do
diff $olddir/$file $newdir/$file
done
popd
</code></pre>
<p>This is only one way to script this. The simple way. But I think you got the idea.</p>
<p>Other suggestion is configuring in emacs a backup dir, so your backup files go always to the same place, outside your work dir!</p>
| 5,304
|
<p>The title pretty much says it all. :-) I have lots of virtual hosts and I want to put a single rewriting block at the top of the httpd.conf file that rewrites URLs no matter which virtual host the request might be directed to. How the heck do I do this?</p>
<p>I found <a href="http://www.webmasterworld.com/forum92/1359.htm" rel="noreferrer">this</a> but my question is the same: how can I do this without resorting to .htaccess files and performing some other action for each virtual host?</p>
<p>OMGTIA!</p>
|
<p>Specify <code>RewriteOptions InheritDown</code> in the parent scope (such as httpd.conf) to get your rules applied in child Virtual Hosts without modifing them.</p>
<p>This will only work on Virtual Hosts where the <code>RewriteEngine</code> directive is set to <code>on</code>:</p>
<blockquote>
<p>Note that rewrite configurations are not inherited by virtual hosts. This means that you need to have a RewriteEngine on directive for each virtual host in which you wish to use rewrite rules.</p>
</blockquote>
<p>(<a href="https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriteengine" rel="noreferrer">source</a>)</p>
<p>Apache supports this since 2.4.8 (not available at the time of the original question).</p>
<p>From documentation for <code>RewriteOptions</code>:</p>
<blockquote>
<p><strong>InheritDown</strong></p>
<p>If this option is enabled, all child configurations will inherit the configuration of the current configuration. It is equivalent to specifying RewriteOptions Inherit in all child configurations. See the Inherit option for more details on how the parent-child relationships are handled.
Available in Apache HTTP Server 2.4.8 and later.</p>
<p><strong>InheritDownBefore</strong></p>
<p>Like InheritDown above, but the rules from the current scope are applied before rules specified in any child's scope.
Available in Apache HTTP Server 2.4.8 and later.</p>
<p><strong>IgnoreInherit</strong></p>
<p>This option forces the current and child configurations to ignore all rules that would be inherited from a parent specifying InheritDown or InheritDownBefore.
Available in Apache HTTP Server 2.4.8 and later.</p>
<p>(<a href="http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriteoptions" rel="noreferrer">http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriteoptions</a>)</p>
</blockquote>
|
<p>I've always used a "catch-all" VHost for directives I wanted across the board, like......</p>
<pre><code>Listen 80
NameVirtualHost *:80
<VirtualHost *:80>
ErrorLog "/var/log/apache2/error_log"
</VirtualHost>
<VirtualHost *:80>
ServerName alloftherestoftheVHosts.com
DocumentRoot "/ServiceData/.........
............
</code></pre>
<p>And it's always <em>seemed</em> to work... error logs were getting combined properly, etc...... but it IS possible that this was the result of an earlier / conflicting / like-minded directive.</p>
<p>Personal note.. <em>Whoever dreamed up the Apache configuration schema and syntax was a dingbat, or a group of dingbats, who spent too much time in their cave.... The whole thing should be exorcised and XMLized, or something!</em> Although they are both wildly different... the Hello-Kitty setup process of <a href="http://www.cherokee-project.com/" rel="nofollow">Cherokee</a>.. to the viciously succinct <a href="http://nginx.net/" rel="nofollow">NGinx</a> config.... are both so much more logical.. </p>
| 44,821
|
<p>Is there a better, more jQuery-ish way of handling this image substitution?</p>
<pre><code>var image = $(obj).children("img");
if ($(image).attr("src") == "Images/TreeCollapse.gif")
$(image).attr("src", "Images/TreeExpand.gif");
else
$(image).attr("src", "Images/TreeCollapse.gif");
</code></pre>
|
<p>Why set a variable when it isn't needed?</p>
<pre><code>$(obj).children("img").toggle(
function(){ $(this).attr("src", "Images/TreeExpand.gif"); },
function(){ $(this).attr("src", "Images/TreeCollapse.gif"); }
);
</code></pre>
|
<p>Not really.</p>
<p>I know... extremely helpful answer. What you are doing is pretty succinct and I'm not so sure there would be anything to make it more "jQueryish" as you ask. </p>
<p>now depending on how you are iterating through this if you are doing it to multiple image instances, that is where there might be some jQuery optimizations.</p>
| 44,300
|
<p>I'm looking to move some of my lighter weight metaprogramming from Nemerle to Boo and I'm trying to figure out how to define custom operators. For example, I can do the following in Nemerle:</p>
<pre><code>macro @<-(func, v) {
<[ $func($v) ]>
}
</code></pre>
<p>Then these two are equivalent:</p>
<pre><code>foo <- 5;
foo(5);
</code></pre>
<p>I can't find a way of doing this in Boo -- any ideas?</p>
|
<p>While Boo supports operator overloading by defining the appropriate static operator function (<code>op_addition</code>), and also supports syntactic macros, it does not support creating custom operators at this time.</p>
|
<p>I'm not sure if this is exactly what you need but you can create syntactic macros in Boo. There's some information on the CodeHaus site, <a href="http://boo.codehaus.org/Syntactic+Macros" rel="nofollow noreferrer">http://boo.codehaus.org/Syntactic+Macros</a>, but the syntax has changed in one of the recent releases. I don't know of any tutorials on the new syntax but the source release for Boo 0.8.2 has some examples (some of the language structures are implemented as macros). If you don't want to download the full source a view of the SVN repository is available, <a href="https://svn.codehaus.org/boo/boo/trunk/src/Boo.Lang.Extensions/Macros/" rel="nofollow noreferrer">https://svn.codehaus.org/boo/boo/trunk/src/Boo.Lang.Extensions/Macros/</a>. The assert macro would be a good place to start.</p>
<p>HTH</p>
<p>Stoo</p>
| 23,557
|
<p>Is it possible to use a ".net configuration" file for a .NET console application? </p>
<p>I'm looking for an equivalent to web.config, but specifically for console applications...</p>
<p>I can certainly roll my own, but If I can use .NET's built in configuration reader then I would like to do that...I really just need to store a connection string... </p>
<p>Thanks</p>
|
<p>Yes - use app.config.</p>
<p>Exactly the same syntax, options, etc. as web.config, but for console and WinForms applications.</p>
<p>To add one to your project, right-click the project in Solution Explorer, Add..., New Item... and pick "Application Configuration File" from the Templates box.</p>
|
<p>Yes, it's possible. You just need to make an app.config file.</p>
| 20,255
|
<p>I need to take any given valid XML schema (XSD) and denormalize it to a simple form containing no refs, no includes, etc. All simple type definitions should be inline, such that when looking at any given element, all declarations are visible without performing another lookup.</p>
<p>I've found some tools that have this built-in, but I need to do it "on the fly." Platform of choice is Java, but I'd be willing to port the code from another language if necessary. I just really don't want to reinvent the wheel here. Searching for OSS libraries from Apache/etc have yielded nothing. The closest I've found is XSOM which supports traversing a schema as an object model, but you still have to handle every possible form that a schema could take to represent a given structure.</p>
<p>The output doesn't have to be actual XML, as it will actually be used in a object model in its final form.</p>
|
<p>You might find XSD4J helpful:</p>
<p><a href="http://dynvocation.selfip.net/xsd4j/" rel="nofollow noreferrer">http://dynvocation.selfip.net/xsd4j/</a></p>
|
<p>Another useful API for XML Schema is <a href="https://xsom.java.net/" rel="nofollow">XSOM</a>.</p>
<p>XSOM is used by <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html" rel="nofollow">XJC</a>, JAXB schema compiler under the hub so is probably guaranteed to be kept alive.</p>
| 14,198
|
<p>One of my Websites is on a Shared Hosting Provider, running either .net 2.0 or .net 3.0, but not 3.5 SP1.</p>
<p>I wonder if it would be possible to still use 3.5 SP1 by simply deploying all the 3.5 assemblies into the /bin Folder, since technically it's all still the 2.0 CLR.</p>
<p>I know that if my Host ever updates I have to remove them or else weird stuff can happen, and that I am driving into Unsupported-Territory at full speed, but is there any really big road sign that says "DON'T DO IT!" or even "That is not possible because of X"?</p>
<p>Primary reason is because I want to use ASP.net MVC and possibly ADO.net Entity Framework, but I do not want to make a contract with yet another Hosting provider.</p>
<p>Thanks!</p>
|
<p>I'm pretty sure you can't do this, but googling on the following blogs may get you the definitive answer:</p>
<p><a href="http://weblogs.asp.net/Scottgu/" rel="nofollow noreferrer">ScottGu</a>
<a href="http://www.hanselman.com/blog/" rel="nofollow noreferrer">ScottHa</a>
<a href="http://blogs.msdn.com/brada/" rel="nofollow noreferrer">BradA</a></p>
<p>The problems would be, I think:</p>
<p>You want to load system.dll. Where does it look? does the GAC take precidence? (I think it does), therefore you get 2.0. So you have system.dll v2.0, and you try to use a DLL (eg system.web.mvc) which is bound to system.dll v3.5, but is only in you /bin.... it should explode loudly, not having the same contracts and the like.</p>
<p>Personally, I wouldn't try it, especially on production. But if you can take the site down for a while, give it a go. Worst case, you have to delete the files and re-upload the old site.</p>
<p>YMMV :)</p>
|
<p>I've successfully run some EntityFramework websites on hosts that only had .net 3.5 installed. I copied the System.Data.Entity.dll and the System.Web.Entity from Program Files%/Reference Assemblies. I also had to modify my web.config and remove the references to the System.Data.Entity and System.Web.Entity.</p>
<p>Update: this technique will not work for DynamicData or the EntityDataSource web control. I belive it has to do with the System.Web.WebExtensions.dll which already exists in the GAC from 3.5</p>
| 37,582
|
<p>Why is <code>volatile</code> needed in C? What is it used for? What will it do?</p>
|
<p><code>volatile</code> tells the compiler not to optimize anything that has to do with the <code>volatile</code> variable.</p>
<p>There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code:</p>
<ul>
<li>When you interface with hardware that changes the value itself</li>
<li>when there's another thread running that also uses the variable</li>
<li>when there's a signal handler that might change the value of the variable.</li>
</ul>
<p>Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:</p>
<pre><code>typedef struct
{
int command;
int data;
int isBusy;
} MyHardwareGadget;
</code></pre>
<p>Now you want to send some command:</p>
<pre><code>void SendCommand (MyHardwareGadget * gadget, int command, int data)
{
// wait while the gadget is busy:
while (gadget->isbusy)
{
// do nothing here.
}
// set data first:
gadget->data = data;
// writing the command starts the action:
gadget->command = command;
}
</code></pre>
<p>Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of <code>isBusy</code> just once and then go into an infinite loop. That's not what you want.</p>
<p>The way to get around this is to declare the pointer <code>gadget</code> as <code>volatile</code>. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either</p>
<p>This is the correct version:</p>
<pre><code>void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)
{
// wait while the gadget is busy:
while (gadget->isBusy)
{
// do nothing here.
}
// set data first:
gadget->data = data;
// writing the command starts the action:
gadget->command = command;
}
</code></pre>
|
<p>it does not allows compiler to automatic changing values of variables. a volatile variable is for dynamic use.</p>
| 30,539
|
<p>I'm creating an asp.net app with just some lite data access from xml files. However, I need to be able to authenticate administrative users (via forms) to manage that data. I don't want to stand up a sql db just for authentication purposes. I'd like to use xml, but not sure about security with that. Any suggestions? Custom role provider? MyOpenID?</p>
|
<p>Try the following: </p>
<pre><code>int number = 0;
while (number != 25)
{
Console.WriteLine("Guess a number between 20 through 25");
number = int.Parse(Console.ReadLine());
if (number != 25)
Console.WriteLine("Keep guessing");
else
Console.WriteLine("Merry Christmas");
}
</code></pre>
|
<pre><code>int number;
do
{
Console.WriteLine("Guess a number between 20 through 25");
number = int.Parse(Console.ReadLine());
} while (number != 25);
Console.WriteLine("Merry Christmas");
</code></pre>
<p>Would be correct if you want them to be able to enter numbers higher than 25.</p>
| 37,120
|
<p>If you are using ASP.NET MVC how are you doing grid display?
Rolled your own?
Got a library from somewhere?</p>
<p>These are some of the known grid display solutions I have found for ASP.NET MVC</p>
<ul>
<li><a href="http://www.codeproject.com/KB/aspnet/MVCFlexigrid.aspx" rel="noreferrer">ASP.NET MVC Flexgrid </a> - Has nice column layout method</li>
<li><a href="https://blog.maartenballiauw.be/post/2008/06/04/code-based-aspnet-mvc-gridview.html" rel="noreferrer">Code based ASP.NET MVC GridView</a> - simple, small, clean</li>
<li><a href="http://weblogs.asp.net/shijuvarghese/archive/2008/07/23/asp-net-mvc-grid-view-using-mvccontrib.aspx" rel="noreferrer">MVC Contrib</a> - grid from codePlex</li>
<li><a href="http://www.trirand.com/blog/?page%5Fid=6" rel="noreferrer">jQueryGrid</a> - jQuery grid</li>
<li><a href="http://www.datatables.net/" rel="noreferrer">Datatables</a> - jQuery plugin - believed to be section 508 compliant (<a href="https://github.com/mcintyre321/mvc.jquery.datatables" rel="noreferrer">.NET binding</a>)</li>
<li><a href="http://extjs.com/deploy/dev/examples/samples.html" rel="noreferrer">extJS</a> - cross browser RIA framework - has grid support</li>
<li><a href="http://www.reconstrukt.com/ingrid/" rel="noreferrer">Ingrid</a> - jQuery data grid</li>
<li><a href="http://jqwidgets.com/" rel="noreferrer">jqxGrid</a> - jQuery data grid</li>
<li><a href="http://demos.telerik.com/aspnet-mvc/" rel="noreferrer">Telerik MVC</a> - jQuery based grid that is GPL v2 licensed, commercial version also available</li>
<li><a href="http://mvccontrolstoolkit.codeplex.com/" rel="noreferrer">MVC Controls Toolkit</a> - Client Site Based Grid</li>
<li><a href="http://www.infragistics.com/dotnet/netadvantage/jquery-controls/grid.aspx" rel="noreferrer">Infragistics igGrid</a> - jQuery based MVC grid</li>
<li><a href="http://www.dhtmlx.com/blog/?p=1349" rel="noreferrer">dhtmlxGrid</a> - Ajax-enabled JavaScript grid control </li>
<li><a href="http://demo.aspnetawesome.com/Dinners" rel="noreferrer">ASP.net MVC Awesome Ajax List</a> - a different, very flexible approach, can be used as a grid</li>
<li><a href="http://mvc.syncfusion.com/sfmvcsamplebrowser/10.2.0.56/Grid_MVC/Samples/4.0/Razor" rel="noreferrer">Syncfusion MVC Grid</a> - Commercial grid</li>
<li><a href="http://demo.aspnetawesome.com/GridDemo" rel="noreferrer">ASP.net MVC Awesome Grid</a> - part of the Awesome library (jQuery based) </li>
<li><a href="http://demos.shieldui.com/mvc/grid-general/basic-usage" rel="noreferrer">Shield UI Grid for ASP.NET MVC</a></li>
<li><a href="http://mvc-grid.azurewebsites.net/" rel="noreferrer">Grid controls for ASP.NET MVC 5 projects</a></li>
</ul>
<p>If you know of anything else that you are using or know to be good, please let me know.</p>
|
<p>We have been using <a href="http://www.trirand.com/blog/?page_id=6" rel="noreferrer">jqGrid</a> on a project and have had some good luck with it. Lots of options for inline editing, etc. If that stuff isn't necessary, then we've just used a plain foreach loop like @Hrvoje.</p>
|
<p>Try: <a href="http://mvcjqgridcontrol.codeplex.com/" rel="nofollow noreferrer">http://mvcjqgridcontrol.codeplex.com/</a>
It's basically a MVC-compliant jQuery Grid wrapper with full .Net support</p>
| 21,356
|
<p>I am writing a tool to help students learn regular expressions. I will probably be writing it in Java.</p>
<p>The idea is this: the student types in a regular expression and the tool shows which parts of a text will get matched by the regex. Simple enough.</p>
<p>But I want to support several different regex "flavors" such as:</p>
<ul>
<li>Basic regular expressions (think: grep)</li>
<li>Extended regular expressions (think: egrep)</li>
<li>A subset of Perl regular expressions, including the character classes \w, \s, etc.</li>
<li>Sed-style regular expressions</li>
</ul>
<p>Java has the java.util.Regex class, but it supports only Perl-style regular expressions, which is a superset of the basic and extended REs. What I think I need is a way to take any given regular expression and escape the meta-characters that aren't part of a given flavor. Then I could give it to the Regex object and it would behave as if it was written for the selected RE interpreter.</p>
<p>For example, given the following regex:</p>
<pre><code>^\w+[0-9]{5}-(\d{4})?$
</code></pre>
<p>As a basic regular expression, it would be interpreted as:</p>
<pre><code>^\\w\+[0-9]\{5\}-\(\\d\{4\}\)\?$
</code></pre>
<p>As an extended regular expression, it would be:</p>
<pre><code>^\\w+[0-9]{5}-(\\d{4})?$
</code></pre>
<p>And as a Perl-style regex, it would be the same as the original expression.</p>
<p>Is there a "regular expression for regular expressions" than I could run through a regex search-and-replace to quote the non-meta characters? What else could I do? Are there alternative Java classes I could use?</p>
|
<p>Alternatively, you could use <a href="http://jakarta.apache.org/oro/" rel="nofollow noreferrer">Jakarta ORO</a>?</p>
<p>This supports the following regex 'flavors':</p>
<ul>
<li>Perl5 compatible regular expressions</li>
<li>AWK-like regular expressions</li>
<li>glob expressions</li>
</ul>
|
<p>if you want your students to learn regex,why not use a freely available tool -- regex Coach -- <a href="http://www.weitz.de/regex-coach/" rel="nofollow noreferrer">http://www.weitz.de/regex-coach/</a> on the net that is pretty good to learn and evaluate regexes ?</p>
<p>look at this SO thread on a similar issue -- <a href="https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world">https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world</a></p>
<p>BR,<BR>
~A</p>
| 28,157
|
<p>I want to do this: </p>
<blockquote>
<p>//*fu</p>
</blockquote>
<p>which returns all nodes whose name ends in <strong>fu</strong>, such as <code><tarfu /></code> and <code><snafu /></code>, but not <code><fubar /></code></p>
|
<p>Do something like:</p>
<pre><code>//*[ends-with(name(), 'fu')]
</code></pre>
<p>For a good XPath reference, check out <a href="http://www.w3schools.com/xml/xsl_functions.asp" rel="noreferrer">W3Schools</a>.</p>
|
<p>I struggled with Dimitre Novatchev's answer, it wouldn't return matches. I knew your XPath must have a section telling that "fu" has length 2. </p>
<p>It's advised to have a string-length('fu') to determine what to substring.</p>
<p>For those who aren't able to get results with his answer and they require solution with xpath 1.0:</p>
<p><code>//*[substring(name(), string-length(name()) - string-length('fu') +1) = 'fu']</code></p>
<blockquote>
<p>Finds matches of elements ending with "fu"</p>
</blockquote>
<p>or</p>
<p><code>//*[substring(name(), string-length(name()) - string-length('Position') +1) = 'Position']</code></p>
<blockquote>
<p>Finds matches to elements ending with "Position"</p>
</blockquote>
| 6,815
|
<p>I already know the obvious answer to this question: "just download <insert favorite windows grep or grep-like tool here>". However, I work in an environment with strict controls by the local IT staff as to what we're allowed to have on our computers. Suffice it to say: I have access to Perl on Windows XP. Here's a quick Perl script I came up with that does what I want, but I haven't figured up how to set up a batch file such that I can either pipe a command output into it, or pass a file (or list of files?) as an argument after the "expression to grep":</p>
<pre>
perl -n -e "print $_ if (m![expression]!);" [filename]
</pre>
<p>How do I write a batch script that I can do something like, for example:</p>
<pre>
dir | grep.bat mypattern
grep.bat mypattern myfile.txt
</pre>
<p><strong>EDIT</strong>: Even though I marked another "answer", I wanted to give kudos to <a href="https://stackoverflow.com/questions/106053/how-to-make-a-batch-file-to-act-like-a-simple-grep-using-perl#106099">Ray Hayes answer</a>, as it is really the "Windows Way" to do it, even if another answer is technically closer to what I wanted.</p>
|
<p>Most of the power of grep is already available on your machine in the Windows application FindStr.exe which is part of all Windows 2000, XP and Vista machines! It offers RegExpr etc.</p>
<p>Far easier than a batch file which in turn calls Perl!</p>
<pre><code>c:\>FindStr /?
Searches for strings in files.
FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
[/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
strings [[drive:][path]filename[ ...]]
/B Matches pattern if at the beginning of a line.
/E Matches pattern if at the end of a line.
/L Uses search strings literally.
/R Uses search strings as regular expressions.
/S Searches for matching files in the current directory and all
subdirectories.
/I Specifies that the search is not to be case-sensitive.
/X Prints lines that match exactly.
/V Prints only lines that do not contain a match.
/N Prints the line number before each line that matches.
/M Prints only the filename if a file contains a match.
/O Prints character offset before each matching line.
/P Skip files with non-printable characters.
/OFF[LINE] Do not skip files with offline attribute set.
/A:attr Specifies color attribute with two hex digits. See "color /?"
/F:file Reads file list from the specified file(/ stands for console).
/C:string Uses specified string as a literal search string.
/G:file Gets search strings from the specified file(/ stands for console).
/D:dir Search a semicolon delimited list of directories
strings Text to be searched for.
[drive:][path]filename
Specifies a file or files to search.
Use spaces to separate multiple search strings unless the argument is prefixed
with /C. For example, 'FINDSTR "hello there" x.y' searches for "hello" or
"there" in file x.y. 'FINDSTR /C:"hello there" x.y' searches for
"hello there" in file x.y.
Regular expression quick reference:
. Wildcard: any character
* Repeat: zero or more occurances of previous character or class
^ Line position: beginning of line
$ Line position: end of line
[class] Character class: any one character in set
[^class] Inverse class: any one character not in set
[x-y] Range: any characters within the specified range
\x Escape: literal use of metacharacter x
\<xyz Word position: beginning of word
xyz\> Word position: end of word
</code></pre>
|
<p>You need to do something like this:</p>
<pre><code>@echo off
perl -x -S script.pl %1
</code></pre>
<p>The "%1" will pass the argument to the Perl script. Save it as a .bat file, and you're good to go.</p>
| 13,156
|
<p>There are some tasks, especially the ones that involve deleting folders as SU, that I do thoughtfully and slowly before I press the Enter key. I think if others saw me do these at the careful pace that I do they would cringe. Are there critical programming tasks that you perform that you believe deserve this thoughtful and careful consideration?</p>
|
<p>Changes to live databases, actually I do a backup first just in case even know I'm extra careful :)</p>
|
<p>Common code. I.e. changes to old, shared code which is used in multiple independent programs.</p>
| 32,594
|
<p>I have a method in an objective-C class. It has 2 callback functions written in C. The class pointer i.e. <code>self</code> is passed to these functions as <code>void *</code>. In the C functions I create a pointer of type class and assign the <code>void *</code> parameter.
The first callback function executes successfully. But the <code>void *</code> pointer becomes <code>nil</code> in the 2nd callback function. Note that I haven't tweaked pointer in the first callback but still I get <code>nil</code> in 2nd callback.</p>
<p>Any ideas what might be going wrong?</p>
<p>For example:</p>
<pre><code>kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification,
matchingDict, RawDeviceAdded, NULL,
&gRawAddedIter);
RawDeviceAdded(NULL, gRawAddedIter, self);
</code></pre>
<p>This works fine. But below function receives <code>self</code> as <code>nil</code>.</p>
<pre><code>kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification,
matchingDict, BulkTestDeviceAdded, NULL,
&gBulkTestAddedIter);
BulkTestDeviceAdded(NULL, gBulkTestAddedIter, self);
</code></pre>
|
<p>Are your problems specifically with the IOKit callback routines? The problem with the specific example you gave is that the IOServiceMatchingCallback takes only 2 parameters, not 3. You need your RawDeviceAdded() and BulkTestDeviceAdded() callback functions to match the IOServiceMatchingCallback prototype and to accept self as the first parameter (refCon), not the 3rd. Also, you need to pass in self as the second-to-last parameter of IOServiceAddMatchingNotification() to get it passed back to you by the callback.</p>
<p>A common method for handling C callbacks in Objective-C code is just to have a static function that forwards the callback to your instance. So, your example callback code would look like this:</p>
<pre><code>static RawDeviceAdded(void* refcon, io_iterator_t iterator)
{
[(MyClass*)refcon rawDeviceAdded:iterator];
}
@implementation MyClass
- (void)setupCallbacks
{
// ... all preceding setup snipped
kr = IOServiceAddMatchingNotification(gNotifyPort,kIOFirstMatchNotification, matchingDict,RawDeviceAdded,(void*)self,&gRawAddedIter );
// call the callback method once to 'arm' the iterator
[self rawDeviceAdded:gRawAddedIterator];
}
- (void)rawDeviceAdded:(io_iterator_t)iterator
{
// take care of the iterator here, making sure to complete iteration to re-arm it
}
@end
</code></pre>
|
<p>This is what Objective-C's selector is for:
<a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSInvocationOperation_Class/Reference/Reference.html" rel="nofollow noreferrer"><a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSInvocationOperation_Class" rel="nofollow noreferrer">http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSInvocationOperation_Class</a></a></p>
<p>The API isn't very intuitive, but its fine once you understand it</p>
<p>You might need to do some refactoring as well, now there might be a better way, but when I had this problem my solution was to refactor and use InvoationOperation.</p>
| 40,920
|
<p>Is there a way run Emacs from a USB drive? I am a Windows user and I would like to be able use it on any PC without an Emacs install.</p>
|
<p>Yes, the "normal" Emacs distribution for Windows is precompiled and just runs without having to do any install. Just get <a href="http://ftp.gnu.org/gnu/windows/emacs/" rel="noreferrer">one of the *.zip files from the usual place</a>, unpack it onto a USB disk, and you can use it directly. (The actual binary is inside the "bin/" directory.)</p>
<p>The only thing you may want to do is set it up to look for ".emacs" always on the USB disk instead of on your hard drive; see </p>
<pre><code> (info "(emacs) Windows HOME")
</code></pre>
<p>on how to do that.</p>
|
<p>I have ported emacs to portable apps format.</p>
<p><a href="http://esnm.sourceforge.net/download.html" rel="nofollow noreferrer">http://esnm.sourceforge.net/download.html</a></p>
| 45,600
|
<p>I'm about to start testing an intranet web application. Specifically, I've to determine the application's performance.</p>
<p>Please could someone suggest formal/informal standards for how I can judge the application's performance.</p>
|
<p>Use some tool for stress and load testing. If you're using Java take a look at <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">JMeter</a>. It provides different methods to test you application performance. You should focus on:</p>
<ul>
<li><strong>Response time</strong>: How fast your application is running for normal requests. Test some read/write use case</li>
<li><strong>Load test</strong>: How your application behaves in high traffic times. The tool will submit several requests (you can configure that properly) during a period of time.</li>
<li><strong>Stress test</strong>: Do your application can operate during a long period of time? This test will push your application to the limits</li>
</ul>
<p>Start with this, if you're interested, there are other kinds of tests.</p>
|
<p>To test the front-end then YSlow is great for getting statistics for how long your pages take to load from a user perspective. It breaks down into stats for each specfic HTTP request, the time it took, etc. Get it at <a href="http://developer.yahoo.com/yslow/" rel="nofollow noreferrer">http://developer.yahoo.com/yslow/</a></p>
<p>Firebug, of course, also is essential. You can profile your JS explicitly or in real time by hitting the profile button. Making optimisations where necessary and seeing how long all your functions take to run. This changed the way I measure the performance of my JS code. <a href="http://getfirebug.com/js.html" rel="nofollow noreferrer">http://getfirebug.com/js.html</a></p>
| 6,326
|
<p>Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc. </p>
|
<p>First be sure you really need to support copy. Most of the time it is not the case, and thus disabling both is the way to go.</p>
<p>Sometimes, you'll still need to provide duplication on a class from a polymorphic hierarchy, in that case: disable the assignment operator, write a (protected?) copy constructor, and provide a virtual clone() function.</p>
<p>Otherwise, in the case you are writing a value class, you're back into the land of the Orthogonal Canonical Form of Coplien. If you have a member that can't be trivially copied, you'll need to provide a copy-constructor, a destructor, an assignment-operator and a default constructor. This rule can be refined, see for instance: <a href="http://www.artima.com/cppsource/bigtwo.html" rel="nofollow noreferrer">The Law of The Big Two</a></p>
<p>I'd also recommend to have a look at <a href="http://www.parashift.com/c++-faq/assignment-operators.html" rel="nofollow noreferrer">C++ FAQ regarding assignment operators</a>, and at the <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-and-swap" rel="nofollow noreferrer">copy-and-swap idiom</a> and at <a href="http://www.gotw.ca/gotw/059.htm" rel="nofollow noreferrer">GOTW</a>.</p>
|
<p>I have no idea about exception safely here but I go this way. Let's imagine it's a templated array wrapper. Hope it helps :)</p>
<pre><code>Array(const Array& rhs)
{
mData = NULL;
mSize = rhs.size();
*this = rhs;
}
Array& operator=(const Array& rhs)
{
if(this == &rhs)
{
return *this;
}
int len = rhs.size();
delete[] mData;
mData = new T[len];
for(int i = 0; i < len; ++i)
{
mData[i] = rhs[i];
}
mSize = len;
return *this;
}
</code></pre>
| 26,417
|
<p>I was pointed to SubSonic (www.subsonicproject.com), but then I found WebWidgetry (www.nthpenguin.com) Before I dig into them too much I'm curious to know who's used either and what the pro's and con's might be?</p>
<p>Thanks for the help,
Jim</p>
|
<p>I have used SubSonic once before and it was incredibly easy to setup and use. I was actually quite impressed, and for ORM tools it takes a lot to impress me.</p>
|
<p>WebWidgetry, seems to be in a release candidate while subsonic is a fairly well known ORM mapper. </p>
<p>WW also seems to be going for a totally different market.
Subsonic is a general purpose ORM which is modelled to be fast and easy to use. </p>
<p>My basic advice if you want to use anything in production wait till it's got sufficient testing / community behind it. </p>
<p>RC releases are usually not the best thing when it comes to quality and support might be lacking. </p>
| 32,942
|
<p>I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.</p>
<p>What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this. </p>
<p>I've been doing this via JavaScript, which works so far, using the following code</p>
<pre><code>document.getElementById('chart').src = '/charts/10.png';
</code></pre>
<p>The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond.</p>
<p>What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it. </p>
<p>I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image. </p>
<p>A good suggestion I've had is to use the following</p>
<pre><code><img src="/charts/10.png" lowsrc="/spinner.gif"/>
</code></pre>
<p>Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed.</p>
<p>Any other ideas?</p>
|
<p>I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback.</p>
<pre><code>function PreloadImage(imgSrc, callback){
var objImagePreloader = new Image();
objImagePreloader.src = imgSrc;
if(objImagePreloader.complete){
callback();
objImagePreloader.onload=function(){};
}
else{
objImagePreloader.onload = function() {
callback();
// clear onLoad, IE behaves irratically with animated gifs otherwise
objImagePreloader.onload=function(){};
}
}
}
</code></pre>
|
<p>@iAn's solution looks good to me. The only thing I'd change is instead of using setTimeout, I'd try and hook into the images 'Load' event. This way, if the image takes longer than 3 seconds to download, you'll still get the spinner.</p>
<p>On the other hand, if it takes less time to download, you'll get the spinner for less than 3 seconds.</p>
| 7,441
|
<p>The last time I took on a non-trivial .Net/C# application I used Castle Monorail and, on the whole, enjoyed the experience. Early-access/preview releases of .Net MVC were not yet available. Many "Microsoft shops" will now find the "official" solution more appealing. Has anyone gone from Monorail to .Net MVC. </p>
<p>How did you find the switch?<br>
What are the biggest differences, presently?</p>
|
<p>While I haven't made the switch yet, I have developed on both platforms and have been doing some pre-switch analysis. </p>
<p>It looks like the biggest difference would be the View Engines. Our Monorail stuff uses the Brail view engine while asp.net mvc comes (stock) with a webforms like view engine. There are other view engines in MvcContrib which could help in this area, though.</p>
<p>Also ViewComponents and view "helpers" seem to be handled quite differently the two frameworks.</p>
|
<p>The ASP.NET MVC team is still making changes before v1.0, so now's a good time to <a href="http://forums.asp.net/1146.aspx" rel="nofollow noreferrer">provide feedback</a>.</p>
<p>Also, be aware that there are more frequent releases on <a href="http://www.codeplex.com/aspnet" rel="nofollow noreferrer">CodePlex</a>, while the home page on www.asp.net still links to Preview 3.</p>
| 4,389
|
<p>What is the best way to determine available bandwidth in .NET?</p>
<p>We have users that access business applications from various remote access points, wired and wireless and at times the bandwidth can be very low based on where the user is. When the applications appear to be running slow, the issue could be due to low bandwidth and not some other issue.</p>
<p>I would like to be able to run some kind of service that would warn users whenever the available bandwidth dips below a specific threshold.</p>
<p>Any thoughts?</p>
|
<p>Not beyond the obvious of downloading a file of a known size and timing how long it takes. the disadvantage of that is that you'd need to waste a lot of bandwidth to do it. Also, if you wanted to alert when throughput drops below a threshold, you'll have to run the test more-or-less continuously.</p>
<p>IMHO, I'd live with poor performance in some locations, given that you can't do anything about it if it does occur.</p>
<p>Sorry.</p>
|
<p>If you're transferring data, simply measure it. You could also download a reference object from somewhere if you want to make it independent of the speed of your server.</p>
| 17,985
|
<p>I have a project that builds fine If I build it manually but it fails with CC.NET.</p>
<p>The error that shows up on CC.NET is basically related to an import that's failing because file was not found; one of the projects (C++ dll) tries to import a dll built by another project. Dll should be in the right place since there's a dependency between the projects - indeeed when I build manually everything works fine (Note that when I say manually I am getting everything fresh from source code repository then invoking a Rebuild from VS2005 to simulate CC.NET automation).</p>
<p>looks like dependencies are ignored when the build is automated through CC.NET.</p>
<p>I am building in Release MinDependency mode.</p>
<p>Any help would be highly appreciated! </p>
|
<p>Can you change CC to use msbuild instead of devenv? That seems like the optimal solution to me, as it means the build is the same in both situations.</p>
|
<p>I wonder if CC.Net is building with different environment variables, such that the necessary library directories aren't properly added to the path.</p>
<p>Is there any specific error message in the CC.Net build log as to why that particular DLL import failed? Could not find file? Permissions? Look in the detailed CC.Net build log for the failure and see where it differs from a normal command-line build.</p>
| 34,500
|
<p>I am adding dynamically controls to page by using LoadControl and Controls.Add. I need somehow to wrap Init and Load event handlers of this loaded controls into my code. So it should be such order of events <em>SomeMyCode() -> Control.Init() -> AnotherMyCode()</em> and the same for Load <em>SomeMyCode() -> Control.Load() -> AnotherMyCode()</em>.<br/>
My idea was to Get List of Control's event handlers for Init and Load events and add first and last event handers with code I should to run. But I cannot figure out how to do this.</p>
|
<p>Usually you can just remove the '>' and it will work. It's a matter of how your CSS and HTML is written. I'd give it a shot. </p>
|
<p>You could target them using JavaScript, but that hardly is a real solution since it would require javaScript for something that should be done by CSS. You could also modify your HTML to have specific classes, but that means modifying you HTML. I don't really think there are any 'nice' solutions, I would probably hack it all together using JavaScript if it was me who had to take care of this, or if I had acces to the HTML or HTML creating script use classes for those specific children.</p>
| 48,735
|
<p>Carbon 3d made a 100x faster printer which has a simple and cheap mechanism using a Teflon layer. It appears to have a 20mn in RnD Costs and $7000 mass market production cost.</p>
<p>The only access method for one is a USD$ 161,250 yearly subscription.</p>
<p>Their printer is not available in shapeways... Is there something wrong with Carbon 3D so that it does not view consumers as a direct market, and has no market news on it's website?</p>
<p>How can they spend 222 million in investment money and not have a 3d printer in shapeways or public access? </p>
|
<p>I will take the question seriously, and consider reasons why Carbon 3D might choose to offer their technology through a yearly subscription, rather than building a product accessible to the consumer market. These reasons are speculation and do not reflect any specific knowledge about Carbon 3D, the details of their technology, or anything unique about their corporate mission.</p>
<p>1) The mission of a company, especially in the beginning while competition makes it possible, to make as much money as possible. If the technology is unique and brings good value to a large enough set of interested customers, it can easily consume the full attention of a company to service those customers. The price those companies pay for access may be higher than others would pay because their derived value is higher.</p>
<p>2) If a technology is new, and perhaps still somewhat immature, there may be very high support efforts and cost required. Through this time, the learning curve does it's job, the technology improves and matures, and the costs go down.</p>
<p>3) If the technology is immature, and perhaps is evolving quickly, it could be to the advantage of a supplier to only offer the technology on a service rather than capital acquisition basis. It simplifies replacing components. </p>
<p>4) If the technology is immature, selling the service may be easier than selling the hardware. It simplifies the acquisition process, and makes it easier for customer's to expand their usage since the supplier's capital is used to finance the machines instead of the customer's.</p>
<p>5) Even with a mature, proven technology, it can be advantageous to maintain a higher price point. The game is optimizing the profit on volume times price. The point they operate at is influenced by their perception of the market.</p>
<p>6) In the early adopter phase, it is critical that the customer experience be stellar. They may be limited in how rapidly they can scale in some critical dimension -- consumables supply chain, manufacturing capacity, trained installation technicians, local service offices, or many other limits. Anything going wrong makes for a bad customer experience.</p>
<p>It doesn't surprise me that they aren't going after the consumer market at this time.</p>
<p>But, I'm not in the CEO's office, and I don't see where his pain comes from. My purpose here is only to propose some plausible reasons why the company has not launched a consumer facing product.</p>
|
<p>It looks like they have only one innovation: their resins. Everything else looks like standard SLA. </p>
<p>All the things Carbon 3D are pitching on their website are more about having a dedicated support team than some fancy printer, and that's what they're selling. </p>
<p>As to why they don't make a home version: why would they? It's <em>at best</em> a distraction from their core business.</p>
| 667
|
<p>I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page.</p>
<p>Any sample code would be greatly appreciated!</p>
<p>Link to API: <a href="http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf" rel="nofollow noreferrer">http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf</a></p>
|
<p>I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simplest way to do this in .NET is using the WebClient class. Alternatively you might want to take a look at the HttpWebRequest/HttpWebResponse classes. Here is some sample code using WebClient:</p>
<pre><code>using System.Net;
using System.Text;
using System;
namespace RightNowSample
{
class Program
{
static void Main(string[] args)
{
string serviceUrl = "http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php";
WebClient webClient = new WebClient();
string requestXml =
@"<connector>
<function name=""ans_get"">
<parameter name=""args"" type=""pair"">
<pair name=""id"" type=""integer"">33</pair>
<pair name=""sub_tbl"" type='pair'>
<pair name=""tbl_id"" type=""integer"">164</pair>
</pair>
</parameter>
</function>
</connector>";
string secString = "";
string postData = string.Format("xml_doc={0}, sec_string={1}", requestXml, secString);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
byte[] responseDataBytes = webClient.UploadData(serviceUrl, "POST", postDataBytes);
string responseData = Encoding.UTF8.GetString(responseDataBytes);
Console.WriteLine(responseData);
}
}
}
</code></pre>
<p>I have no access to RightNow CRM, so I could not test this, but it can serve as s tarting point for you.</p>
|
<p>This will Create a Contact in Right now</p>
<pre><code> class Program
{
private RightNowSyncPortClient _Service;
public Program()
{
_Service = new RightNowSyncPortClient();
_Service.ClientCredentials.UserName.UserName = "Rightnow UID";
_Service.ClientCredentials.UserName.Password = "Right now password";
}
private Contact Contactinfo()
{
Contact newContact = new Contact();
PersonName personName = new PersonName();
personName.First = "conatctname";
personName.Last = "conatctlastname";
newContact.Name = personName;
Email[] emailArray = new Email[1];
emailArray[0] = new Email();
emailArray[0].action = ActionEnum.add;
emailArray[0].actionSpecified = true;
emailArray[0].Address = "mail@mail.com";
NamedID addressType = new NamedID();
ID addressTypeID = new ID();
addressTypeID.id = 1;
addressType.ID = addressTypeID;
addressType.ID.idSpecified = true;
emailArray[0].AddressType = addressType;
emailArray[0].Invalid = false;
emailArray[0].InvalidSpecified = true;
newContact.Emails = emailArray;
return newContact;
}
public long CreateContact()
{
Contact newContact = Contactinfo();
//Set the application ID in the client info header
ClientInfoHeader clientInfoHeader = new ClientInfoHeader();
clientInfoHeader.AppID = ".NET Getting Started";
//Set the create processing options, allow external events and rules to execute
CreateProcessingOptions createProcessingOptions = new CreateProcessingOptions();
createProcessingOptions.SuppressExternalEvents = false;
createProcessingOptions.SuppressRules = false;
RNObject[] createObjects = new RNObject[] { newContact };
//Invoke the create operation on the RightNow server
RNObject[] createResults = _Service.Create(clientInfoHeader, createObjects, createProcessingOptions);
//We only created a single contact, this will be at index 0 of the results
newContact = createResults[0] as Contact;
return newContact.ID.id;
}
static void Main(string[] args)
{
Program RBSP = new Program();
try
{
long newContactID = RBSP.CreateContact();
System.Console.WriteLine("New Contact Created with ID: " + newContactID);
}
catch (FaultException ex)
{
Console.WriteLine(ex.Code);
Console.WriteLine(ex.Message);
}
System.Console.Read();
}
}
</code></pre>
| 16,945
|
<p><a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7ab67d24-6afa-4be6-855e-e260845a47e2/" rel="noreferrer">Tell me it ain't so</a>.</p>
<p>I have a typical windows/file explorer like setup.</p>
<ul>
<li>Left Side I have a TreeView all data bound showing nodes in a hierachy</li>
<li>Right Side I have a ListView showing Node.Properties</li>
</ul>
<p>ListView has a IsSynchronizedWithCurrentItem property, which rocks. e.g. If I had another ListView showing a list of nodes and both listViews have this property set to true. Changing selection of node in NodesListView will update the PropertiesListView automatically.</p>
<p>Now I need the same thing with a NodesTreeView and a PropertiesListView... and seems like TreeView has no such property. </p>
<p>Is there a more 'the WPF way' kind of solution to this problem ? Or do I have to handle the NodeSelectionChanged event of the Tree and refresh the listView via code.</p>
|
<p>A really simple solution is to bind your "details" UI elements to the SelectedValue property of the TreeView. For example, if your TreeView looked like this:</p>
<pre><code><TreeView Name="CategoryName" ItemsSource="{Binding Source={StaticResource A_Collection}, Path=RootItems}" />
</code></pre>
<p>Then you could bind details UI elements (like a textbox) using:</p>
<pre><code><TextBox Text="{Binding ElementName=CategoryTreeView, Path=SelectedValue.Name}"/>
</code></pre>
<p>Would cause the text box to be bound to Name property of the items currently selected in the TreeView.</p>
<p>If you want to bind many UI items as details for the selected TreeView item, consider setting up a DataContext on the elemtent that contains all the details controls (DockPanel / Grid / StackPanel, etc).</p>
|
<p>My solution to this turned out to be pretty tiny.. don't know if it is equivalent to IsSynchronizedWithCurrentItem. ListView refreshes as expected.</p>
<pre><code>// the XAML
<TreeView DockPanel.Dock="Left" x:Name="tvwNodes" ItemsSource="{Binding}" SelectedItemChanged="OnNewNodeSelected"/>
<ListView x:Name="lvwProperties" ItemsSource="{Binding Path=Properties}"
// the code-behind
private void OnNewNodeSelected(object sender, RoutedPropertyChangedEventArgs<object> e)
{
lvwProperties.DataContext = tvwNodes.SelectedItem; // this returns the selected Node obj
}
</code></pre>
| 48,924
|
<p>I'm using maven 2.0.9 with Eclipse 3.3.2.</p>
<p>I'm used to launching a fresh build once per day by a <code>mvn clean install</code>.
Then, if I refresh my Eclipse project, it will be "polluted" by files from Maven's <em>target</em> directory.</p>
<p>That's very annoying while performing searches, getting resources by "open resource" and so on.</p>
<p>Is there a way to avoid Eclipse looking in this folder?</p>
|
<p>Right click on the folder you want to ignore, open the "Properties" dialog, chose the "Resource" tab and check the box that says "Derived"</p>
|
<p>When Eclipse freezes, looking at the process activity, I can see it browsing all my target, .hg and .git directories. Moreover, those directories are also copied into Eclipse's bin directory. A lot of CPU and disk usage for nothing.</p>
<p>Not cleaning the target directory is not an acceptable solution.</p>
<p>There was a solution using a Monkey script (http://maven.40175.n5.nabble.com/Eclipse-amp-target-directory-td72354.html) but the project has been closed.</p>
<p>I still look for a solution to tell Eclipse to ignore Maven target directories, as well as .hg and .git directories.</p>
<p>Eclipse continuously watching those is a pain.</p>
<p>I also use m2eclipse but it doesn't solve that issue.</p>
| 35,946
|
<p>I tried to use <code>OPTION (MAXRECURSION 0)</code> in a view to generate a list of dates.
This seems to be unsupported. Is there a workaround for this issue?</p>
<p>EDIT to Explain what I actually want to do:</p>
<p>I have 2 tables.</p>
<p>table1: int weekday, bool available</p>
<p>table2: datetime date, bool available</p>
<p>I want the result:
view1: date (here all days in this year), available(from table2 or from table1 when not in table2).</p>
<p>That means I have to apply a join on a date with a weekday.
I hope this explanation is understandable, because I actually use more tables with more fields in the query.</p>
<p>I found this code to generate the recursion:</p>
<pre><code>WITH Dates AS
(
SELECT cast('2008-01-01' as datetime) Date
UNION ALL
SELECT Date + 1
FROM Dates
WHERE Date + 1 < DATEADD(yy, 1, GETDATE())
)
</code></pre>
|
<p><a href="http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=124653" rel="nofollow noreferrer">No</a> - if you can find a way to do it within 100 levels of recusion (have a table of numbers), which will get you to within 100 recursion levels, you'll be able to do it. But if you have a numbers or pivot table, you won't need the recursion anyway...</p>
<p>See <a href="https://stackoverflow.com/questions/10819/sql-auxiliary-table-of-numbers">this question</a> (but I would create a table and not a table-valued function), <a href="https://stackoverflow.com/questions/40456/sql-missing-rows-when-grouped-by-day-month-year">this question</a> and <a href="http://andre-silva-cardoso.blogspot.com/2007/11/sql-trickspatterns-1-numbers-table.html" rel="nofollow noreferrer">this link</a> and <a href="http://www.sqlmag.com/Article/ArticleID/94376/sql_server_94376.html" rel="nofollow noreferrer">this link</a></p>
|
<p>You can use a <a href="http://blog.crowe.co.nz/archive/2007/09/06/Microsoft-SQL-Server-2005---CTE-Example-of-a-simple.aspx" rel="nofollow noreferrer">CTE</a> for hierarchical queries.</p>
| 31,680
|
<p>What is the equivalent of <code>/dev/null</code> on Windows?</p>
|
<p>I think you want <code>NUL</code>, at least within a command prompt or batch files.</p>
<p>For example:</p>
<pre><code>type c:\autoexec.bat > NUL
</code></pre>
<p>doesn't create a file.</p>
<p>(I <em>believe</em> the same is true if you try to create a file programmatically, but I haven't tried it.)</p>
<p>In PowerShell, you want <code>$null</code>:</p>
<pre><code>echo 1 > $null
</code></pre>
|
<p>You have to use <strong><em>start</em></strong> and <strong><em>$NUL</em></strong> for this in <strong>Windows PowerShell</strong>:</p>
<p>Type in this command assuming <code>mySum</code> is the name of your application and <code>5</code> <code>10</code> are command line arguments you are sending.</p>
<pre><code>start .\mySum 5 10 > $NUL 2>&1
</code></pre>
<p>The <code>start</code> command will start a detached process, a similar effect to <code>&</code>. The <code>/B</code> option prevents start from opening a new terminal window if the program you are running is a console application. and <code>NUL</code> is Windows' equivalent of <code>/dev/null</code>. The <code>2>&1</code> at the end will redirect stderr to stdout, which will all go to <code>NUL</code>.</p>
| 40,360
|
<p>I'm trying to get tags working in my rails application and want to use acts_as_taggable. Firstly I followed the instructions I found in Rails Recipies (a free sample bit online) that used the acts_as_taggable plugin. However, I then found <a href="http://taggable.rubyforge.org/" rel="nofollow noreferrer">this site</a> which seems to have a gem for acts_as_taggable which is more advanced (has options for related tags etc).</p>
<p>I've tried to follow the instructions there to install it, but I keep getting errors.</p>
<p>Firstly I installed the gem as normal (<code>gem install acts_as_taggable</code>) and then I tried various ways to get rails to recognise and load the gem. The <code>require_gem</code> listed on the site didn't work (I assume that is an old command that has been removed) and neither did a straight <code>require</code> (although that has worked for my bluecloth gem).</p>
<p>I've then tried using <code>config.gem 'acts_as_taggable'</code> but that keeps telling me that I haven't got acts_as_taggable installed and asks me to run <code>rake gems:install</code>. No matter how many times I run that it still gives the error!</p>
<p>The result of the <code>gem query -l -n acts_as_taggable</code> lists acts_as_taggable as an installed local gem.</p>
<p>I've tried running <code>gem check</code> and that doesn't show any problems.</p>
<p>The response I get when I try to require it from the console is:</p>
<pre><code>MissingSourceFile: no such file to load -- acts_as_taggable
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `ge
m_original_require'
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `re
quire'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_suppo
rt/dependencies.rb:510:in `require'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_suppo
rt/dependencies.rb:355:in `new_constants_in'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_suppo
rt/dependencies.rb:510:in `require'
from (irb):1
</code></pre>
<p>It looks like for some reason it can't find it. Any ideas why?</p>
|
<p>You could also try <a href="http://agilewebdevelopment.com/plugins/acts_as_taggable_on_steroids" rel="nofollow noreferrer">acts_as_taggable_on_steroids</a>:</p>
<blockquote>
<p>This plugin is based on acts_as_taggable by DHH but includes extras such as tests, smarter tag assignment, and tag cloud calculations.</p>
</blockquote>
<p>I've used it recently. Aside from some performance issues, it works very well and, unlike <a href="http://taggable.rubyforge.org/" rel="nofollow noreferrer">taggable</a>, is under active maintenance.</p>
|
<p>Have you tried running something like "gem query -l -n <em>taggable</em>" to check whether it has installed correctly into your local gem repository?</p>
<p>If it has you could use some of the built in checks against it - <a href="http://www.rubygems.org/read/chapter/10" rel="nofollow noreferrer">Gem is good for this</a> - to make sure it installed as it is supposed to.</p>
<p>That would be my first avenue to explore.</p>
| 28,338
|
<p>Obviously there are security reasons to close a wireless network and it's not fun if someone is stealing your bandwidth. That would be a serious problem?</p>
<p>To address the first concern: Does a device on the same wireless network have any special privileges or access that an other device on the internet has?<br>
<strong>Assumptions :</strong> Wireless network is connected to the internet</p>
<p>The second seems like a community issue. If your neighbor is stealing bandwidth, you'd act just as if he were "borrowing" water or electricity. </p>
<p>First, Talk to him about the problem and if that doesn't work, go to the authorities or lock stuff up. Am I missing something?</p>
|
<p>Bruce Schneier is famous for running an open wireless network at home (<a href="http://www.schneier.com/blog/archives/2008/01/my_open_wireles.html" rel="noreferrer">see here</a>). He does it for two reasons:</p>
<ol>
<li>To be neighborly (you'd let your neighbor borrow a cup of sugar, wouldn't you? Why not a few megabits?)</li>
<li>To keep away from the false sense of security that a firewall gives you. In other words, it forces him to make sure his hosts are secure.</li>
</ol>
<p>Personally, I would never run an open wireless network for one reason: accountability. If someone does something illegal on my network, I don't want to be held accountable.</p>
|
<p>@kronoz: I guess it depends on where you live. Only two houses are within reach of my wireless network, excluding my own. So I doubt that small number of people can affect my bandwidth. But if you live in a major metro area, and many people are able to see and get on the network, yeah, it might become a problem.</p>
| 5,295
|
<p>I found <a href="http://www.databaseanswers.org/data_models/" rel="nofollow noreferrer">http://www.databaseanswers.org/data_models/</a> very useful. Any other suggestions?</p>
|
<p>If you're just looking for data models, I recommend the following books:</p>
<ul>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0471380237" rel="nofollow noreferrer" rel="nofollow noreferrer">The Data Model Resource Book, Vol.
1: A Library of Universal Data
Models for All Enterprises</a></li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0471353485" rel="nofollow noreferrer" rel="nofollow noreferrer">The Data Model Resource Book, Vol. 2: A Library of Data Models for Specific Industries</a> </li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0470178450" rel="nofollow noreferrer" rel="nofollow noreferrer">The Data Model Resource Book: Universal Patterns for Data Modeling</a> </li>
</ul>
<p>I have Vol 1 and Vol 2 and these have been pretty helpful in the past.</p>
|
<p>Microsoft have db samples in <strong>VS2005</strong> and <strong>VS2008</strong>, but you can also download it from here:
<a href="http://msdn.microsoft.com/en-us/library/ms227484.aspx" rel="nofollow noreferrer">Northwind Database</a></p>
| 44,635
|
<p>How do I share state amongst TestMethods in MSTest. These tests would be run as Ordered Tests and in sequence.</p>
<pre><code> private TestContext testContext;
public TestContext TestContext
{
get { return this.testContext; }
set { this.testContext = value;}
}
[TestMethod]
public void Subscribe()
{
bool subscribed = true;
TestContext.Properties.Add("subscribed", subscribed);
Assert.IsTrue(subscribed == true, string.Format("Subscribed...{0}", this.GetHashCode()));
}
[TestMethod]
public void GenerateEvent()
{
bool subscribed = (bool)TestContext.Properties["subscribed"];
Assert.IsTrue(subscribed == true, string.Format("Subscribed...{0}", this.GetHashCode()));
}
</code></pre>
<p>Thanks in advance.</p>
|
<p>Vyas, I agree with Chad that you're still doing it wrong. </p>
<p>That said, you can look into using the TestContext object.</p>
<p>See <a href="http://blogs.msdn.com/vstsqualitytools/archive/2006/01/10/511030.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/vstsqualitytools/archive/2006/01/10/511030.aspx</a></p>
|
<p>As Chad had pointed out, it seems that I have no alternative but to use a single test [For once the tool is forcing me to do the right thing ;)] to test the whole flow.</p>
<p>Seems that I could use TestContext.BeginTimer & EndTimer to time each call in the method.</p>
<p>Here's the link to MSDN Forum where I received this answer</p>
| 25,893
|
<p>I can never remember the differences in regular expression syntax used by tools like <a href="http://en.wikipedia.org/wiki/Grep" rel="noreferrer">grep</a> and <a href="http://en.wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a>, or languages like Python and PHP. Generally, Perl has the most expansive syntax, but I'm often hamstrung by the limitations of even <code>egrep</code> ("extended" <code>grep</code>).</p>
<p>Is there a site that lists the differences in a concise and easy-to-read fashion?</p>
|
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0596528124" rel="nofollow noreferrer" rel="nofollow noreferrer">Mastering Regular Expressions</a>, devotes the last four chapters to Java, PHP, Perl, and <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a>. One chapter for each. From what I know, the <a href="https://rads.stackoverflow.com/amzn/click/com/0596514271" rel="nofollow noreferrer" rel="nofollow noreferrer">pocket edition</a> contains just those final four chapters. </p>
|
<p>I find this site helpful: <a href="http://www.regular-expressions.info/" rel="noreferrer">http://www.regular-expressions.info/</a></p>
<p>Other than that, I use the corresponding documentation extensively and I believe, all said and done, there's no way around that.</p>
| 4,322
|
<p>I am building a blog type page, and I want to load items into the page as the user scrolls down, much like Google Reader, or Soup.io. How would you go about achieving this effect? I've seen some examples which read the height of the page, and have an onScroll even attached to the window so that as the user scrolls down we can test to see if they've scrolled down far enough to warrant loading more items. Soup.io's implementation seems to remove the old items as you scroll down so that the browser isn't dealing with an ever-increasingly large DOM tree. Which javascript libraries would be best suited to this task?</p>
|
<p>Unspace had an article demonstrating this functionality: <a href="https://web.archive.org/web/20071009004156/http://unspace.ca/discover/pageless/" rel="nofollow noreferrer">Endless Pageless: No More Next Page</a>. Their demonstration page is <a href="https://web.archive.org/web/20071009004258/http://unspace.ca/livefilter" rel="nofollow noreferrer">here</a> (dead, for reference).</p>
<p>This particular example uses RoR and <a href="http://www.prototypejs.org/" rel="nofollow noreferrer">Prototype.</a></p>
|
<p>Thy this jquery example <a href="http://webdeveloperplus.com/jquery/create-a-dynamic-scrolling-content-box-using-ajax/" rel="nofollow">http://webdeveloperplus.com/jquery/create-a-dynamic-scrolling-content-box-using-ajax/</a></p>
| 22,221
|
<p>Does anyone know how a <code>System.Windows.Forms.Timer</code> affects the host application and the system in general?</p>
<p>A threaded background loop on one hand has a very high CPU usage %, whilst a <code>Timer</code> with a very high tick rate shows no effect in Windows Task Manager.</p>
<p>Does a high tick-rate timer clutter up the Windows Message loop, or?</p>
|
<p>Define "high tick rate timer" :).</p>
<p>The problem with timer components relying on WM_TIMER (such as the Windows.Forms one) is manifold:</p>
<ul>
<li>You will <em>not</em> be able to get a resolution better than 50 msec out of it, ever.</li>
<li>If your system is under load (e.g. heavy redrawing, running over RDP links, etc.) you might get WM_TIMER messages once every 500 msec or more, no matter how low you've set the interval.</li>
<li>WM_TIMER messages are synthetic messages and might not get delivered to your application at all for prolonged periods of time if your message queue gets flooded with other messages.</li>
<li>If your timer method takes longer than one timer interval to execute, the timer will "skip" the message, i.e. you will not get another WM_TIMER message until you've returned from the first one. In other words, you will never get two WM_TIMER messages one after the other in sequence.</li>
</ul>
|
<p>Overall I have not noticed many negative downfalls to using a timer component inside my application, they are much more effective, and better on resources than some other methods out there.</p>
<p>I find that this <a href="http://msdn.microsoft.com/en-us/magazine/cc164015.aspx" rel="nofollow noreferrer">Timer Comparison</a> article from microsoft is also helpful when comparing these types of things.</p>
<p>But the long and short of it is that they don't appear to clutter up much.</p>
| 43,031
|
<p>In Windows XP:</p>
<p>How do you direct traffic to/from a particular site to a specific NIC?</p>
<p>For Instance: How do I say, all connections to stackoverflow.com should use my wireless connection, while all other sites will use my ethernet?</p>
|
<p>I'm not sure if there's an easier way, but one way would be to add a route to the IP(s) of stackoverflow.com that explicitly specifies your wireless connection, using a lower metric (cost) than your default route.</p>
<p>Running nslookup www.stackoverflow.com shows only one IP: 67.199.15.132, so the syntax would be:</p>
<pre>route -p add 67.199.15.132 [your wireless gateway] metric [lower metric than default route] IF [wireless interface]</pre>
<p>See the route command for more info.</p>
|
<p>you should be able to do it using the route command. Route add (ip address) (netmask) (gateway) metric 1</p>
| 9,923
|
<p>I wonder how can I write a <strong><em>catch'em all</em></strong> exception handler in the application level which will give the user the option to resume the application flow?</p>
|
<p>If you are running a Windows Forms application: add a handler to the <code>Application.ThreadException</code> event.</p>
|
<p>This just screams bad design all over. Never use exceptions for things like this. Exceptions are ONLY to be used when something the programmer did not intend to occures.</p>
<p>If you want error-handling. dont use exceptions like this, rahter build a system where you save states and can go back to states etc... but using exceptions for state handling, bad idea.</p>
| 43,822
|
<p>I see that in the SQL Server Reporting Services 2005 Report Manager there is the capability to schedule reports for specific times (i.e. every weekday at a particular time). </p>
<p>What I would like though is more control -- i.e. every weekday, but only between certain dates of the year -- for example, getting sales figures every day starting 6 weeks before Christmas and ending 1 week after Christmas. There is a table that has the dates. How do I set that up in SQL Server Reporting Services 2005?</p>
|
<p>If you have Enterprise Edition you can create a Data Driven Subscription, whereby you generate a table of the report recipients and parameters and then point the report subscription to the table. You have complete control over how the table gets populated so you can make sure it only gets populated on the days you want the report to go out (the subscription would run every day but if the table is empty, it doesn't go out to anyone).</p>
|
<ol>
<li><p>I don't think there is a way to customize the Report Manager interface to show the custom schedule because there is a part of it that is managed by SSIS.</p></li>
<li><p>Yes you can remove the Subscription feature for some users. You can do that in SSMS, when connected to your report Server, in the Security | Roles section. The permission that manages the subscription feature is named : "Manage individual subscriptions". By removing it, your end users won't be able to create or update their subscriptions schedules.</p></li>
</ol>
<p>Hope this helps!</p>
| 49,059
|
<p>Within an XSLT document, is it possible to loop over a set of files in the current directory?</p>
<p>I have a situation where I have a directory full of xml files that need some analysis done to generate a report. I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents. </p>
<p>I was thinking along these lines:</p>
<pre><code><xsl:for-each select="{IO Selector Here}">
<xsl:variable select="document(@url)" name="contents" />
<!--More stuff here-->
</xsl:for-each>
</code></pre>
|
<p>In XSLT 2.0, and with Saxon, you can do this with the <code>collection()</code> function:</p>
<pre><code><xsl:for-each select="file:///path/to/directory">
<!-- process the documents -->
</xsl:for-each>
</code></pre>
<p>See <a href="http://www.saxonica.com/documentation/sourcedocs/collections.html" rel="noreferrer" title="Saxonica: XSLT and XQuery Processing: Collections">http://www.saxonica.com/documentation/sourcedocs/collections.html</a> for more details.</p>
<p>In XSLT 1.0, you have to create an index that lists the documents you want to process with a separate tool. Your environment may provide such a tool; for example, Cocoon has a <a href="http://cocoon.apache.org/2.1/userdocs/directory-generator.html" rel="noreferrer">Directory Generator</a> that creates such an index. But without knowing what your environment is, it's hard to know what to recommend.</p>
|
<p>I don't think XSL is set up to work that way: it's designed to be used by something else on one or more documents, and the something else would be responsible for finding files to which the XSLT should be applied. </p>
<p>If you had one main document and a fixed set of supporting documents, you could possibly use the <a href="http://www.w3schools.com/xsl/func_document.asp" rel="nofollow noreferrer"><code>document()</code> function</a> to return specific nodes and/or values, but I suspect your case is different. </p>
| 12,812
|
<p>I want to post an xml document to an <strong>asp</strong> page from an <strong>asp.net</strong> page. If I use WebRequest with content/type text/xml the document never gets to the asp page. How can I do this ?</p>
|
<p>Here is a sample without any error handling (do it yourself :) ):</p>
<pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = POST;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using(Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
//read the response
</code></pre>
|
<p>It's absolutely possible. Make sure that you are writing the XML to the RequestStream.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getrequeststream.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getrequeststream.aspx</a></p>
| 23,625
|
<p>One of the frequent causes of memory leaks in .Net are event handlers which are never removed from their source objects. </p>
<p>Will this WCF code cause a memory leak, or will the lambda go out of scope too, allowing both the proxy class and the handler to be GCed?</p>
<pre><code>void AMethod()
{
WCFClient proxy;
proxy = new WCFClient();
proxy.RemoteOperationCompleted += (sender, e) => proxy.Close();
proxy.Open();
proxy.RemoteOperationAsync();
}
</code></pre>
|
<p>Here's my test - note the explicit <code>proxy</code> set to <code>null</code> in the lambda - without it the <code>WeakReference</code> lives and therefore a leak is likely:</p>
<pre><code>public class Proxy
{
private bool _isOpen;
public event EventHandler Complete;
public void Close()
{
_isOpen = false;
}
public void Open()
{
_isOpen = true;
}
public void RemoteOperationAsync()
{
if (!_isOpen)
throw new ApplicationException();
Thread.Sleep(1000);
if (Complete != null)
Complete(this, EventArgs.Empty);
}
}
public static class Program
{
public static void Main()
{
WeakReference wr = null;
{
var proxy = new Proxy();
proxy.Complete += (sender, e) =>
{
proxy.Close();
wr = new WeakReference(proxy);
proxy = null;
};
proxy.Open();
proxy.RemoteOperationAsync();
}
GC.Collect(GC.GetGeneration(wr));
GC.WaitForPendingFinalizers();
Console.WriteLine("[LAMBDA] Is WeakReference alive? " + wr.IsAlive);
}
}
</code></pre>
|
<p>That object will die... it'll be cleaned up.</p>
<p>Don't forget that the lamda isn't doing anything special... it's a compiler trick (so just assume it's a normal += SomeDelegate).</p>
<p>Also, the "Close" method (I don't know why they didn't make it IDisposable) will clean up everything else that was left open.</p>
| 34,099
|
<p>I'm new to SQL Server Reporting Services, and was wondering the best way to do the following:</p>
<blockquote>
<ul>
<li>Query to get a list of popular IDs</li>
<li>Subquery on each item to get properties from another table</li>
</ul>
</blockquote>
<p>Ideally, the final report columns would look like this:</p>
<pre><code>[ID] [property1] [property2] [SELECT COUNT(*)
FROM AnotherTable
WHERE ForeignID=ID]
</code></pre>
<p>There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help.</p>
|
<p>I would recommend using a <a href="http://msdn.microsoft.com/en-us/library/ms160348.aspx" rel="nofollow noreferrer">SubReport</a>. You would place the SubReport in a table cell.</p>
|
<p>Simplest method is this:</p>
<pre><code>select *,
(select count(*) from tbl2 t2 where t2.tbl1ID = t1.tbl1ID) as cnt
from tbl1 t1
</code></pre>
<p>here is a workable version (using table variables):</p>
<pre><code>declare @tbl1 table
(
tbl1ID int,
prop1 varchar(1),
prop2 varchar(2)
)
declare @tbl2 table
(
tbl2ID int,
tbl1ID int
)
select *,
(select count(*) from @tbl2 t2 where t2.tbl1ID = t1.tbl1ID) as cnt
from @tbl1 t1
</code></pre>
<p>Obviously this is just a raw example - standard rules apply like don't select *, etc ...</p>
<hr>
<p><strong>UPDATE from Aug 21 '08 at 21:27:</strong><br>
@AlexCuse - Yes, totally agree on the performance.</p>
<p>I started to write it with the outer join, but then saw in his sample output the count and thought that was what he wanted, and the count would not return correctly if the tables are outer joined. Not to mention that joins can cause your records to be multiplied (1 entry from tbl1 that matches 2 entries in tbl2 = 2 returns) which can be unintended.</p>
<p>So I guess it really boils down to the specifics on what your query needs to return.</p>
<hr>
<p><strong>UPDATE from Aug 21 '08 at 22:07:</strong><br>
To answer the other parts of your question - is a VB function the way to go? No. Absolutely not. Not for something this simple.</p>
<p>Functions are very bad on performance, each row in the return set executes the function.</p>
<p>If you want to "compartmentalize" the different parts of the query you have to approach it more like a stored procedure. Build a temp table, do part of the query and insert the results into the table, then do any further queries you need and update the original temp table (or insert into more temp tables).</p>
| 4,125
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.