input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
How to simulate memory allocation errors <p>My C application uses 3rd libraries, which do their own memory management.
In order to be robust, my application has code to deal with failures of library functions due to lack of free memory.</p>
<p>I would like to test this code, and for this, I need to simulate failures due to lack of memory.</p>
<p>What tool/s are recommended for this?
My environment is Linux/gcc.</p>
|
<p>You can use <code>ulimit</code> to limit the amount of resources a user can use, including memory. So you create a test user, limit their memory use to something just enough to launch your program, and watch it die :)</p>
<p>Example:</p>
<pre><code>ulimit -m 64
</code></pre>
<p>Sets a memory limit of 64kb.</p>
|
Is there a .NET OS abstraction layer to make OS calls work cross-platform? <p>I really want to write .NET apps that run on any platform (PC, Linux and Mac). I am not really concerned about UI capabilities because these are mostly background services. I have heard of MONO and that it allows you to write .NET apps that run on Mac and Linux, but I want to be able to write a single app that when compiled for Windows will run as a Service, and when compiled for Linux will run as whatever the UNIX equivalent is. I also would like to be able to store things in the registry and have that work. Is there any way to write truly OS agnostic code like this? ...and DON'T say I should make it run on the web! :)</p>
|
<p>Yes, Mono has the windows service stuff ported to Linux, but you are going to have to think of a better way to store configuration settings than Registry... Using XML files for instance would be cross platform.</p>
<p>You should also check out mono's wiki on how to develop portable applications <a href="http://www.mono-project.com/Guidelines:Application_Portability" rel="nofollow">here</a>.</p>
|
PHP GD, imagecreatefromstring( ); how to get the image dimensions? <p>Normally I use <code>imagecreatefromjpeg()</code> and then <code>getimagesize()</code>, but with Firefox 3 I need to go round this different. So now im using <code>imagecreatefromstring()</code>, but how do I retreive the image dimensions now?</p>
|
<p><code>imagesx()</code> and <code>imagesy()</code> functions seem to work with images made with <code>imagecreatefromstring()</code>, too.</p>
|
What is the best online book service for software development references? <p>I'm a member of ACM, and I have limited access to both Books 24x7 and Safari Books Online, however if I was interested in moving up to a full account for greater access to other books what online book service would you recommend?</p>
|
<p><a href="http://www.safaribooksonline.com/whysafari/try-safari.php" rel="nofollow">Safari Books Online</a> has a corporate subscription service which companies appreciate.</p>
|
In ASP.NET how you get the physcial file path when HttpContext.Current is NULL? <p>I'm working with DotNetNuke's scheduler to schedule tasks and I'm looking to get the physical file path of a email template that I created. The problem is that HttpContext is NULL because the scheduled task is on a different thread and there is not http request. How would you go about getting the file's physical path?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath.aspx">System.Web.Hosting.HostingEnvironment.MapPath</a> is what you're looking for. Whenever you're using the Server or HttpContext.Current objects, check first to see if <a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.aspx">HostingEnvironment</a> has what you need.</p>
|
Caching paginated results, purging on update - how to solve? <p>I've created a forum, and we're implementing an apc and memcache caching solution to save the database some work.</p>
<p>I started implementing the cache layer with keys like "Categories::getAll", and if I had user-specific data, I'd append the keys with stuff like the user ID, so you'd get <code>"User::getFavoriteThreads|1471"</code>. When a user added a new favorite thread, I'd delete the cache key, and it would recreate the entry.</p>
<p><strong>However, and here comes the problem:</strong></p>
<p>I wanted to cache the threads in a forum. Simple enough, "Forum::getThreads|$iForumId". But... With pagination, I'd have to split this into several cache entries, for example</p>
<pre><code>"Forum::getThreads|$iForumId|$iLimit|$iOffset".
</code></pre>
<p>Which is alright, until someone posts a new thread in the forum. I will now have to delete all the keys under <code>"Forum::getThreads|$iForumId"</code>, no matter what the limit and offset is.</p>
<p>What would be a good way of solving this problem? I'd really rather not loop through every possible limit and offset until I find something that doesn't match anymore.</p>
<p>Thanks.</p>
|
<p>Just an update:
I decided that Josh's point on data usage was a very good one.
People are unlikely to keep viewing page 50 of a forum.</p>
<p>Based on this model, I decided to cache the 90 latest threads in each forum. In the fetching function I check the limit and offset to see if the specified slice of threads is within cache or not. If it is within the cache limit, I use array_slice() to retrieve the right part and return it.</p>
<p>This way, I can use a single cache key per forum, and it takes very little effort to clear/update the cache :-)</p>
<p>I'd also like to point out that in other more resource heavy queries, I went with flungabunga's model, storing the relations between keys. Unfortunately Stack Overflow won't let me accept two answers. </p>
<p>Thanks!</p>
|
Rails and Gmail SMTP, how to use a custom from address <p>I've got my Rails (2.1) app setup to send email via Gmail, however whenever I send an email no matter what I set the from address to in my ActionMailer the emails always come as if sent from my Gmail email address. Is this a security restriction they've put in place at Gmail to stop spammers using their SMTP?</p>
<p>Note: I've tried both of the following methods within my ActionMailer (just in case):</p>
<pre><code>@from = me@mydomain.com
from 'me@mydomain.com'
</code></pre>
|
<p>I believe it's just something Gmail does when mail is sent through its SMTP, as it was mentioned that they do this on a tutorial about using their SMTP to send mail.</p>
|
How do I access cookies within Flash? <p>I'm looking to grab cookie values for the same domain within a Flash movie. Is this possible?</p>
<p>Let's see I let a user set a variable foo and I store it using any web programming language. I can access it easily via that language, but I would like to access it via the Flash movie without passing it in via printing it within the HTML page.</p>
|
<p>If you just want to store and retrieve data, you probably want to use the SharedObject class. See <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html">Adobe's SharedObject reference</a> for more details of that.</p>
<p>If you want to access the HTTP cookies, you'll need to use ExternalInterface to talk to javascript. The way we do that here is to have a helper class called HTTPCookies.</p>
<p>HTTPCookies.as:</p>
<pre><code>import flash.external.ExternalInterface;
public class HTTPCookies
{
public static function getCookie(key:String):*
{
return ExternalInterface.call("getCookie", key);
}
public static function setCookie(key:String, val:*):void
{
ExternalInterface.call("setCookie", key, val);
}
}
</code></pre>
<p>You need to make sure you enable javascript using the 'allowScriptAccess' parameter in your flash object.</p>
<p>Then you need to create a pair of javascript functions, getCookie and setCookie, as follows (with thanks to <a href="http://www.quirksmode.org/js/cookies.html">quirksmode.org</a>)</p>
<p>HTTPCookies.js:</p>
<pre><code>function getCookie(key)
{
var cookieValue = null;
if (key)
{
var cookieSearch = key + "=";
if (document.cookie)
{
var cookieArray = document.cookie.split(";");
for (var i = 0; i < cookieArray.length; i++)
{
var cookieString = cookieArray[i];
// skip past leading spaces
while (cookieString.charAt(0) == ' ')
{
cookieString = cookieString.substr(1);
}
// extract the actual value
if (cookieString.indexOf(cookieSearch) == 0)
{
cookieValue = cookieString.substr(cookieSearch.length);
}
}
}
}
return cookieValue;
}
function setCookie(key, val)
{
if (key)
{
var date = new Date();
if (val != null)
{
// expires in one year
date.setTime(date.getTime() + (365*24*60*60*1000));
document.cookie = key + "=" + val + "; expires=" + date.toGMTString();
}
else
{
// expires yesterday
date.setTime(date.getTime() - (24*60*60*1000));
document.cookie = key + "=; expires=" + date.toGMTString();
}
}
}
</code></pre>
<p>Once you have HTTPCookies.as in your flash project, and HTTPCookies.js loaded from your web page, you should be able to call getCookie and setCookie from within your flash movie to get or set HTTP cookies.</p>
<p>This will only work for very simple values - strings or numbers - but for anything more complicated you really should be using SharedObject.</p>
|
What are the bigger hurdles to overcome migrating from Winforms to WPF? <p>I've been developing Winforms applications in C# for a few years now and have been interested in moving future development toward WPF, mainly because of the positive things I've been hearing about it. But, I'm wondering what sort of hurdles others have had to overcome as they migrated to WPF. Was there a significant hit to your productivity or any particular issues which you found challenging?</p>
|
<p>I'm not sure I can give you just one hurdle, because it is a complete departure from WinForms. My suggestion is get Adam Nathan's WPF Unleashed, forget everything you know about building UI's with any previous technology (Winforms, MFC, Java) and begin again at square one. </p>
<p>If you try and do it any other way it will cause utter frustration.</p>
<p>ETA: the reason I say to just start from scratch is because sometimes it's easier to learn new concepts if you go in with a clean slate. In the past, I've discovered that I can be my own worst enemy when it comes to learning something new if I try to carry knowledge from technology to technology (e.g. thinking that doing asmx web services for years precludes me from reading the first couple chapters of a WCF book).</p>
|
likely()/unlikely() macros in the Linux kernel - how do they work? What's their benefit? <p>I've been digging through some parts of the Linux kernel, and found calls like this:</p>
<pre><code>if (unlikely(fd < 0))
{
/* Do something */
}
</code></pre>
<p>or</p>
<pre><code>if (likely(!err))
{
/* Do something */
}
</code></pre>
<p>I've found the definition of them:</p>
<pre><code>#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
</code></pre>
<p>I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course).</p>
|
<p>They are an instruction to the compiler to emit instructions that will cause branch prediction to favour the "likely" side of a jump instruction. This can be a big win, if the prediction is correct it means that the jump instruction is basically free and will take zero cycles. On the other hand if the prediction is wrong, then it means the processor pipeline needs to be flushed and it can cost several cycles. So long as the prediction is correct most of the time, this will tend to be good for performance.</p>
<p>Like all such performance optimisations you should only do it after extensive profiling to ensure the code really is in a bottleneck, and probably given the micro nature, that it is being run in a tight loop. Generally the Linux developers are pretty experienced so I would imagine they would have done that. They don't really care too much about portability as they only target gcc, and they have a very close idea of the assembly they want it to generate.</p>
|
Use of the Exception class in c# <p>Errors that occur deep down in a data access layer or even higher up, (say within ADO.net operations for example) rarely make much sense to an end user. Simply bubbling these errors up to a UI and displaying them will usually achieve nothing except frustration for an end user.</p>
<p>I have recently employed a basic technique for reporting errors such as this whereby I catch the error and at least add some user friendly text so that at least the end user understands what failed.</p>
<p>To do this I am catching an exception within each specific function (say for example a fetch function in a data access layer), then raising a new error with user friendly text about the function that has failed and probably cause, but then embedding the original exception in the new exception as the "inner exception" of that new exception. </p>
<p>This can then occur at each layer if necessary, each consumer of the lower level function adding it's own context to the error message, so that what reaches the UI is an increasingly user friendly error message.</p>
<p>Once the error reaches the UI - if necessary - it can then iterate through the nested exceptions in order to display an error message that firstly tells the user which operation failed, but also provides a bit of technical information about what actually went wrong.</p>
<p>e.g. </p>
<blockquote>
<p>"The list of customer names your
requested could not be displayed."</p>
<p>"Obtaining the list of customers
you requested failed due to an error with the database."</p>
<p>"There was an error connecting to the
database when retrieving a list of
customers"</p>
<p>"Login failed for user xx"</p>
</blockquote>
<p>My question is this: Is this horribly inefficient (all those nested exceptions)? I suspect it is not best practice so what should I be doing to achieve the same thing - or should I in fact be trying to achieve something better?</p>
|
<p>It is just slightly horrible.</p>
<p>If you are showing an error to the end user, the user is supposed to be able to act about it. In "The list of customer names your requested could not be displayed." case, your user will just think "so what?" On all of these cases, just display a "something bad happened" message. You do not even need to catch these exceptions, when something goes bad, let some global method (like application_error) handle it and display a generic message. When you or your user can do something about the error, catch it and do the thing or notify the user.</p>
<p>But you will want to log every error that you do not handle.</p>
<p>By the way, displaying information about the errors occuring may yield to security vulnerabilities. The less the attackers know about your system, the less likely they will find ways to hack it (remember those messages like "Syntax error in sql statement: Select * From Users Where username='a'; drp database;--'..." expected: 'drop' instead of 'drp'. They do not make sites like these anymore).</p>
|
Database Choice for a C# 2008 front end <p>I was wondering what and why you would choose to be able to make a database that can support no more than 100 users with no more than 10 using it at once with a Visual Studio 2008 C# Windows Form front end to access it by. I have to access the database over a network connection, not just on the local machine. I also need to define where the database is found at run-time in the code as opposed to the "Data Source" view in Visual Studio. If my question needs reframing or is not understood, let me know and I will adjust. Part of my problem is I am not sure even how to ask the right question, much less what the answer is.</p>
|
<p>If it is not for comercial purposes you can try SQL Server 2008 Express. It can integrate nicely with Visual Studio 2008 for development and has support for LINQ, Entity Data Model and ADO.NET Entity Framework to make it easy to create next generation data-enabled applications.</p>
<p><a href="http://www.microsoft.com/express/sql/default.aspx" rel="nofollow">http://www.microsoft.com/express/sql/default.aspx</a></p>
<p>You can also store your connections strings in the application configuration file and retrieve them programatically for setting up the database connection.</p>
<p><a href="http://www.codeguru.com/columns/DotNet/article.php/c7987/" rel="nofollow">http://www.codeguru.com/columns/DotNet/article.php/c7987/</a></p>
|
Not getting emails from ExceptionNotifier <p>I followed this <a href="http://svn.rubyonrails.org/rails/plugins/exception_notification/README" rel="nofollow">tutorial</a> on configuring the Rails plugin ExceptionNotifier.</p>
<p>I know that I have ActionMailer configured correctly because I am getting mail from other forms. I even have local_addresses.clear set so that it should be delivering mail no matter what.</p>
<p>I am using Apache with a mongrel_cluster running in the backend.</p>
<p>What am I missing?</p>
|
<p>You're using the SVN version of the plugin, which is probably unmaintained. <a href="http://github.com/rails/exception_notification/tree/master" rel="nofollow">Latest version can be found here</a>.</p>
<p>Second thing which you can do is check the production log. Mailings get written to the log, so you'll see if Rails ever even <em>tried</em> to send it. If there are no entries, that means things are silently failing, which probably happens because -- for some reason -- exceptions are not caught properly.</p>
|
Is there a Perl solution for lazy lists this side of Perl 6? <p>Has anybody found a good solution for lazily-evaluated lists in Perl? I've tried a number of ways to turn something like </p>
<pre><code>for my $item ( map { ... } @list ) {
}
</code></pre>
<p>into a lazy evaluation--by tie-ing @list, for example. I'm trying to avoid breaking down and writing a source filter to do it, because they mess with your ability to debug the code. Has anybody had any success. Or do you just have to break down and use a while loop? </p>
<p><strong>Note:</strong> I guess that I should mention that I'm kind of hooked on sometimes long grep-map chains for functionally transforming lists. So it's not so much the foreach loop or the while loop. It's that map expressions tend to pack more functionality into the same vertical space. </p>
|
<p>As mentioned previously, for(each) is an eager loop, so it wants to evaluate the entire list before starting.</p>
<p>For simplicity, I would recommend using an iterator object or closure rather than trying to have a lazily evaluated array. While you <em>can</em> use a tie to have a lazily evaluated infinite list, you can run into troubles if you ever ask (directly or indirectly, as in the foreach above) for the entire list (or even the size of the entire list).</p>
<p>Without writing a full class or using any modules, you can make a simple iterator factory just by using closures:</p>
<pre><code>sub make_iterator {
my ($value, $max, $step) = @_;
return sub {
return if $value > $max; # Return undef when we overflow max.
my $current = $value;
$value += $step; # Increment value for next call.
return $current; # Return current iterator value.
};
}
</code></pre>
<p>And then to use it:</p>
<pre><code># All the even numbers between 0 - 100.
my $evens = make_iterator(0, 100, 2);
while (defined( my $x = $evens->() ) ) {
print "$x\n";
}
</code></pre>
<p>There's also the <a href="http://search.cpan.org/perldoc?Tie::Array::Lazy" rel="nofollow">Tie::Array::Lazy</a> module on the CPAN, which provides a much richer and fuller interface to lazy arrays. I've not used the module myself, so your mileage may vary.</p>
<p>All the best,</p>
<p>Paul</p>
|
Filtering duplicate newsgroup posts from Google <p>I have the constant need to Google error messages to try to find out what they mean and what solutions people might have. Usually those error messages were posted in some newsgroup. Unfortunately, Google's results (even when it says "similar results removed") usually consist of many copies of the exact same message (usually with some non-answer) replicated among many different newsgroup archives. Even just Google Groups results will be there three or four times, counting different localizations of Google Groups. How do you sort through huge piles of the exact same newsgroup posts?</p>
|
<p>Try using a google custom search like Dan Appleman's <a href="http://www.searchdotnet.com/" rel="nofollow">SearchDotNet</a> first. That will eliminate a lot of duplicates.</p>
|
How should I organize my ASP.Net themes and common CSS files <p>I am currently working on a project where a programmer who fancied themselves a graphic designer attempted their hand at ASP.Net themes. The CSS is pretty bad, but that is another question altogether.</p>
<p>What I really need help with is the best way to organize ASP.Net Themes and the CSS that lies within them. Imagine that there is a directory structure that looks something like this:</p>
<ul>
<li>Themes
<ul>
<li>Theme A
<ul>
<li>StyleA.css</li>
<li><em>Common.css</em></li>
</ul></li>
<li>Theme B
<ul>
<li>StyleB.css</li>
<li><em>Common.css</em></li>
</ul></li>
<li>Theme C
<ul>
<li>StyleC.css</li>
<li><em>Common.css</em></li>
</ul></li>
</ul></li>
</ul>
<p>Each theme has a common stylesheet in it. Unfortunately the author of those style sheets managed to change only a few things here and there in each copy of <em>Common.css</em>. Eventually I will evaluate whether or not those changes are even necessary, but some major cleanup needs to happen first. For now just assume that the changes, ever so small, are necessary for things to look right with each theme.</p>
<p>I would like to know what the best practices are for using themes while also needing some common styles across your application. I want to minimize the number of AppTurns in the page load, but I really want to consolidate common styles into one place in a way that maintains the ease of themes.</p>
|
<p>You should just include the standard/common css in the website and include it in the head of the masterpage instead of placing it in themes.</p>
|
VisualStudio using BootCamp/VMWare on OS X <p>Just bought a 2.4GHz Intel Core 2 Duo iMac with 2GB of memory and a 320GB hard drive. I plan on doing some .net development on it using a BootCamp/VMWare combo since VMWare grants access to the bootcamp partition.</p>
<p>What is a recommended size for a BootCamp partition and how much memory should I give VMWare? Any pitfalls to watch out for? What is your current configuration?</p>
|
<p>I use VMWare Fusion 2.0 on my MacBook Pro and I wouldn't have it any other way.</p>
<p>I'd strongly recommend getting a min of 4gb RAM is you're going to run Windows + VS 2008 in virtualisation.</p>
<p>I have a 2gb RAM for my VM and you do notice a bit of chugging, particularly when you are compiling a large solution, or when running lots of apps at once.</p>
<p>I strongly recommend VMWare over Parallels as VMWare supports 2 virtual CPU's (I think it's up to 4 virtual CPU's in v2).</p>
<p>I'd recommend around a 30gb disk for your VM and I don't recommend BootCamp unless you want to play games on it.
Why? It's a lot easier to have a really large virtual disk which is not using it all where as BootCamp will take the space. Also a complete virtual disk is easier to backup/ snapshot/ restore.</p>
|
How many unit tests should I write per function/method? <p>Do you write one test per function/method, with multiple checks in the test, or a test for each check?</p>
|
<p>One test per check and super descriptive names, per instance:</p>
<pre><code>@Test
public void userCannotVoteDownWhenScoreIsLessThanOneHundred() {
...
}
</code></pre>
<p>Both only one assertion and using good names gives me a better report when a test fails. They scream to me: "You broke THAT rule!".</p>
|
USRP2: Number of A/D Converters <p>Why are there two A/D converters on the USRP2 board if you can only use one RX
daughtercard?</p>
|
<p>Most of the daughterboards do quadrature downconversion and produce
analog I & Q. For those daughterboards we use 1 A/D for I and another
one for Q.</p>
|
Report generation <p>I am writing a web app using TurboGears, and in that app the users must be able to generate different reports.
The data the reports need is stored in a database (MySQL).
The reports must be returned either as a easily printable html document, or a pdf file.</p>
<p>I have previously used jasper and iReport for creating the documents, but if I can avoid having to fire up Java to create the report I would be happy.</p>
<p>Ideally I would like to specify reports in a easily readable markup language and then just feed the template data with some kind of library that produces the report.</p>
<p>I gladly accept any kind of hints on how I should go about generating these reports!</p>
|
<p><a href="http://appyframework.org/pod.html" rel="nofollow">Pod</a> is my favorite solution to your problem.</p>
|
Changing Hostname / IP Address of Windows System Mounted as an Image <p>I'm looking for a way to change the hostname and IP address of a Windows XP system that is mounted via a loop-back image on a Linux system. So basically I have access to the Windows XP system on a file level, but I cannot execute any programs on it. A way similar to editing the /etc/hostname and whatever network configuration file under Linux.</p>
<p>The only ways I've found so far would include running a tool after boot, e.g. MS sysprep or use a solution like Acronis Snap Deploy.</p>
|
<p>You can use <a href="http://home.eunet.no/~pnordahl/ntpasswd/" rel="nofollow"><code>chntpw</code></a> tool to edit Windows registry offline. Here's an example of <a href="http://home.eunet.no/~pnordahl/ntpasswd/regedit.txt" rel="nofollow">how to use it</a>.</p>
<p>The keys you're looking for are these:</p>
<pre><code>HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\ComputerName\ComputerName
HKEY_LOCAL_MACHINE\SYSTEM\Current Control Set\
Services\Tcpip\Parameters\Interfaces\{<Interface GUID>}
</code></pre>
<p>Under your interface's GUID you'll find many keys, the ones you need are:</p>
<pre><code>IPAddress (REG_MULTI_SZ) = x.x.x.x
SubnetMask (REG_MULTI_SZ) = x.x.x.x
DefaultGateway (REG_MULTI_SZ) = x.x.x.x
</code></pre>
<p>Do take a look at the rest of they keys in there, you might find some interesting information.</p>
|
interval rails caching <p>I need to cache a single page. I've used ActionController's caches_page for this. But now, I'd like to expire AND regenerate it once in every 10 minutes. What are my options?</p>
<p>later: I'd like to not use any external tools for this, like cron. The important point is <strong>interval-based</strong> expiry of the cache. </p>
|
<p>You can also use <a href="http://code.google.com/p/timedcachedfragment/" rel="nofollow">this</a> if you want to have fragments timeout.</p>
|
Developing MS Word add-in <p>Anyone knows of a good tool for developing add-ins for Word in .net?
Hopefully something that supports both office 2003 and 2007.</p>
<p>Thanks.</p>
|
<p>There are lots of options for development tools for Office. The most obvious one is of course Office itself. It has rich support for macros and VBA. You could also use SharePoint to extend document sharing and management functionality. But if your add-in is more complex than can be handled inside of Office, I suggest you use <a href="http://msdn.microsoft.com/en-us/vs2008/default.aspx">Visual Studio 2008</a> or the <a href="http://msdn.microsoft.com/en-us/office/aa905543.aspx">Tools For Office</a> add-on for Visual Studio 2005.</p>
<p>One thing to keep in mind is that Office is mostly a collection of COM objects. So while tools like Visual Studio, with its deep support of the .NET Framework and Office classes make it very simple to develop solutions for Office applications, with some time, energy, and a high tolerance for pain, you could develop an Office add-in with Notepad.</p>
<p>Microsoft has a very nice resource site for Office developers <a href="http://msdn.microsoft.com/en-us/office/default.aspx">here</a>.</p>
|
How does nunit work? <p>Can someone explain me how it works, starting from when you select to run a test</p>
|
<p>When you select to run a test, </p>
<ul>
<li>it will create an instance of the parent class of that test method. </li>
<li>It then proceeds to run the method marked with TestFixtureSetup attribute if one exists (once for the the test class).</li>
<li>Next is the method marked with the Setup attribute is called if one exists (once before every test in that class)</li>
<li>Next your selected method (with the Test attribute) is executed. All assertions are checked. If all assertions are valid, the test is marked as Pass (Green in the GUI) else Fail (Red). If any exceptions pop up that were not specified with the ExpectedException attribute, test fails.</li>
<li>Then the method marked with the Teardown attribute is called if one exists. (Cleanup code.. called once after every test in the class)</li>
<li>Finally method marked with TestFixtureTeardown attribute is executed. (once after all tests in the test class)</li>
</ul>
<p>That's it in a nutshell. The power of xUnit is its simplicity. Is that what you were looking for ?</p>
|
What are some ADFS alternatives for doing single sign on for an ASP.NET app with users in active directory? <p>Needs to be secure and able to handle thousands of users.</p>
|
<p>Check out ADAM and AzMan.</p>
<p>ADAM is Active Directory Application Mode. There is a how-to guide at: <a href="http://msdn.microsoft.com/en-us/library/ms998331.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms998331.aspx</a></p>
<p>AzMan is Authorization Manager. There is a how-to guide at: <a href="http://msdn.microsoft.com/en-us/library/ms998336.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms998336.aspx</a></p>
|
Should domain objects and simple JavaBeans be unit tested? <p>Should simple JavaBeans that have only simple getters and setters be unit tested?? </p>
<p>What about Beans with some logic in getters and setters?</p>
|
<p>You should not write tests which:</p>
<ul>
<li>Test the language or the IDE (i.e. automatically generated getters and setters)</li>
<li>Add no value to your test harness and kill your enthusiasm for Unit Testing</li>
</ul>
<p>The same applies for .NET objects which only have properties (sometimes called 'Info' objects). </p>
<p>In an ideal world you would have 100% test coverage, but in practice this is not going to happen. So spend the client's money where it will add the most benefit i.e. writing tests for classes with complex state and behaviour.</p>
<p>If your JavaBean becomes more interesting you can of course add a test case later. One of the common problems associated with Unit Testing / TDD is the mistaken belief that everything has to be perfect first time.</p>
|
How to configure asp.net process to run under a domain account? <p>I would like to configure asp.net process to run under an account with domain credentials.
My requirement is to access some files on a network share.</p>
<p>What are the steps for this? Is there any built-in account I can use?</p>
|
<p>Check this article from MSDN.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms998297.aspx">How To: Create a Service Account for an ASP.NET 2.0 Application</a></p>
<p>*This How To shows you how to create and configure a custom least-privileged service account to run an ASP.NET Web application. By default, an ASP.NET application on Microsoft Windows Server 2003 and IIS 6.0 runs using the built-in Network Service account. In production environments, you usually run your application using a custom service account. By using a custom service account, you can audit and authorize your application separately from others, and your application is protected from any changes made to the privileges or permissions associated with the Network Service account. To use a custom service account, you must configure the account by running the Aspnet_regiis.exe utility with the -ga switch, and then configure your application to run in a custom application pool that uses the custom account's identity.*</p>
|
How can I detect, using php, if the machine has oracle (oci8 and/or pdo_oci) installed? <p>How can I detect, using php, if the machine has oracle <code>(oci8 and/or pdo_oci)</code> installed?</p>
<p>I'm working on a <code>PHP</code> project where some developers, such as myself, have it installed, but there's little need for the themers to have it. How can I write a quick function to use in the code so that my themers are able to work on the look of the site without having it crash on them?</p>
|
<p>if the oci extension isn't installed, then you'll get a fatal error with farside.myopenid.com's answer, you can use function_exists('oci_connect') or extension_loaded('oci8') (or whatever the extension's actually called)</p>
|
.Net 8-bit Encoding <p>I'm working on serial port, transmitting and receiving data to some hardware at 8bit data. I would like to store it as string to facilitate comparison, and preset data are stored as string or hex format in xml file. I found out that only when using Encoding.Default which is ANSI encoding then the 8bit data is converted properly and easily reversible. ASCII encoding will only works for 7bit data, and UTF8 or UTF7 doesn't works well too, since I'm using some character from 1-255. Encoding.Default would be just fine, but I read on MSDN that it's dependent on OS codepage setting, which means it might behave differently on different codepage configured. I use GetBytes() and GetString extensively using the Encoding, but would like a failsafe and portable method that works all the time at any configuration. Any idea or better suggestion for this?</p>
|
<p>Latin-1 aka ISO-8859-1 aka codepage 28591 is a useful codepage for this scenario, as it maps values in the range 128-255 unchanged. The following are interchangeable:</p>
<pre><code>Encoding.GetEncoding(28591)
Encoding.GetEncoding("Latin1")
Encoding.GetEncoding("iso-8859-1")
</code></pre>
<p>The following code illustrates the fact that for Latin1, unlike Encoding.Default, all characters in the range 0-255 are mapped unchanged:</p>
<pre><code>static void Main(string[] args)
{
Console.WriteLine("Test Default Encoding returned {0}", TestEncoding(Encoding.Default));
Console.WriteLine("Test Latin1 Encoding returned {0}", TestEncoding(Encoding.GetEncoding("Latin1")));
Console.ReadLine();
return;
}
private static bool CompareBytes(char[] chars, byte[] bytes)
{
bool result = true;
if (chars.Length != bytes.Length)
{
Console.WriteLine("Length mismatch {0} bytes and {1} chars" + bytes.Length, chars.Length);
return false;
}
for (int i = 0; i < chars.Length; i++)
{
int charValue = (int)chars[i];
if (charValue != (int)bytes[i])
{
Console.WriteLine("Byte at index {0} value {1:X4} does not match char {2:X4}", i, (int) bytes[i], charValue);
result = false;
}
}
return result;
}
private static bool TestEncoding(Encoding encoding)
{
byte[] inputBytes = new byte[256];
for (int i = 0; i < 256; i++)
{
inputBytes[i] = (byte) i;
}
char[] outputChars = encoding.GetChars(inputBytes);
Console.WriteLine("Comparing input bytes and output chars");
if (!CompareBytes(outputChars, inputBytes)) return false;
byte[] outputBytes = encoding.GetBytes(outputChars);
Console.WriteLine("Comparing output bytes and output chars");
if (!CompareBytes(outputChars, outputBytes)) return false;
return true;
}
</code></pre>
|
Using the Window API, how do I ensure controls retain a native appearance? <p>Some of the controls I've created seem to default to the old Windows 95 theme, how do I prevent this? Here's an example of a button that does not retain the Operating System's native appearance (I'm using Vista as my development environment):</p>
<pre><code>HWND button = CreateWindowEx(NULL, L"BUTTON", L"OK", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
170, 340, 80, 25, hwnd, NULL, GetModuleHandle(NULL), NULL);
</code></pre>
<p>I'm using native C++ with the Windows API, no managed code.</p>
|
<p>To add a manifest to the application you need create a MyApp.manifest file and add it to the application resource file:</p>
<pre><code>//-- This define is normally part of the SDK but define it if this
//-- is an older version of the SDK.
#ifndef RT_MANIFEST
#define RT_MANIFEST 24
#endif
//-- Add the MyApp XP Manifest file
CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "MyApp.manifest"
</code></pre>
<p>With newer versions of <em>Visual Studio</em> there is a <em>Manifest Tool</em> tab found in the project settings and the <em>Additional Manifest Files</em> field found on this tab can also be used to define the manifest file.</p>
<p>Here is a simple MyApp.manifest file for a Win32 application:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
version="1.0.0.1"
processorArchitecture="X86"
name="Microsoft.Windows.MyApp"
type="win32"
/>
<description>MyApp</description>
</assembly>
</code></pre>
<p>If you application depends on the other dlls these details can also be added to the manifest and Windows will use this information to make sure your application always uses the correct versions of these dependent dlls.</p>
<p>For example here are the manifest dependency details for the common control and version 8.0 C runtime libraries:</p>
<pre><code><dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.VC80.CRT"
version="8.0.50608.0"
processorArchitecture="x86"
publicKeyToken="1fc8b3b9a1e18e3b" />
</dependentAssembly>
</code></pre>
|
6502 CPU Emulation <p>It's the weekend, so I relax from spending all week programming by writing a hobby project.</p>
<p>I wrote the framework of a MOS 6502 CPU emulator yesterday, the registers, stack, memory and all the opcodes are implemented. (Link to source below)</p>
<p>I can manually run a series of operations in the debugger I wrote, but I'd like to load a NES rom and just point the program counter at its instructions, I figured that this would be the fastest way to find flawed opcodes.</p>
<p>I wrote a quick NES rom loader and loaded the ROM banks into the CPU memory.</p>
<p>The problem is that I don't know how the opcodes are encoded. I know that the opcodes themselves follow a pattern of one byte per opcode that uniquely identifies the opcode, </p>
<pre><code>0 - BRK
1 - ORA (D,X)
2 - COP b
</code></pre>
<p>etc</p>
<p>However I'm not sure where I'm supposed to find the opcode argument. Is it the the byte directly following? In absolute memory, I suppose it might not be a byte but a short. </p>
<p>Is anyone familiar with this CPU's memory model?</p>
<p>EDIT: I realize that this is probably shot in the dark, but I was hoping there were some oldschool Apple and Commodore hackers lurking here.</p>
<p><strong>EDIT:</strong> Thanks for your help everyone. After I implemented the proper changes to align each operation the CPU can load and run Mario Brothers. It doesn't do anything but loop waiting for Start, but its a good sign :)</p>
<p>I uploaded the source:</p>
<p><a href="http://www.codeplex.com/Cpu6502/SourceControl/DirectoryView.aspx?SourcePath=&changeSetId=1810" rel="nofollow">http://www.codeplex.com/Cpu6502/SourceControl/DirectoryView.aspx?SourcePath=&changeSetId=1810</a></p>
<p>If anyone has ever wondered how an emulator works, its pretty easy to follow. Not optimized in the least, but then again, I'm emulating a CPU that runs at 2mhz on a 2.4ghz machine :)</p>
|
<p>The opcode takes one byte, and the operands are in the following bytes. Check out the byte size column <a href="http://www.atariarchives.org/2bml/chapter_10.php">here</a>, for instance.</p>
|
source control with VB2005 Express <p>Can anyone suggest a good source control system that interfaces with VB2005 Express? As the Express editions of Visual Studio do not allow add-ins does this mean that I will not be able to integrate source control into the IDE? I'm used to the check-in/check-out process of SourceSafe integrated into VB6. Can anyone recommend TortoiseSVN as an alternative?</p>
|
<p>TortoiseSVN is a good choice. Although it won't integrate into the IDE (because of the plug-in problem you mentioned), it's really solid in the Explorer right-button menu.</p>
<p>Also consider <a href="http://www.sourcegear.com/vault/" rel="nofollow">Vault</a> from SourceGear. If you're used to SourceSafe, Vault will be easier to learn; Vault was specifically designed for ex-SourceSafe users.</p>
|
How to enable inno-db support on MySql 5 installed above MySql 4? <p>How to enable inno-db support on installed instance of MySql?</p>
<p>I have installed mysql-5.0.67-win32.
'InnoDB' is 'DISABLED' when executing 'show engines'.
According to documentation MySql is compiled with support of inno-db
(From doc: A value of DISABLED occurs either because the server was started with an option that disables the engine, or because not all options required to enable it were given.)</p>
<p>In my.ini I commented line with 'skip-innodb'. This didn't help.
All other inno-db related variables remain unchanged.</p>
<p>I have performed some unusual action before I experienced described situation.
I have mysql-4.0.17-win installed. I uninstall it and after this installed mysql-5.0.67-win32.
In installation wizard I chose MyISAM support only (as far as I understand I disabled inno-db support in such way. When I tried to reinstall with support of inno-db I had problems of using my previous database 'mysql' with account information).</p>
<p>MySQL documentation says that I should use mysqldump to export data and after this to import exported data in process of upgrade. I tried to do so, but when importing data I obtained message about syntax error (I think that it is connected with some incompatibilities of 4-th and 5-th version of mysql)</p>
|
<p>Should be enabled by default. There are some situations where wrong permissions on the MySQL lib folder cause InnoDB to bark. Check your MySQL error log for permission errors.</p>
|
php.ini & SMTP= - how do you pass username & password <p><code>My ISP</code> account requires that I send a username & password for outbound <code>SMTP</code> mail. </p>
<p>How do I get <code>PHP</code> to use this when executing <code>php.mail()?</code> The <code>php.ini</code> file only contains entries for the server <code>(SMTP= )</code> and <code>From: (sendmail_from= )</code>.</p>
|
<p>PHP <code>mail()</code> command does not support authentication. Your options:</p>
<ol>
<li><a href="http://sourceforge.net/projects/phpmailer">PHPMailer</a>- <a href="http://phpmailer.codeworxtech.com/index.php?pg=tutorial#2">Tutorial</a></li>
<li><a href="http://pear.php.net/package/Mail">PEAR</a> - <a href="http://email.about.com/od/emailprogrammingtips/qt/et073006.htm">Tutorial</a></li>
<li>Custom functions - See various solutions in the notes section: <a href="http://php.net/manual/en/ref.mail.php">http://php.net/manual/en/ref.mail.php</a></li>
</ol>
|
Is static metaprogramming possible in Java? <p>I am a fan of <a href="http://stackoverflow.com/questions/112277/best-intro-to-c-static-metaprogramming">static metaprogramming in C++</a>. I know Java now has generics. Does this mean that static metaprogramming (i.e., compile-time program execution) is possible in Java? If so, can anyone recommend any good resources where one can learn more about it?</p>
|
<p>No, this is not possible. Generics are not as powerful as templates. For instance, a template argument can be a user-defined type, a primitive type, or a value; but a generic template argument can only be <code>Object</code> or a subtype thereof.</p>
<p>Edit: This is an old answer; since 2011 we have Java 7, which has <a href="http://stackoverflow.com/a/8387752/409102">Annotations that can be used for such trickery</a>.</p>
|
Javascript error <p>I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!</p>
<pre><code> <SCRIPT language=JavaScript>
<!--
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("\/_layouts\/images\/icon1.gif");
newImage("\/_layouts\/images\/icon2.gif");
// -->
</SCRIPT>
</code></pre>
<p>The error I am getting is when clicking on a drop down context menu on a page, for this line:</p>
<pre><code>newImage("\/_layouts\/images\/icon1.gif");
</code></pre>
<p>Error: The object doesn't accept this property or method
Code: 0</p>
<p>I really don't see what could happen... Any tips on what may be happening here?<br>
Thanks a lot!</p>
|
<p>Have you tried loading your scripts into a JS debugger such as <a href="http://www.aptana.com/" rel="nofollow">Aptana</a> or Firefox plugin like <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow">Firebug</a>?</p>
|
Is it possible to have one appBase served by multiple context paths in Tomcat? <p>Is it possible to have one appBase served up by multiple context paths in Tomcat?</p>
<p>I have an application base that recently replaced a second application base. My problem is a number of users still access the old context. I would like to serve the, now common, application from a single appBase yet accessed via either context. I took a swing at the low lying fruit and used a symbolic link in the 'webapps' directory... pointing the old context path at the new context path; it works, but feels "cheezy." And I don't like that a database connection pool is created for both contexts ( I would like to minimize the resources for connecting to the database ). </p>
<p>Anyway, if anyone knows of the "proper" way to do this I will greatly appreciate it. I'm using Tomcat 6.0.16 - no apache front end ( I suppose URL rewrite would be nice ).</p>
|
<p>I'm not sure if the answer above will prevent your webapp from loading twice (as you'd have to deploy it to both new and old context paths), but I could be mistaken. Another option would be to have an extremely simple webapp left in the old context, that does nothing except have one custom servlet filter declared in the web.xml that re-writes all requests to the new path (essentially simulating apache's rewrite rule behaviour). You'd have to write the filter class yourself but it would be quite trivial.</p>
|
How do I join two tables in a third n..n (hasAndBelongsToMany) relationship in CakePHP? <p>I have a <code>n...n</code> structure for two tables, <strong><code>makes</code></strong> and <strong><code>models</code></strong>. So far no problem.</p>
<p>In a third table (<strong><code>products</code></strong>) like:</p>
<pre><code>id
make_id
model_id
...
</code></pre>
<p>My problem is creating a view for products of one specifi <strong><code>make</code></strong> inside my <code>ProductsController</code> containing just that's make models:</p>
<p>I thought this could work:</p>
<pre><code>var $uses = array('Make', 'Model');
$this->Make->id = 5; // My Make
$this->Make->find(); // Returns only the make I want with it's Models (HABTM)
$this->Model->find('list'); // Returns ALL models
$this->Make->Model->find('list'); // Returns ALL models
</code></pre>
<p>So, If I want to use the <code>list</code> to pass to my view to create radio buttons I will have to do a <code>foreach()</code> in my <strong><code>make</code></strong> array to find all models titles and create a new array and send to the view via <code>$this->set()</code>.</p>
<pre><code>$makeArray = $this->Make->find();
foreach ($makeArray['Model'] as $model) {
$modelList[] = $model['title'];
}
$this->set('models', $models)
</code></pre>
<p>Is there any easier way to get that list without stressing the <strong><code>make</code></strong> Array. It will be a commom task to develops such scenarios in my application(s).</p>
<p>Thanks in advance for any hint!</p>
|
<p>Here's my hint: Try getting your query written in regular SQL before trying to reconstruct using the Cake library. In essence you're doing a lot of extra work that the DB can do for you.
Your approach (just for show - not good SQL):</p>
<pre><code>SELECT * FROM makes, models, products WHERE make_id = 5
</code></pre>
<p>You're not taking into consideration the relationships (unless Cake auto-magically understands the relationships of the tables)</p>
<p>You're probably looking for something that joins these things together:</p>
<pre><code>SELECT models.title FROM models
INNER JOIN products
ON products.model_id = models.model_id
AND products.make_id = 5
</code></pre>
<p>Hopefully this is a nudge in the right direction?</p>
|
How do you re-attach a subversion local copy to a different remote? <p>Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository?</p>
|
<p>Example:</p>
<pre><code>svn switch --relocate \
http://svn.example.com/path/to/repository/path/within/repository \
http://svnnew.example.com/new/repository/path/within/repository
</code></pre>
<p>One thing which is to remember, lets assume you checked out the project "path/within/repository" then you have to go to the <strong>root of your working copy</strong>, and execute the above command. it is <strong>NOT</strong> enough just to use the repository root (as in <em>svn switch --relocate <a href="http://svn.example.com/path/to/repository/">http://svn.example.com/path/to/repository/</a> http://svnnew.example.com/new/repository/</em>), because that wouldn't work.</p>
|
Conflicting desires in Database Design, with fields of two similar functions <p>Okay, so I'm making a table right now for "Box Items".</p>
<p>Now, a Box Item, depending on what it's being used for/the status of the item, may end up being related to a "Shipping" box or a "Returns" box.</p>
<p>A Box Item may be defective:if it is, a flag will be set in the Box Item's row (IsDefective), and the Box Item will be put in a "Returns" box (with other items to be returned to that vendor). Otherwise, the Box Item will eventually be put into a "Shipping" box (with other items to be shipped). (Note that Shipping and Returns boxes have their own tables: there's not one common table for all boxes... though maybe I should consider doing that if possible as a third possibility?)</p>
<p>Maybe I'm just not thinking clearly today, but I started questioning what should be done in this situation.</p>
<p>My gut tells me that I should have a separate field for each possible relation, even if only one of the relations can happen at any given time, which would make the schema for Box Items look like:</p>
<p>BoxItemID
Description
IsDefective
ShippingBoxID
ReturnBoxID
etc...</p>
<p>This would make the relations clear, but it seems wasteful (since only one of the relations will be used at any time). So then I thought I could have just one field for the BoxID, and determine which BoxID it's referring to (a Shipping or a Returns Box ID) based on the IsDefective field:</p>
<p>BoxItemID
Description
IsDefective
BoxID
etc...</p>
<p>This seems less wasteful, but doesn't sit right with me. The relation isn't obvious.</p>
<p>So, I put it to you, database gurus of Stackoverflow. What would you do in this situation?</p>
<p>EDIT: Thank you everyone for your input! It's given me a lot to think about. For one, I'm going to use an ORM next time I start a project like this. =) For two, since I'm not right now, I'll bite the four bytes and use two fields.</p>
<p>Thanks everyone again!</p>
|
<p>I'm with Psychotic Venom and mattlant.</p>
<p>Going the polymorphic route (having to figure out which table your foreign key points to based on the contents of another field) is going to be a pain. Coding the constraints for that maybe tough (I'm not sure most databases would support that natively, I think you'd have to use a trigger).</p>
<p>Do items ever move between the tables? Sticking with two tables with identical definitions where one is for returns and one is for shipping may be the easiest route. If you want to stick with the definition you first proposed (with the two separate fields) is perfectly reasonable. </p>
<p>"Premature optimization is the root of all evil" and all that. While it seems wasteful, remember what you're storing. Since they are IDs they are probably just integers, maybe 4 bytes. Wasting four bytes per record is basically nothing. In fact, due to padding to put things on even addresses or other such things it may be "free" to put that extra field in there. It all depends on the DB design.</p>
<p>Unless you have a very good reason to go the polymorphic route (like you're on an embedded system with little memory or you have to replicate across some really slow 9600bps link) it probably won't be worth the headaches you can end up with. Having to write all those special cases into your queries can get annoying.</p>
<p>Quick example: doing a join between two tables where if you want to join is based on if the isDefective flag is set is going to be a pain. Being able to just use one of the two columns alone is probably enough of a hassle you may save, at least for me.</p>
|
Calling a ASP Page thru it Class <p>Like in Windows Forms:</p>
<p>Dim myForm as New AForm(Constr-arg1, Constr-arg2)</p>
<p>myForm.Show</p>
<p>... is there a similar way to Load a Page in ASP.Net. I would like to overload the Page Constructor and instantiate the correct Page Contructor depending on the situation.</p>
|
<p>Can you just link to the page passing parameters in the QueryString (after the ? in the URL) and then use them in the constructor (more likely PageLoad)</p>
|
What are the statistics of HTML vs. Text email usage <p>What the latest figures are on people viewing their emails in text only mode vs. HTML?</p>
<p><a href="http://en.wikipedia.org/wiki/Html_email" rel="nofollow">Wikipedia</a> and it's <a href="http://www.emaillabs.com/tools/email-marketing-statistics.html" rel="nofollow">source</a> both seem to reference <a href="http://www.dmnews.com/Outlook-2006-More-Technology-More-Targeting/article/90305/" rel="nofollow">this</a> research from 2006 which is an eternity ago in internet terms.</p>
<p>An issue with combining both HTML and text based emails is taking a disproportionate amount of time to resolve given the likely number of users it is affecting.</p>
|
<p>As with web browser usage statistics, it depends entirely on the audience.</p>
<p>I have access to a bit of data on this subject and it seems that text-only email use is very low (for non-technical audiences, at least). <0.1% up to ~6% depending on demographic.</p>
<p>It's not <em>that</em> much effort to do both (especially if you can find something to help you do the heavy lifting when creating multipart MIME containers), and you can always write a script to generate text from your HTML or something.</p>
|
Python - When to use file vs open <p>What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)</p>
|
<p>You should always use <code>open()</code>.</p>
<p>As the <a href="http://docs.python.org/2/library/functions.html#file" rel="nofollow" title="BuiltinFuncs Doc">documentation</a> states:</p>
<blockquote>
<p>When opening a file, it's preferable
to use open() instead of invoking this
constructor directly. file is more
suited to type testing (for example,
writing "isinstance(f, file)").</p>
</blockquote>
<p>Also, <code>file()</code> <a href="http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins" rel="nofollow">has been removed</a> since Python 3.0.</p>
|
Dynamic IP-based blacklisting <p>Folks, we all know that IP blacklisting doesn't work - spammers can come in through a proxy, plus, legitimate users might get affected... That said, blacklisting seems to me to be an efficient mechanism to stop a persistent attacker, given that the actual list of IP's is determined dynamically, based on application's feedback and user behavior. </p>
<p>For example:
- someone trying to brute-force your login screen
- a poorly written bot issues very strange HTTP requests to your site
- a script-kiddie uses a scanner to look for vulnerabilities in your app</p>
<p>I'm wondering if the following mechanism would work, and if so, do you know if there are any tools that do it: </p>
<ul>
<li>In a web application, developer has a hook to report an "offense". An offense can be minor (invalid password) and it would take dozens of such offenses to get blacklisted; or it can be major, and a couple of such offenses in a 24-hour period kicks you out. </li>
<li>Some form of a web-server-level block kicks in on before every page is loaded, and determines if the user comes from a "bad" IP. </li>
<li>There's a "forgiveness" mechanism built-in: offenses no longer count against an IP after a while.</li>
</ul>
<p>Thanks!</p>
<p><b>Extra note: it'd be awesome if the solution worked in PHP, but I'd love to hear your thoughts about the approach in general, for any language/platform</b></p>
|
<p>Take a look at <a href="http://www.fail2ban.org/">fail2ban</a>. A python framework that allows you to raise IP tables blocks from tailing log files for patterns of errant behaviour.</p>
|
What is the cost of using a pointer to member function vs. a switch? <p>I have the following situation:</p>
<pre><code>
class A
{
public:
A(int whichFoo);
int foo1();
int foo2();
int foo3();
int callFoo(); // cals one of the foo's depending on the value of whichFoo
};
</code></pre>
<p>In my current implementation I save the value of <code>whichFoo</code> in a data member in the constructor and use a <code>switch</code> in <code>callFoo()</code> to decide which of the foo's to call. Alternatively, I can use a <code>switch</code> in the constructor to save a pointer to the right <code>fooN()</code> to be called in <code>callFoo()</code>. </p>
<p>My question is which way is more efficient if an object of class A is only constructed once, while <code>callFoo()</code> is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a <code>switch</code>?</p>
<p>Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it. </p>
<p>Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :) </p>
|
<p>How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference?</p>
<p>In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually <em>measure</em> the different choices. You may be surprised!</p>
<p>More info: There is an excellent article <a href="http://www.codeproject.com/KB/cpp/FastDelegate.aspx" rel="nofollow">Member Function Pointers and the Fastest Possible C++ Delegates</a> which goes into very deep detail about the implementation of member function pointers.</p>
|
What are the Python equivalents of the sighold and sigrelse functions found in C? <p>It appears the Python signal module doesn't have anything similar to the sighold and sigrelse functions found in C, using signal.h. Are there Python equivalents of <em>any</em> sort?</p>
<p>Many thanks!</p>
|
<p>There is no way to ``block'' signals temporarily from critical sections (since this is not supported by all Unix flavors).</p>
<p><a href="https://docs.python.org/library/signal.html" rel="nofollow">https://docs.python.org/library/signal.html</a></p>
|
Displaying code in blog posts <p>What libraries and/or packages have you used to create blog posts with code blocks? Having a JavaScript library that would support line numbers and indentation is ideal.</p>
|
<p>The <a href="http://qbnz.com/highlighter/" rel="nofollow">GeSHi text highlighter</a> is pretty awesome. If you're using WordPress, <a href="http://wordpress.org/extend/plugins/wp-syntax/" rel="nofollow">there's a plugin</a> for you already</p>
|
Which CSS tag creates a box like this with title? <p>I want to create a box like this with title:</p>
<p><img src="https://i.stack.imgur.com/2rip1.gif" alt="CSS box with title"></p>
<p>Can any one please let me know if there is a default CSS tag to do this? Or do I need to create my custom style?</p>
|
<p>I believe you are looking for the <code>fieldset</code> HTML tag, which you can then style with CSS. E.g.,</p>
<pre><code><fieldset style="border: 1px black solid">
<legend style="border: 1px black solid;
margin-left: 1em; padding: 0.2em 0.8em ">title</legend>
Text within the box <br />
Etc
</fieldset>
</code></pre>
|
How do I run a script when ip-address changes (most likely using a dhclient hook) on a (Ubuntu) Linux machine? <p>I have a script which contacts a few sources and tell them "the IP-address XXX.XXX.XXX.XXX is my current one". My test web server has a dynamic IP-address through DHCP and amongst other things it needs to update a DDNS entry when its IP-address changes. However it's not the only thing it does, so I will need to run my own custom script.</p>
<p>I suspect that this is possible by a attaching the script to be run for a given dhclient hook. However I still need to know which hook I should use, and how.</p>
|
<p>I would recommend to put the script into dhclient-exit-hooks.d. Because you should just change the DDNS entry, if the address change has been finished. However, I am not sure if dhclient-exit-hooks are called, if assigning an address fails. </p>
<p>Edit: The man pages (man dhclient-script) says, that the exit-hooks script will get the exit code in a shell variable (exit_status). So you could check it. </p>
|
How do I cancel a text selection after the initial mousedown event? <p>I'm trying to implement a pop-up menu based on a click-and-hold, positioned so that a (really) slow click will still trigger the default action, and with the delay set so that a text-selection gesture won't usually trigger the menu. </p>
<p>What I can't seem to do is cancel the text-selection in a way that doesn't prevent text-selection in the first place: returning false from the event handler (or calling <code>$(this).preventDefault()</code>) prevents the user from selecting at all, and the obvious <code>$().trigger('mouseup')</code> doesn't doesn't do anything with the selection at all.</p>
<ul>
<li>This is in the general context of a page, not particular to a textarea or other text field.</li>
<li><code>e.stopPropogation()</code> doesn't cancel text-selection.</li>
<li>I'm not looking to <em>prevent</em> text selections, but rather to <em>veto</em> them after some short period of time, if certain conditions are met.</li>
</ul>
|
<p>Try this:</p>
<pre><code>var input = document.getElementById('myInputField');
if (input) {
input.onmousedown = function(e) {
if (!e) e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
}
</code></pre>
<p>And if not, have a read of:</p>
<p><a href="http://www.quirksmode.org/js/introevents.html">http://www.quirksmode.org/js/introevents.html</a></p>
|
Javascript curry - what are the practical applications? <p>I don't think I've grokked currying yet. I understand what it does, and how to do it. I just can't think of a situation I would use it.</p>
<p>Where are you using currying in javascript (or where are the main libraries using it)? DOM manipulation or general application development examples welcome.</p>
<p>EDIT: <a href="http://stackoverflow.com/questions/113780/javascript-curry-what-are-the-practical-applications#113799">One of the answers</a> mentions animation. Functions like "slideUp", "fadeIn" take an element as an arguments and are normally a curried function returning the high order function with the default "animation function" built-in. Why is that better than just applying the higher-up function with some defaults?</p>
<p>Oh and are there any drawbacks to using it?</p>
<p>Cheers.</p>
<p>EDIT: As requested here are some good resources on javascript currying:</p>
<ul>
<li><a href="http://www.dustindiaz.com/javascript-curry/">http://www.dustindiaz.com/javascript-curry/</a></li>
<li>Crockford, Douglas (2008) <em>Javascript: The Good Parts</em></li>
<li><a href="http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html">http://www.svendtofte.com/code/curried_javascript/</a>
(Takes a detour into ML so skip the whole section from "A crash course in ML" and start again at "How to write curried JavaScript")</li>
<li><a href="http://blog.morrisjohns.com/javascript_closures_for_dummies">http://blog.morrisjohns.com/javascript_closures_for_dummies</a></li>
<li><a href="http://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How do JavaScript closures work?</a></li>
<li><strong><a href="http://ejohn.org/blog/partial-functions-in-javascript/">http://ejohn.org/blog/partial-functions-in-javascript</a> (Mr. Resig on the money as per usual)</strong></li>
<li><a href="http://benalman.com/news/2010/09/partial-application-in-javascript/">http://benalman.com/news/2010/09/partial-application-in-javascript/</a></li>
</ul>
<p>I'll add more as they crop up in the comments.</p>
<hr>
<p>EDIT:</p>
<p>Thanks for the answers.</p>
<p>So currying and partial application in general are convenience techniques.</p>
<p>If you are frequently "refining" a high-level function by calling it with same configuration, you can curry (or use Resig's partial) the higher-level function to create simple, concise helper methods.</p>
<p>Cheers!</p>
|
<p>Here's an <a href="http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/" rel="nofollow"><strong>interesting AND practical use of currying in JavaScript that uses closures</strong></a>:</p>
<blockquote>
<pre><code>function converter(toUnit, factor, offset, input) {
offset = offset || 0;
return [((offset+input)*factor).toFixed(2), toUnit].join(" ");
}
var milesToKm = converter.curry('km',1.60936,undefined);
var poundsToKg = converter.curry('kg',0.45460,undefined);
var farenheitToCelsius = converter.curry('degrees C',0.5556, -32);
milesToKm(10); // returns "16.09 km"
poundsToKg(2.5); // returns "1.14 kg"
farenheitToCelsius(98); // returns "36.67 degrees C"
</code></pre>
</blockquote>
|
Performance penalty for working with interfaces in C++? <p>Is there a runtime performance penalty when using interfaces (abstract base classes) in C++?</p>
|
<p>Short Answer: No.</p>
<p>Long Answer:
It is not the base class or the number of ancestors a class has in its hierarchy that affects it speed. The only thing is the cost of a method call.</p>
<p>A non virtual method call has a cost (but can be inlined)<br>
A virtual method call has a slightly higher cost as you need to look up the method to call before you call it (but this is a simple table look up <b>not</b> a search). Since all methods on an interface are virtual by definition there is this cost.</p>
<p>Unless you are writing some hyper speed sensitive application this should not be a problem. The extra clarity that you will recieve from using an interface usually makes up for any perceived speed decrease.</p>
|
How to check if an OLEDB driver is installed on the system? <p>How can I make sure that a certain OLEDB driver is installed when I start my application? I use ADO from Delphi and would like to display a descriptive error message if the driver is missing. The error that's returned from ADO isn't always that user-friendly.</p>
<p>There are probably a nice little function that returns all installed drivers but I haven't found it.</p>
|
<p>This is an old question but I had the same problem now and maybe this can help others.</p>
<p>In Delphi 7 there is an procedure in ADODB that return a TStringList with the provider names.</p>
<p>Usage example:</p>
<pre><code>names := TStringList.Create;
ADODB.GetProviderNames(names);
if names.IndexOf('SQLNCLI10')<>-1 then
st := 'Provider=SQLNCLI10;'
else if names.IndexOf('SQLNCLI')<>-1 then
st := 'Provider=SQLNCLI;'
else if names.IndexOf('SQLOLEDB')<>-1 then
st := 'Provider=SQLOLEDB;';
</code></pre>
|
Get Performance Counter Instance Name (w3wp#XX) from ASP.NET worker process ID <p>I would like to display some memory statistics (working set, GCs etc.) on a web page using the .NET/Process performance counters. Unfortunately, if there are multiple application pools on that server, they are differentiated using an index (#1, #2 etc.) but I don't know how to match a process ID (which I have) to that #xx index. Is there a programmatic way (from an ASP.NET web page)?</p>
|
<p>The first hit on Google:</p>
<p><a href="http://openrent.blogspot.com/2008/01/multiple-clr-performance-counters.html">Multiple CLR performance counters appear that have names that resemble "W3wp#1"</a></p>
<blockquote>
<p>When multiple ASP.NET worker processes
are running, Common Language Runtime
(CLR) performance counters will have
names that resemble "W3wp#1" or
"W3sp#2"and so on. This was remedied
in .NET Framework 2.0 to include a
counter named Process ID in the .NET
CLR Memory performance object. This
counter displays the process ID for an
instance. You can use this counter to
determine the CLR performance counter
that is associated with a process.</p>
</blockquote>
<p>Also <a href="http://support.microsoft.com/kb/281884">KB 281884</a>:</p>
<blockquote>
<p>By default, Performance Monitor
(Perfmon.msc) displays multiple
processes that have the same name by
enumerating the processes in the
following way:</p>
<p>Process#1 Process#2 Process#3</p>
<p>Performance Monitor can also display
these processes by appending the
process ID (PID) to the name in the
following way:</p>
<p>Process_PID</p>
</blockquote>
|
Create anonymous object by Reflection in C# <p>Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically.</p>
<p><em>edited later to clarify the use case</em></p>
<p>An extra constraint is that I will be running all of it inside a Silverlight app, so extra runtimes are not an option, and not sure how generating code on the fly will work.</p>
|
<p>Yes, there is.
From memory:</p>
<pre><code>public static T create<T>(T t)
{
return Activator.CreateInstance<T>();
}
object anon = create(existingAnonymousType);
</code></pre>
|
Pointer vs. Reference <p>What would be better practice when giving a function the original variable to work with:</p>
<pre><code>unsigned long x = 4;
void func1(unsigned long& val) {
val = 5;
}
func1(x);
</code></pre>
<p>or:</p>
<pre><code>void func2(unsigned long* val) {
*val = 5;
}
func2(&x);
</code></pre>
<p>IOW: Is there any reason to pick one over another?</p>
|
<p>My rule of thumb is:</p>
<p>Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.</p>
<p>Use references otherwise.</p>
|
How can I share a variable value between classic asp, .NET and javascript? <p>I've created an <code>IHttpHandler</code> in .NET C# which returns pieces of html to a classic asp page.</p>
<p>The classic asp page communicates with the <code>IHttpHandler</code> through basic http requests using <code>ServerXMLHTTP</code> in vbscript or Ajax Calls in JavaScript.</p>
<p>Now, I need a way to share a variable which I have in vbscript but not in javascript with the .NET application.</p>
<p>The first bit, sharing a variable between classic asp and .net is not a problem as I can just add it onto the http request. Because the variable is not available in javascript however I can't do this in that case.</p>
<p>I had the idea that I could maybe cache the variable in the .NET application and use the cached version for javascript calls. But for this to work I would need a way to uniquely identify the "client" in .NET...</p>
<p>I tried to add <code>System.Web.SessionState.IRequiresSessionState</code> to my HttpHandler and use the SessionId but this didn't work because every single call to the HttpHandler seems to get a new ID.</p>
<p>Am I thinking the right way? What are my options here?</p>
|
<p>You could put your value in a cookie, then you could read with javascript and do anything with it, including sending it in a request to the .net app...</p>
|
Creating Custom GnuCash Reports with Scheme <p>Are there any resources which show how to create custom GnuCash reports? I don't know the intricacies of Scheme but I do know the basics of Lisp, based on tinkering with Emacs. Is there a site which lays out the API for GnuCash reports, ideally with a little explanation of Scheme as well?</p>
|
<p>It appears that their wiki has some information <a href="http://wiki.gnucash.org/wiki/Custom_Reports">here</a>.</p>
|
Simple web "live chat" software (LAMP stack) that integrates with Jabber/Aim <p>I've looked for this a few times in the past, to no avail. I would like a simple <code>php/ajax</code> web chat interface, that, and this is the critical part, will interface with my <code>IM client (Pidgin)</code> ... via Jabber or Aim. <code>Plugoo</code> is almost what I want, except it is hosted, and flash based. Flash-based would be OK if not ideal, but hosted isn't. </p>
<p>Note that I don't just need notifications, but I want a user of the website who clicks "live chat" to get a chat interface and my IM client allows me to interact with them. </p>
<p>This is super handy for those of us that want to provide live support to clients who do not use IM. </p>
|
<p>(Disclaimer: I work for <a href="http://www.jabber.com/" rel="nofollow">Jabber, Inc.</a>, the commercial company behind the product I'm about to pimp.)</p>
<p><img src="http://www.jabber.com/images/GroupChatAJAXThumb.png" alt="JabberWerx AJAX" title="" /></p>
<p>The <a href="http://www.jabber.com/CE/JabberWerxAJAXLibrary" rel="nofollow">JabberWerx AJAX</a> libraries do exactly what you want. You include a reference to a Javascript library, add a div tag where you want the chat to go, and add a couple lines of configuration javascript to hook the two together. There's also a one-to-one mode. User accounts can be created on the fly if you like, as well.</p>
<p>Sorry for the ad, but I think it's exactly what you want.</p>
|
Is a Python dictionary an example of a hash table? <p>One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?</p>
|
<p>Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, <a href="http://mail.python.org/pipermail/python-list/2000-March/048085.html">here</a>.</p>
<p>That's why you can't use something 'not hashable' as a dict key, like a list:</p>
<pre><code>>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
</code></pre>
<p>You can <a href="http://en.wikipedia.org/wiki/Hash_table">read more about hash tables</a> or <a href="https://hg.python.org/cpython/file/10eea15880db/Objects/dictobject.c">check how it has been implemented in python</a> and <a href="https://hg.python.org/cpython/file/10eea15880db/Objects/dictnotes.txt">why it is implemented that way</a>.</p>
|
What is the best way to pack JavaScript code without getting perfomance flaws? <p>I am searching for a way to compress JavaScript code for the iPhone. Is there a way to avoid using a lot of CPU time on the small and rather slow device?</p>
|
<p>Use the <a href="http://www.julienlecomte.net/yuicompressor/" rel="nofollow">YUI Compressor</a></p>
|
How to pass an array parameter in TOAD <p>Using toad and an oracle database, how can I call a sp and see the results by passing an array to one of the parameters of the sp?</p>
|
<p>In the Editor tab you can call it like this:</p>
<pre><code>begin
myproc (my_array_type(1,4,7,9));
end;
</code></pre>
|
How do you verify the Work and Experience level of Consultants? <p>So, right now I am hunting for consultants for two technologies I have knowledge about but no experience in. I have put ads on Craigslist as these are two small tasks and most likely the larger firms wont want to be bothered and will charge an arm and a leg. </p>
<p>How do I verify that these guys are on the up and up? That the work they are sending me is THEIRS? I mean, I'd love to believe that the guy that didn't sign his email did all the flash work for Guess.com and is trolling Craigslist for gigs, I just don't think it's likely. </p>
<p>I also don't have much time for this, so anything I can do will have to be fast (thus the reason I am hiring consultants). </p>
<p><strong>UPDATE</strong></p>
<p>The problem is, this is a small company, and I AM the IT department. I mean, I know enough about Flash to ask some high level questions, but not much. The other thing is a Mac product called File Maker Pro, which I know relatively nothing about. </p>
<p>The point of this is to save me time so I don't have to learn the technologies and do it. Are there reputable firms that handle small things like this? I suppose that may have been a better question. </p>
<p>Thank you. </p>
|
<p>Well, you get what you pay for, and using Craigslist for high-level technology hires might not be the best way to find the cream of the crop.</p>
<p>The most telling tool that I have for weeding out the liars and posers is a good, grueling phone-screen. If you don't know anything about the technology, then you've got a problem. You need someone knowledgeable, who you trust, to kick the tires on these guys.</p>
<p>You could always ask them for their Stack Overflow reputation score.</p>
<p>;)</p>
|
How can I trigger Core Animation on an animator proxy during a call to resizeSubviewsWithOldSize? <p>I have some NSViews that I'm putting in one of two layouts depending on the size of my window.</p>
<p>I'm adjusting the layout when the relevant superview receives the resizeSubviewsWithOldSize method.</p>
<p>This works, but I'd like to animate the change. So naturally I tried calling the animator proxy when I set the new frames, but the animation won't run while the user is still dragging. If I release the mouse before the animation is scheduled to be done I can see the tail end of the animation, but nothing until then. I tried making sure kCATransactionDisableActions was set to NO, but that didn't help.</p>
<p>Is it possible to start a new animation and actually have it run during the resize?</p>
|
<p>I don't think you can do this easily because CA's animations are run via a timer and the timer won't fire during the runloop modes that are active while the user is dragging.</p>
<p>If you can control the runloop as the user is dragging, play around with the runloop modes. That'll make it work. I don't think you can change it on the CA side.</p>
|
MVC Preview 5 - Rendering A View To String For Testing <p>I was reading a post by Brad Wilson (<a href="http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html">http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html</a>) on the new ViewEngine changes to MVC Preview 5 and thought that it would be great to be able to render a view to string for use in tests. I get the impression from the article that it may be possible to achieve this but cannot figure out how. </p>
<p>I believe this would enable us to do away with some of our WatIn tests (which are slow and unreliable) as it would allow us to check that the View has rendered correctly by simply checking the string for expected values/text.</p>
<p>Has anyone implemented something like this?</p>
|
<p>It's tricky. What you have to do is set the Response.Filter property to a custom stream class that you implement. The MVC Contrib project actually has examples of doing this. I'd poke around in there.</p>
|
How to check whether a file is valid UTF-8? <p>I'm processing some data files that are supposed to be valid UTF-8 but aren't, which causes the parser (not under my control) to fail. I'd like to add a stage of pre-validating the data for UTF-8 well-formedness, but I've not yet found a utility to help do this.</p>
<p>There's a <a href="http://www.w3.org/2005/01/yacker/uploads/utf8-validator" rel="nofollow">web service</a> at W3C which appears to be dead, and I've found a Windows-only validation <a href="http://bolek.techno.cz/UTF8-Validator/" rel="nofollow">tool</a> that reports invalid UTF-8 files but doesn't report which lines/characters to fix.</p>
<p>I'd be happy with either a tool I can drop in and use (ideally cross-platform), or a ruby/perl script I can make part of my data loading process. </p>
|
<p>You can use GNU iconv:</p>
<pre><code>$ iconv -f UTF-8 your_file -o /dev/null
</code></pre>
<p>iconv will return 0 if the file could be converted successfully, and 1 if not. Additionally, it will print out the byte offset where the invalid byte sequence occurred.</p>
<p><strong>Edit</strong>: The output encoding doesn't have to be specified, it will be assumed to be UTF-8.</p>
|
Flex profiler gives "Socket timeout " error. Why for? <p>When trying to run the Flex Builder 3 profiler on any I don't get the profiler dialog window and then after a few seconds I get "Socket timeout" in the console window. Any ideas why it can't connect?</p>
<p>I've got the latest debug version of Flash player and have tried shutting off my firewall.<br />
I'm running it on XP from the local drive, ie. not through localhost.</p>
<p>Thanks,
Alex</p>
|
<p>It looks like the browser (Firefox in my case) has to be shutdown before the profiler is started. Step 1. in the livedocs even says this -- wish I had read it earlier. :)</p>
<p><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=profiler_3.html" rel="nofollow">http://livedocs.adobe.com/flex/3/html/help.html?content=profiler_3.html</a></p>
|
How do you specify a port range for Java sockets? <p>In Java you can give the number zero as a single parameter for the Socket or DatagramSocket constructor. Java binds that Socket to a free port then. Is it possible to limit the port lookup to a specific range?</p>
<p>Thanks in advance,<br />
Roland</p>
|
<p>Hrm, after reading the docs, I don't think you can. You can either bind to any port, then rebind if it is not acceptable, or repeatedly bind to a port in your range until you succeed. The second method is going to be most "efficient".</p>
<p>I am uneasy about this answer, because it is... inelegant, yet I really can't find anything else either :/</p>
|
In P4V, how do I create a branch from a label? <p>My company just imported our CVS repository into Perforce. I'm new to P4V and I can't work out how to create a branch from an existing label. Can anyone tell me how to do this?</p>
|
<p>In my copy of P4V (Version 2013.3), I go to the <code>Actions</code> menu and choose <code>Branch Files...</code>, which brings up the <code>Branch Files</code> dialog:</p>
<p><a href="http://i.stack.imgur.com/eAp34.png" rel="nofollow"><img src="http://i.stack.imgur.com/eAp34.png" alt="enter image description here"></a></p>
<p>In that dialog, I specify the source files to branch, and the target name of my branch (in my case I am branching <code>//depot/main/...</code> to <code>//depot/branch/...</code>), and in the <code>Filter</code> tab I specify that I want to specify the source revisions using a label.</p>
<p>And I type my label name into the text box (If I don't know the label name I can <code>Browse...</code> for it).</p>
<p>Then I click the <code>Branch</code> button to make the branch.</p>
|
Is there a way to clear a user's brower of my page, or say not to use cache? <p>Is there a command in classic ASP I can use to tell the browser not to pull the page from it's cache, or, to not cache, or clear the cache of my page?</p>
|
<p>You can use HTML meta tags:</p>
<pre><code><meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="Fri, 01 Jan 1999 1:00:00 GMT" />
<meta http-equiv="Last-Modified" content="0" />
<meta http-equiv="Cache-Control" content="no-cache, must-revalidate" />
</code></pre>
<p>Or you can use ASP response headers:</p>
<pre><code><%
Response.CacheControl = "no-cache"
Response.AddHeader "Pragma", "no-cache"
Response.Expires = -1
%>
</code></pre>
|
In Eclipse, why does "Build Automatically" get mysteriously disabled? <p>I'm running Eclipse Europa (3.3). I leave the "Build Automatically" setting, under the Project menu, on all the time. Once in awhile my code isn't compiling, and I puzzle over it and then pull down the Project menu ... lo and behold, it's not set anymore. What gives? Is this a bug, or is there something else I'm doing that could cause it?</p>
<p>Edit: I am running the regular Java developer installation, plus Subversive and its connectors, Jetty Launcher, and I believe no other plugins. Other people at my workplace have had the same problem.</p>
<p>Edit: I am still having this problem once in a blue moon, only now I'm using Eclipse Galileo (3.5) for Windows. I haven't had this problem in Galileo for OS X, neither in Cocoa nor Carbon, but I have not used that for as long.</p>
|
<p>I don't have eclipse right here to test and make sure but here is an idea.</p>
<p>Is any of the project or even workspace file in SVN ? if they are and they were uploaded with auto build disabled that might explain it</p>
<p>You update and overwrite your settings. This doesn't become apparent until you restart eclipse. this would also explain why other people at your workplace experienc this. it would even explain why some don't : thay are the ones who are careful what they update and don't allow eclipse to overwrite their own settings plus the ones who actually prefer to have autobuild disabled :)</p>
|
What pre-existing services exist for calculating distance between two addresses? <p>I'd like to implement a way to display a list of stored addresses sorted by proximity to a given address.</p>
<p>Addresses in the list will be stored in a database table. Separate parts have separate fields (we have fields for postal code, city name, etc.) so it is not just a giant <code>varchar</code>. These are user-entered and due to the nature of the system may not always be complete (some may be missing postal code and others may have little more than city and state).</p>
<p>Though this is for an intranet application I have no problems using outside resources including accessing internet web services and such. I'd actually prefer that over rolling my own unless it would be trivial to do myself. If Google or Yahoo! already provides a free service, I'm more than willing to check it out. The keyword is it must be free, as I'm not at liberty to introduce any additional cost onto this project for this feature as it is already a bonus "perk" so to speak.</p>
<p>I'm thinking of this much like many brick & mortar shops do their "Find a Location" feature. Showing it in a simple table sorted appropriately and displaying distance (in, say, miles) is great. Showing a map mash-up is even cooler, but I can definitely live with just getting the distance back and me handling all of the subsequent display and sorting.</p>
<p>The problem with simple distance algorithms is the nature of the data. Since all or part of the address can be undefined, I don't have anything convenient like lat/long coords. Also, even if I make postal codes required, 90% of the addresses will probably have the same five postal codes.</p>
<p>While it need not be blisteringly fast, anything that takes more than seven seconds to show up on the page due to latency might be too long for the average user to wait, as we know. If such a hypothetical service supports sending a batch of addresses at once instead of querying one at a time, that'd be great. Still, I should not think the list of addresses would exceed 50 total, if that many.</p>
|
<p><a href="http://code.google.com/apis/maps/documentation/services.html#Geocoding">Google</a> and <a href="http://developer.yahoo.com/maps/rest/V1/geocode.html">Yahoo!</a> both provide geocoding services for free. You can calculate distance using the <a href="http://en.wikipedia.org/wiki/Haversine_formula">Haversine formula</a> (<a href="http://www.codeproject.com/KB/cs/distancebetweenlocations.aspx">implemented in .NET or SQL</a>). Both services will let you do partial searches (zip code only, city only) and will let you know what the precision of their results are (so that you can exclude locations without meaningful information, though Yahoo! provides more precision info than Google).</p>
|
Bad UI Design? Having two logos on the top left of the website? <p>Well i am currently working on a project doing some UI mockups when certain users wanted to have two logo on the top left ot the website.
One is to indicate what is the website about then another is to indicate that this website is actually belong to this particular sector.</p>
<p>I thought that UI design wise this is very bad because two logos on top left. If users go in initially he won't be able to know which logo means what.</p>
<p>What are your opinions regarding this?</p>
|
<p>It does sound rather confusing, though it may depend on the content of the logos as to whether they are difficult to figure out.</p>
<p>I would recommend getting someone who hasn't used the site to see the mockup and see what they think about it (without guidance)... ie some usability testing.</p>
<p>Check out <a href="http://rads.stackoverflow.com/amzn/click/0321344758">Don't Make Me Think by Steve Krug</a>... you will want to do some tests right away after you read that, and he goes into detail about what to do when you get pulled in the wrong direction by people who don't really understand the consequences of the decision.</p>
|
Location of My Pictures <p>How do I programatically (Using C#) find out what the path is of my My Pictures folder? </p>
<p>Does this work on XP and Vista?</p>
|
<p>The following will return a full-path to the location of the users picture folder (Username\My Documents\My Pictures on XP, Username\Pictures on Vista)</p>
<pre><code>Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
</code></pre>
|
How do I kill a process using Vb.NET or C#? <p>I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code. </p>
<p>Does any one have any straight-forward code for killing a process using vb.net or c#?</p>
|
<p>You'll want to use the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx">System.Diagnostics.Process.Kill</a> method. You can obtain the process you want using
<a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx">System.Diagnostics.Proccess.GetProcessesByName</a>.</p>
<p>Examples have already been posted here, but I found that the non-.exe version worked better, so something like:</p>
<pre><code>foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") )
{
try
{
p.Kill();
p.WaitForExit(); // possibly with a timeout
}
catch ( Win32Exception winException )
{
// process was terminating or can't be terminated - deal with it
}
catch ( InvalidOperationException invalidException )
{
// process has already exited - might be able to let this one go
}
}
</code></pre>
<p>You probably don't have to deal with <code>NotSupportedException</code>, which suggests that the process is remote.</p>
|
Using AssemblyInfo to automatically update multiple AssemblyInfo.cs files <p>I've got several AssemblyInfo.cs files as part of many projects in a single solution that I'm building automatically as part of TeamCity.</p>
<p>To make the msbuild script more maintainable I'd like to be able to use the AssemblyInfo community task in conjunction with an ItemGroup e.g.</p>
<pre><code><ItemGroup>
<AllAssemblyInfos Include="..\**\AssemblyInfo.cs" />
</ItemGroup>
<AssemblyInfo AssemblyTitle="" AssemblyProduct="$(Product)" AssemblyCompany="$(Company)" AssemblyCopyright="$(Copyright)"
ComVisible="false" CLSCompliant="false" CodeLanguage="CS" AssemblyDescription="$(Revision)$(BranchName)"
AssemblyVersion="$(FullVersion)" AssemblyFileVersion="$(FullVersion)" OutputFile="@(AllAssemblyInfos)" />
</code></pre>
<p>Which blatently doesn't work because OutputFile cannot be a referenced ItemGroup.</p>
<p>Anyone know how to make this work?</p>
|
<p>We use "linked" files in project.
Solution Explorer -> Add Existin Item -> .. select_file .. -> arrow_on_left_of_add_button -> Add As Link</p>
<p>Then the selected file ( AssemblyInfo.cs for now ) is not copied to the direcotry of project, bud is only linked from specified path.</p>
|
Open an Emacs buffer when a command tries to open an editor in shell-mode <p>I like to use Emacs' shell mode, but it has a few deficiencies. One of those is that it's not smart enough to open a new buffer when a shell command tries to invoke an editor. For example with the environment variable <code>VISUAL</code> set to <code>vim</code> I get the following from <code>svn propedit</code>:</p>
<pre>
$ svn propedit svn:externals .
"svn-prop.tmp" 2L, 149C[1;1H
~ [4;1H~ [5;1H~ [6;1H~ [7;1H~
...
</pre>
<p>(It may be hard to tell from the representation, but it's a horrible, ugly mess.)</p>
<p>With <code>VISUAL</code> set to <code>"emacs -nw"</code>, I get</p>
<pre>
$ svn propedit svn:externals .
emacs: Terminal type "dumb" is not powerful enough to run Emacs.
It lacks the ability to position the cursor.
If that is not the actual type of terminal you have,
use the Bourne shell command `TERM=... export TERM' (C-shell:
`setenv TERM ...') to specify the correct type. It may be necessary
to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.svn: system('emacs -nw svn-prop.tmp') returned 256
</pre>
<p>(It works with <code>VISUAL</code> set to just <code>emacs</code>, but only from inside an Emacs X window, not inside a terminal session.)</p>
<p>Is there a way to get shell mode to do the right thing here and open up a new buffer on behalf of the command line process?</p>
|
<p>You can attach to an Emacs session through <code>emacsclient</code>. First, start the emacs server with </p>
<pre><code>M-x server-start
</code></pre>
<p>or add <code>(server-start)</code> to your <code>.emacs</code>. Then,</p>
<pre><code>export VISUAL=emacsclient
</code></pre>
<p>Edit away.</p>
<p>Note:</p>
<ul>
<li>The versions of <code>emacs</code> and <code>emacsclient</code> must agree. If you have multiple versions of Emacs installed, make sure you invoke the version of <code>emacsclient</code> corresponding to the version of Emacs running the server.</li>
<li>If you start the server in multiple Emacs processes/frames (e.g., because <code>(server-start)</code> is in your <code>.emacs</code>), the buffer will be created in the last frame to start the server.</li>
</ul>
|
MySpace DOM? <p>I've been given the task of doing some work customizing an artist's space in MySpace. It seems that you sort of hack the HTML you want into your edit profile page (which has several empty boxes). The MySpace page, it seems, is already HTML so you can only hack into that. Suggested "tweaks" include incomplete HTML code (e.g., a <code><DIV></code> tag without a <code></DIV></code> tag to supress certain sections) and stylesheet pieces that you can "place anywhere" (meaning somewhere on your edit profile page). And the best one is that sites that offer layouts say, "Layout Code - Copy and Paste the code at the bottom of your 'I'd Like to Meet' Section!"</p>
<p>This cannot possibly be this lame, can it?</p>
<p>Is there any coherent guide to customizing MySpace pages for programmers/HTML designers? Is there a coherent DOM (including things like <code>.contactTable</code> etc.)? Could it be that all the tweaks are just hacks people have figured out from looking at the generated HTML?</p>
<p>Thanks!</p>
|
<p>You hit the nail on the head with your final question. The MySpace DOM is a disgusting set of nearly-infinitely nested tables. Normally, people edit the page by finding those sites that let you "cut and paste" and use their generated CSS since they've already done the hard work for isolating the proper elements.</p>
<p>Good luck... unfortunately, you are <em>really</em> going to need it. =/</p>
|
Hiding Subreports in SQL Report (RDL) <p>I have a bunch a reports that are printed out and mailed to clients. At the top of the report is the return address, left aligned. I was asked to add an optional logo to the report. This logo should be left of the return address. (The logo and all other info is stored in the database). So if the logo exists, you SHOULD see:</p>
<p><someimage> <Return Address></p>
<p>And if no logo exists, you SHOULD see:</p>
<p><Return Address></p>
<p>There are many different logos possible placed in many different reports, so to make life easier, the logo was implemented as a subreport. The subreport just grabs the correct logo image, and then it automatically displays in the report.</p>
<p>The problem I'm having is this. If the log DOES NOT exist, then we want the return address left aligned, as shown above. But what is happening is that while the subreport shows nothing, it still takes up the space where the logo WOULD be, and the return address is floating a few inches to the right of the left side of the page.</p>
<pre><code> <Return Address>
</code></pre>
<p>SO... is there a setting I can use/set to get the subreport to either not show, or not take up any space, if there is no logo to be displayed?</p>
<p>Sorry, hope I made this clear enough. I'm totally new to RDL's.</p>
|
<p>You should be able to set an expression on the subreport's visibility so that it does not show if there isn't a logo.</p>
<p>Here is the XML from an RDL I had handy:</p>
<pre><code><Subreport Name="SubReport">
<ReportName>SubReport</ReportName>
<Visibility>
<Hidden>=Not Parameters!ShowLogo.Value</Hidden>
</Visibility>
</Subreport>
</code></pre>
<p>This tests against a boolean parameter called ShowLogo, but you could just as easily test the value of another parameter (perhaps the length of a URL?).</p>
<p>To be clear, when specifying the expression for the "Hidden" property, you want it to evaluate to False when you want the element to display. If your expression evaluates to True, that means that the element will be hidden.</p>
|
Low Java single process thread limit in Red Hat Linux <p>I'm experiencing an issue on a test machine running Red Hat Linux (kernel version is 2.4.21-37.ELsmp) using Java 1.6 (1.6.0_02 or 1.6.0_04). The problem is, once a certain number of threads are created in a single thread group, the operating system is unwilling or unable to create any more.</p>
<p>This seems to be specific to Java creating threads, as the C thread-limit program was able to create about 1.5k threads. Additionally, this doesn't happen with a Java 1.4 JVM... it can create over 1.4k threads, though they are obviously being handled differently with respect to the OS.</p>
<p>In this case, the number of threads it's cutting off at is a mere 29 threads. This is testable with a simple Java program that just creates threads until it gets an error and then prints the number of threads it created. The error is a <pre>java.lang.OutOfMemoryError: unable to create new native thread</pre></p>
<p>This seems to be unaffected by things such as the number of threads in use by other processes or users or the total amount of memory the system is using at the time. JVM settings like Xms, Xmx, and Xss don't seem to change anything either (which is expected, considering the issue seems to be with native OS thread creation).</p>
<p>The output of "ulimit -a" is as follows:</p>
<pre>
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) 4
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
stack size (kbytes, -s) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 7168
virtual memory (kbytes, -v) unlimited
</pre>
<p>The user process limit does not seem to be the issue. Searching for information on what could be wrong has not turned up much, but <a href="http://blogs.oracle.com/gverma/2008/03/redhat_linux_kernels_and_proce_1.html" rel="nofollow">this post</a> seems to indicate that at least some Red Hat kernels limit a process to 300 MB of memory allocated for stack, and at 10 MB per thread for stack, it seems like the issue could be there (though it seems strange and unlikely as well).</p>
<p>I've tried changing the stack size with "ulimit -s" to test this, but any value other than 10240 and the JVM does not start with an error of:</p>
<pre>Error occurred during initialization of VM
Cannot create VM thread. Out of system resources.</pre>
<p>I can generally get around Linux, but I really don't know much about system configuration, and I haven't been able to find anything specifically addressing this kind of situation. Any ideas on what system or JVM settings could be causing this would be appreciated.</p>
<p><strong>Edits</strong>: Running the thread-limit program mentioned by <a href="http://stackoverflow.com/questions/116640/low-single-process-thread-limit-in-red-hat-linux#116696">plinth</a>, there was no failure until it tried to create the 1529th thread.</p>
<p>The issue also did not occur using a 1.4 JVM (does occur with 1.6.0_02 and 1.6.0_04 JVMs, can't test with a 1.5 JVM at the moment).</p>
<p>The code for the thread test I'm using is as follows:</p>
<pre><code>public class ThreadTest {
public static void main(String[] pArgs) throws Exception {
try {
// keep spawning new threads forever
while (true) {
new TestThread().start();
}
}
// when out of memory error is reached, print out the number of
// successful threads spawned and exit
catch ( OutOfMemoryError e ) {
System.out.println(TestThread.CREATE_COUNT);
System.exit(-1);
}
}
static class TestThread extends Thread {
private static int CREATE_COUNT = 0;
public TestThread() {
CREATE_COUNT++;
}
// make the thread wait for eternity after being spawned
public void run() {
try {
sleep(Integer.MAX_VALUE);
}
// even if there is an interruption, dont do anything
catch (InterruptedException e) {
}
}
}
}
</code></pre>
<p>If you run this with a 1.4 JVM it will hang when it can't create any more threads and require a kill -9 (at least it did for me).</p>
<p><strong>More Edit:</strong></p>
<p>It turns out that the system that is having the problem is using the LinuxThreads threading model while another system that works fine is using the NPTL model. </p>
|
<p>Have you looked at <a href="http://people.redhat.com/alikins/system_tuning.html#threads" rel="nofollow">this resource</a>?
It states that you should be able run thread-limit to find the maximum number of threads and can tweak it by compiling glibc.</p>
|
cURL equivalent in JAVA <p>I am tasked with writing an authentication component for an open source <code>JAVA</code> app. We have an in-house authentication widget that uses <code>https</code>. I have some example <code>php</code> code that accesses the <code>widget</code> which uses <code>cURL</code> to handle the transfer. </p>
<p>My question is whether or not there is a port of <code>cURL</code> to <code>JAVA</code>, or better yet, what base package will get me close enough to handle the task? </p>
<p><strong>Update</strong>:</p>
<p>This is in a nutshell, the code I would like to replicate in JAVA:</p>
<pre><code>$cp = curl_init();
$my_url = "https://" . AUTH_SERVER . "/auth/authenticate.asp?pt1=$uname&pt2=$pass&pt4=full";
curl_setopt($cp, CURLOPT_URL, $my_url);
curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($cp);
curl_close($cp);
</code></pre>
<p><a href="http://stackoverflow.com/questions/116650/curl-equivalent-in-java#116725">Heath</a>, I think you're on the right track, I think I'm going to end up using HttpsURLConnection and then picking out what I need from the response.</p>
|
<p>Exception handling omitted:</p>
<pre><code>HttpURLConnection con = (HttpURLConnection) new URL("https://www.example.com").openConnection();
con.setRequestMethod("POST");
con.getOutputStream().write("LOGIN".getBytes("UTF-8"));
con.getInputStream();
</code></pre>
|
Javascript to extract author/date from SVN keyword substitution <p>SVN keyword substition gives is not pretty. E.g.,</p>
<blockquote>
<p>Last updated: $Date$ by $Author$</p>
</blockquote>
<p>yields</p>
<blockquote>
<p>Last updated: $Date: 2008-09-22
14:38:43 -0400 (Mon, 22 Sep 2008) $ by
$Author: cconway $"</p>
</blockquote>
<p>Does anybody have a Javascript snippet that prettifies things and outputs some HTML? The result should be more like:</p>
<blockquote>
<p>Last update: 22 Sep 2008 by cconway</p>
</blockquote>
<p>P.S. Is there a way to replace "cconway" with a display name?</p>
|
<p>Errr.. This feels a bit like me doing your job for you :), but here goes:</p>
<pre><code>function formatSvnString(string){
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var re = /\$Date: (\d{4})-(\d\d)-(\d\d).*?\$Author: (\S+) \$/
return string.replace(re, function(match, year, month, day, author){
var date = new Date([year, month, day].join('/'))
return date.getDate()
+ ' ' + months[date.getMonth()]
+ ' ' + date.getFullYear()
+ ' by ' + author
})
}
</code></pre>
<p>Usage:</p>
<pre><code>formatSvnString("$Date: 2008-09-22 14:38:43 -0400 (Mon, 22 Sep 2008) $ by $Author: cconway $")
// returns: 22 Sep 2008 by cconway
</code></pre>
<p>I'll leave it up to you to work out how to find these SVN string and apply the above code automatically :)</p>
<p>To do the user's display name, you'll either have to convince SVN to insert it (I don't think it can do that, but I might be wrong), or somehow provide a means for JS to either fetch it, or to have access to a table full of usernames and associated display name (might be a bit too much like a security risk though. Hey kids, see if you can break into my server using one of these usernames!)</p>
|
Oracle: Is there a simple way to say "if null keep the current value" in merge/update statements? <p>I have a rather weak understanding of any of oracle's more advanced functionality but this should I think be possible.</p>
<p>Say I have a table with the following schema:</p>
<pre><code>MyTable
Id INTEGER,
Col1 VARCHAR2(100),
Col2 VARCHAR2(100)
</code></pre>
<p>I would like to write an sproc with the following </p>
<pre><code>PROCEDURE InsertOrUpdateMyTable(p_id in integer, p_col1 in varcahr2, p_col2 in varchar2)
</code></pre>
<p>Which, in the case of an update will, if the value in p_col1, p_col2 is null will not overwrite Col1, Col2 respectively</p>
<p>So If I have a record:</p>
<pre><code>id=123, Col1='ABC', Col2='DEF'
exec InsertOrUpdateMyTable(123, 'XYZ', '098'); --results in id=123, Col1='XYZ', Col2='098'
exec InsertOrUpdateMyTable(123, NULL, '098'); --results in id=123, Col1='ABC', Col2='098'
exec InsertOrUpdateMyTable(123, NULL, NULL); --results in id=123, Col1='ABC', Col2='DEF'
</code></pre>
<p>Is there any simple way of doing this without having multiple SQL statements? </p>
<p>I am thinking there might be a way to do this with the Merge statement though I am only mildly familiar with it.</p>
<p><hr /></p>
<p><strong>EDIT:</strong>
Cade Roux bellow suggests using COALESCE which works great! <a href="http://www.java2s.com/Code/Oracle/Conversion-Functions/COALESCEreturnsthefirstnonnullexpressionintheexpressionlist.htm" rel="nofollow">Here are some examples of using the coalesce kewyord.</a>
And here is the solution for my problem:</p>
<pre><code>MERGE INTO MyTable mt
USING (SELECT 1 FROM DUAL) a
ON (mt.ID = p_id)
WHEN MATCHED THEN
UPDATE
SET mt.Col1 = coalesce(p_col1, mt.Col1), mt.Col2 = coalesce(p_col2, mt.Col2)
WHEN NOT MATCHED THEN
INSERT (ID, Col1, Col2)
VALUES (p_id, p_col1, p_col2);
</code></pre>
|
<p>Change the call or the update statement to use</p>
<pre><code>nvl(newValue, oldValue)
</code></pre>
<p>for the new field value.</p>
|
Scrape multi-frame website <p>I'm auditing our existing web application, which makes heavy use of <a href="http://www.w3schools.com/HTML/html_frames.asp" rel="nofollow">HTML frames</a>. I would like to download all of the HTML in each frame, is there a method of doing this with <a href="http://www.gnu.org/software/wget/" rel="nofollow">wget</a> or a little bit of scripting?</p>
|
<p>as an addition to Steve's answer:</p>
<p>Span to any hostââ-Hâ</p>
<p>The â-Hâ option turns on host spanning, thus allowing Wget's recursive run to visit any host referenced by a link. Unless sufficient recursion-limiting criteria are applied depth, these foreign hosts will typically link to yet more hosts, and so on until Wget ends up sucking up much more data than you have intended. </p>
<p>Limit spanning to certain domainsââ-Dâ</p>
<p>The â-Dâ option allows you to specify the domains that will be followed, thus limiting the recursion only to the hosts that belong to these domains. Obviously, this makes sense only in conjunction with â-Hâ. </p>
<p>A typical example would be downloading the contents of âwww.server.comâ, but allowing downloads from âimages.server.comâ, etc.:</p>
<pre><code> wget -rH -Dserver.com http://www.server.com/
</code></pre>
<p>You can specify more than one address by separating them with a comma, </p>
<p>e.g. â-Ddomain1.com,domain2.comâ. </p>
<p>taken from: <a href="http://www.gnu.org/software/wget/manual/html_node/Spanning-Hosts.html#Spanning-Hosts">wget manual</a></p>
|
Is there an "anonymous" generic tag in C#, like '?' in Java? <p>In Java, one can declare a variable parameterised by an "unknown" generic type, which looks like this:</p>
<pre><code>Foo<?> x;
</code></pre>
<p>Is there an equivalent construct to this question-mark, in C#?</p>
|
<p>From <a href="http://www.25hoursaday.com/CsharpVsJava.html#generics">C# from a Java developer's perspective</a> by Dare Obasanjo:</p>
<p>In certain cases, one may need create a method that can operate on data structures containing any type as opposed to those that contain a specific type (e.g. a method to print all the objects in a data structure) while still taking advantage of the benefits of strong typing in generics. The mechanism for specifying this in C# is via a feature called generic type inferencing while in Java this is done using wildcard types. The following code samples show how both approaches lead to the same result.</p>
<p>C# Code</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
class Test{
//Prints the contents of any generic Stack by
//using generic type inference
public static void PrintStackContents<T>(Stack<T> s){
while(s.Count != 0){
Console.WriteLine(s.Pop());
}
}
public static void Main(String[] args){
Stack<int> s2 = new Stack<int>();
s2.Push(4);
s2.Push(5);
s2.Push(6);
PrintStackContents(s2);
Stack<string> s1 = new Stack<string>();
s1.Push("One");
s1.Push("Two");
s1.Push("Three");
PrintStackContents(s1);
}
}
</code></pre>
<p>Java Code</p>
<pre><code>import java.util.*;
class Test{
//Prints the contents of any generic Stack by
//specifying wildcard type
public static void PrintStackContents(Stack<?> s){
while(!s.empty()){
System.out.println(s.pop());
}
}
public static void main(String[] args){
Stack <Integer> s2 = new Stack <Integer>();
s2.push(4);
s2.push(5);
s2.push(6);
PrintStackContents(s2);
Stack<String> s1 = new Stack<String>();
s1.push("One");
s1.push("Two");
s1.push("Three");
PrintStackContents(s1);
}
}
</code></pre>
|
When have we any practical use for hierarchical namespaces in c++? <p>I can understand the use for one level of namespaces. But 3 levels of namespaces. Looks insane. Is there any practical use for that? Or is it just a misconception?</p>
|
<p>Hierarchical namespaces do have a use in that they allow progressively more refined definitions. Certainly a single provider may produce two classes with the same name. Often the first level is occupied by the company name, the second specifies the product, the third (and possibly more) my provide the domain.</p>
<p>There are also other uses of namespace segregation. One popular situation is placing the base classes for a factory pattern in its own namespace and then derived factories in their own namespaces by provider. E.g. <code>System.Data</code>, <code>System.Data.SqlClient</code> and <code>System.Data.OleDbClient</code>.</p>
|
Can I (re-) map commands in vim? <p>I love vim and the speed it gives me. But sometimes, my fingers are too speedy and I find myself typing ":WQ" instead of ":wq" (on a German keyboard, you have to press shift to get the colon). Vim will then complain that 'W' is not an editor command.</p>
<p>Is there some way to make W and Q editor commands?</p>
|
<p>Try </p>
<pre><code> :command WQ wq
:command Wq wq
:command W w
:command Q q
</code></pre>
<p>This way you can define your own commands. See <code>:help command</code> for more information.</p>
|
Is it possible to delete subdomain cookies? <p>If there is a cookie set for a subdomain, metric.foo.com, is there a way for me to delete the metric.foo.com cookie on a request to www.foo.com? The browser (at least Firefox) seems to ignore a Set-Cookie with a domain of metric.foo.com.</p>
|
<p>Cookies are only readable by the domain that created them, so if the cookie was created at metric.foo.com, it will have to be deleted under the same domain as it was created. This includes sub-domains.</p>
<p>If you are required to delete a cookie from metric.foo.com, but are currently running a page at www.foo.com, you will not be able to.</p>
<p>In order to do this, you need to load the page from metric.foo.com, or create the cookie under foo.com so it can be accessable under any subdomain. OR use this:</p>
<p>Response.cookies("mycookie").domain = ".foo.com"</p>
<p>...while creating it, AND before you delete it.</p>
<p>..untested - should work.</p>
|
How do I get a decimal value when using the division operator in Python? <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
|
<p>There are three options:</p>
<pre><code>>>> 4 / float(100)
0.04
>>> 4 / 100.0
0.04
</code></pre>
<p>which is the same behavior as the C, C++, Java etc, or </p>
<pre><code>>>> from __future__ import division
>>> 4 / 100
0.04
</code></pre>
<p>You can also activate this behavior by passing the argument <code>-Qnew</code> to the Python interpreter:</p>
<pre><code>$ python -Qnew
>>> 4 / 100
0.04
</code></pre>
<p>The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the <code>//</code> operator. </p>
<p><strong>Edit</strong>: added section about <code>-Qnew</code>, thanks to <a href="http://stackoverflow.com/users/6899/">ΤÎΩΤÎÎÎÎ¥</a>!</p>
|
Best approach for sortable table with a lot of data <p>On our web application, the search results are displayed in sortable tables. The user can click on any column and sort the result. The problem is some times, the user does a broad search and gets a lot of data returned. To make the sortable part work, you probably need all the results, which takes a long time. Or I can retrieve few results at a time, but then sorting won't really work well. What's the best practice to display sortable tables that might contain lots of data? </p>
<hr>
<p>Thanks for all the advises. I will certainly going over these.</p>
<p>We are using an existing Javascript framework that has the sortable table; "lots" of results means hundreds. The problem is that our users are at some remote site and a lot of delay is the network time to send/receive data from the data center. Sorting the data at the database side and only send one page worth of results at a time is nice; but when the user clicks some column header, another round trip is done, which always add 3-4 seconds. </p>
<p>Well, I guess that might be the network team's problem :)</p>
|
<p>You should be doing paging back on the database server. E.g. on SQL 2005 and SQL 2008 there are paging techniques. I'd suggest looking at paging options for whatever system you're looking at.</p>
|
What can Services do under Windows? <p>Does anyone have a good guide to capabilities of Windows Services under XP? In particular, I am trying to find out what happens when a program being run as a service tries to open windows, but hasn't been given permission to interact with the desktop.</p>
<p>Basically, I have a program that is/was a GUI application, that should be able to run as a service for long term background processing. Rewriting the program to not display the GUI elements when doing background processing is a major effort, so I'd like to see if there is just a way to ignore the UI elements. It is sort of working now, as long as too many windows aren't opened. I'm trying to figure out what limits I might be running into. Ideally, there would be an MSDN page that discusses this, but I've had no luck finding one yet.</p>
|
<p>Generally, services should be designed to not have any visible UI. The entire point of a service is to run in the background, without UI, unattended. (Think SQL Server, IIS, etc.)</p>
<p>In most scenarios, a separate application controls the service's operation, should a GUI be needed. (Continuing the samples I just mentioned, SQL Server Management Studio, IIS Manager, etc.) These separate applications configure and manipulate the service (and occasionally, if needed, bounce said service).</p>
<p>If your service requires occasional UI, and said UI can't be isolated to a control app, then you probably should reconsider the fact that you're using a service to begin with. Perhaps a UI application which resides in the system notification area is the right pattern to use? (E.G., Windows Live Communicator.)</p>
|
Planning the flow of a program <p>I am already aware of UML but I want to look at all the options before I pick. Essentially I will need to have a way (preferably visual) to plan out the flow and actions of programs. They will all be web applications written in PHP or Python.</p>
<p>What (preferably free) ways are there to plan a program in this way beyond UML and common flow charts?</p>
|
<p>Large white board, dry erase markers, time and collaborators always work in a pinch..and a digital camera is good to snapshot the progress(unless you have a really nice whiteboard that will save to a file).</p>
|
Wait until any of Future<T> is done <p>I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of N tasks are finished).
Currently they are presented as Future, so I need something like</p>
<pre><code>/**
* Blocks current thread until one of specified futures is done and returns it.
*/
public static <T> Future<T> waitForAny(Collection<Future<T>> futures)
throws AllFuturesFailedException
</code></pre>
<p>Is there anything like this? Or anything similar, not necessary for Future. Currently I loop through collection of futures, check if one is finished, then sleep for some time and check again. This looks like not the best solution, because if I sleep for long period then unwanted delay is added, if I sleep for short period then it can affect performance.</p>
<p>I could try using </p>
<pre><code>new CountDownLatch(1)
</code></pre>
<p>and decrease countdown when task is complete and do </p>
<pre><code>countdown.await()
</code></pre>
<p>, but I found it possible only if I control Future creation. It is possible, but requires system redesign, because currently logic of tasks creation (sending Callable to ExecutorService) is separated from decision to wait for which Future. I could also override </p>
<pre><code><T> RunnableFuture<T> AbstractExecutorService.newTaskFor(Callable<T> callable)
</code></pre>
<p>and create custom implementation of RunnableFuture with ability to attach listener to be notified when task is finished, then attach such listener to needed tasks and use CountDownLatch, but that means I have to override newTaskFor for every ExecutorService I use - and potentially there will be implementation which do not extend AbstractExecutorService. I could also try wrapping given ExecutorService for same purpose, but then I have to decorate all methods producing Futures.</p>
<p>All these solutions may work but seem very unnatural. It looks like I'm missing something simple, like </p>
<pre><code>WaitHandle.WaitAny(WaitHandle[] waitHandles)
</code></pre>
<p>in c#. Are there any well known solutions for such kind of problem?</p>
<p>UPDATE:</p>
<p>Originally I did not have access to Future creation at all, so there were no elegant solution. After redesigning system I got access to Future creation and was able to add countDownLatch.countdown() to execution process, then I can countDownLatch.await() and everything works fine.
Thanks for other answers, I did not know about ExecutorCompletionService and it indeed can be helpful in similar tasks, but in this particular case it could not be used because some Futures are created without any executor - actual task is sent to another server via network, completes remotely and completion notification is received.</p>
|
<p>simple, check out <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html">ExecutorCompletionService</a>.</p>
|
How to get Django AutoFields to start at a higher number <p>For our Django App, we'd like to get an <code>AutoField</code> to start at a number other than 1. There doesn't seem to be an obvious way to do this. Any ideas?</p>
|
<p>Like the others have said, this would be much easier to do on the database side than the Django side. </p>
<p>For Postgres, it'd be <a href="http://www.postgresql.org/docs/9.1/static/sql-altersequence.html">like so</a>: <code>ALTER SEQUENCE sequence_name RESTART WITH 12345;</code> Look at your own DB engine's docs for how you'd do it there.</p>
|
Upload files directly to Amazon S3 from ASP.NET application <p>My ASP.NET MVC application will take a lot of bandwidth and storage space. How can I setup an ASP.NET upload page so the file the user uploaded will go straight to Amazon S3 without using my web server's storage and bandwidth?</p>
|
<p>Update Feb 2016:</p>
<p>The AWS SDK can handle a lot more of this now. Check out <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTForms.html" rel="nofollow">how to build the form</a>, and <a href="http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-authentication-HTTPPOST.html" rel="nofollow">how to build the signature</a>. That should prevent you from needing the bandwidth on your end, assuming you need to do no processing of the content yourself before sending it to S3.</p>
|
How do I unload a externally loaded SWF file from a SWFLoader component in Adobe Flex? <p>I have an application that loads external SWF files and plays them inside a Adobe Flex / Air application via the <a href="http://livedocs.adobe.com/flex/3/html/controls_15.html" rel="nofollow">SWFLoader Flex component</a>. I have been trying to find a way to unload them from a button click event. I have Google'd far and wide and no one seems to have been able to do it without a hack. The combination of code I see people use is:</p>
<pre><code>swfLoader.source = ""; // Removes the external link to the SWF.
swfLoader.load(null); // Forces the loader to try to load nothing.
// Note: At this point sound from the SWF is still playing, and
// seems to still be playing in memory.
flash.media.SoundMixer.stopAll();
// Stops the sound. This works on my development machine, but not
// on the client's.
</code></pre>
<p>If the SWFs are closed (hidden) this way, eventually the program crashes.</p>
<p>Any ideas? I have found tons of posts in various forums with people having the same problem. I assume I will get one wrong/incomplete answer here, and than my post will sink into nothingness as usual, but either way, thanks in advance!</p>
<p><em>Edit 1</em>: I can't edit the actual SWF movies, they're created by the client. If I can't close any SWF opened through Flex, isn't that a problem with the Flex architecture? Is my only option sending the SWFs to the web browser?</p>
|
<blockquote>
<p>... isn't that a problem with the Flex architecture?</p>
</blockquote>
<p>Yes it is, and it also affects Flash in general. Until you can take advantage of the <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/Loader.html">Loader.unloadAndStop()</a> method in FP10 (AIR 1.5), you can't guarantee that externally loaded content will not continue to consume memory and cpu resources, even if you use the <code>Loader.unload()</code> method. (To be honest, I'm not 100% sure that even that will guarantee freeing of resources, but maybe I'm a pessimist.)</p>
<p>The next best thing is for you to insist that the creators of the content you load adhere to a set of guidelines, including exposing something like a <code>dispose()</code> method which your app can call to ask it to release as many resources as possible before you <code>unload()</code> it. If this isn't possible, then your application will almost definitely bloat in memory and cpu usage each time you load an external swf. Sorry. </p>
<p>If it makes you feel any better, you're not alone. ;)</p>
|
How do I open Office 2007 files stored on a website? <p>I have a website where people can upload documents, and view them later at their convenience. I store the binary info along with the mime type in my db, and later just stream the binary content straight to the browser.</p>
<p>This works for for every file type except Office 2007 files. When I try to view the Office 2007 files, I get a popup requesting credentials. After I dismiss the the dialog (by canceling), I get another popup like the one below:</p>
<p><img src="http://4.bp.blogspot.com/_U0AuZcqOces/SNgVYTB4rCI/AAAAAAAAAD8/_WT8BwTZwBQ/s400/office07popup.jpg"></p>
<p>After also dismissing this dialog (by clicking "Yes"), the document finally opens. What gives? Does the browser really not know how to handle Office 2007 files? I checked the mime-type I'm saving, and everything looks correct. Any ideas on what I can do to get rid of these dialogs when trying to open a file?</p>
|
<p>Check out <a href="http://blogs.msdn.com/vsofficedeveloper/pages/Excel-2007-Extension-Warning.aspx" rel="nofollow">this explanation</a> on VS Office Developer.</p>
<p>It gives a registry hack which your users could choose to apply to rid suppress this warning.</p>
|
How to version control the build tools and libraries? <p>What are the recommendations for including your compiler, libraries, and other tools in your source control system itself?</p>
<p>In the past, I've run into issues where, although we had all the source code, building an old version of the product was an exercise in scurrying around trying to get the exact correct configuration of Visual Studio, InstallShield and other tools (including the correct patch version) used to build the product. On my next project, I'd like to avoid this by checking these build tools into source control, and then build using them. This would also simplify things in terms of setting up a new build machine -- 1) install our source control tool, 2) point at the right branch, and 3) build -- that's it.</p>
<p>Options I've considered include:</p>
<ul>
<li>Copying the install CD ISO to source control - although this provides the backup we need if we have to go back to an older version, it isn't a good option for "live" use (each build would need to start with an install step, which could easily turn a 1 hour build into 3 hours).</li>
<li>Installing the software to source control. ClearCase maps your branch to a drive letter; we could install the software under this drive. This doesn't take into account non-file part of installing your tools, like registry settings.</li>
<li>Installing all the software and setting up the build process inside a virtual machine, storing the virtual machine in source control, and figuring out how to get the VM to do a build on boot. While we capture the state of the "build machine" with ease, we get the overhead of a VM, and it doesn't help with the "make the same tools available to developers issue."</li>
</ul>
<p>It seems such a basic idea of configuration management, but I've been unable to track down any resources for how to do this. What are the suggestions?</p>
|
<p>I think the VM is your best solution. We always used dedicated build machines to get consistency. In the old COM DLL Hell days, there were dependencies on (COMCAT.DLL, anyone) on non-development software installed (Office). Your first two options don't solve anything that has shared COM components. If you don't have any shared components issue, maybe they will work.</p>
<p>There is no reason the developers couldn't take a copy of the same VM to be able to debug in a clean environment. Your issues would be more complex if there are a lot of physical layers in your architecture, like mail server, database server, etc.</p>
|
Best practice for translating exceptions in C++/CLI wrapper class <p>I am writing a .NET wrapper class for an existing native class which throws exceptions. What are the best practices for translating between native C++ exceptions and Managed exceptions? Catch and re-throw on a one-to-one basis (e.g. std::invalid_argument -> System.System.ArgumentException)? Is there a mapping already drawn up somewhere?</p>
|
<p>There is no standard mapping that I know of. What I've done in the past is translate the ones I know about, and a catch block for System.Runtime.InteropServices.SEHException. All non-translated exceptions will be turned into that exception. As long as you have a debug build of the code that is throwing the exception, you should get a nice stack trace. Then you can go and look at the exception and write the wrapper.</p>
<p>But on the last project I had to do this on, I went with something much more simple, I ended up writing a couple of System.Exception derivatives for logic_error and runtime_error. Then I would catch those 2 base classes and use typeid(err) to write the .NET message that got thrown. This way I didn't "lose" what was being thrown from the C++ but didn't have to map everything except the most important ones.</p>
|
How to refactor in a branch without losing my mind? <p>I refactor my and other people's code <strong>all the time</strong>.
When I work in a branch and not in Trunk, this sometimes results in some extremely painful merges, especially if I don't merge back to Trunk regularly (the code at the branch slowly shifts away from the Trunc, and when people modify Trunk I have to figure out manually how to apply this to the branch).</p>
<p>The solutions I know are either </p>
<ol>
<li>Constantly merge to and from Trunk - reduces painful merges, but then why work in a branch at all?</li>
<li>Whenever you need to refactor something, switch to Trunk, do the refactoring there and merge to your branch - I don't find this very practical, since the actual cost of switching environments for every refactoring is huge.</li>
</ol>
<p>What do you do?</p>
|
<p>Refactoring on a large scale needs to be done at the right time in the development timeline. If you do huge amounts of refactoring near release you'll end up hurting yourself because you'll introduce painful merges at a time when changes should be minimized. The more disruptive your refactoring will be the earlier in the development cycle it should happen (and the more special process there should be for it, e.g. stop edits to the affected files as much as possible for a period of time).</p>
<p>Constantly merging to and from trunk is generally good practice.</p>
<p>Why work in a branch at all in that case? Because you have more control (you can stop merging into trunk to stabilize it for release, for example, without stopping checkins to your development branch). Because you can place a high level of validation around merging to/from trunk without impacting checkin velocity to the development branch much.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.