input
stringlengths
51
42.3k
output
stringlengths
18
55k
Moving Mac's user settings to another users <p>I have three new admin users for my Mac: Math, CS and Fun.</p> <p>I would like to move my user settings such as keyboard layout and other config files in the user Masi to other users.</p> <p>I use mostly terminal softwares.</p> <p><strong>How can you move the user settings from one user to other users in Mac Leopard?</strong></p>
<p>Most programs store preferences in subfolders of ~/Library. Just copy corresponding folders, but be careful, you can break something.</p>
Regexp for matching numbers and units in an HTML fragment? <p>I'm trying to make a regexp that will match numbers, excluding numbers that are part of other words or numbers inside certain html tags. The part for matching numbers works well but I can't figure out how to find the numbers inside the html.</p> <p>Current code:</p> <pre><code>//number regexp part var prefix = '\\b()';//for future use var baseNumber = '((\\+|-)?([\\d,]+)(?:(\\.)(\\d+))?)'; var SIBaseUnit = 'm|kg|s|A|K|mol|cd'; var SIPrefix = 'Y|Z|E|P|T|G|M|k|h|ia|d|c|m|µ|n|p|f|a|z|y'; var SIUnit = '(?:('+SIPrefix+')?('+SIBaseUnit+'))'; var generalSuffix = '(PM|AM|pm|am|in|ft)'; var suffix = '('+SIUnit+'|'+generalSuffix+')?\\b'; var number = '(' + prefix + baseNumber + suffix + ')'; //trying to make it match only when not within tags or inside excluded tags var htmlBlackList = 'script|style|head' var htmlStartTag = '&lt;[^(' + htmlBlackList + ')]\\b[^&gt;]*?&gt;'; var reDecimal = new RegExp(htmlStartTag + '[^&lt;]*?' + number + '[^&gt;]*?&lt;'); </code></pre>
<pre><code>&lt;script&gt; var htmlFragment = "&lt;script&gt;alert('hi')&lt;/script&gt;"; var style = "&lt;style&gt;.foo { font-size: 14pt }&lt;/style&gt;"; // ... &lt;/script&gt; &lt;!-- turn off this style for now &lt;style&gt; ... &lt;/style&gt; --&gt; </code></pre> <p>Good luck getting a regular expression to figure that out.</p> <p>You're using JavaScript, so I'm guessing you're probably running in a browser. Which means you have access to the DOM, giving you access to the browser's very capable HTML parser. <em>Use it.</em></p>
imagecreatefromjpeg is silently terminating scripts <p>Like so many before me, I'm writing a PHP script to do some image thumbnailing. The script has earned WOMM (works on my machine) certification, but when I move it to my host (1&amp;1 Basic), there's an issue: images above a certain filesize cannot be processed. I've moved all operations to the filesystem, to be certain it's not some latent <code>POST</code> issue. Here's the relevant code:</p> <pre><code> function cropAndResizeImage( $imageLocation ) { // // Just to be certain // ini_set('display_errors','on'); error_reporting(E_ALL); ini_set('memory_limit','128M'); ini_set('max_execution_time','300'); $image_info = getimagesize($imageLocation); $image_width = $image_info[0]; $image_height = $image_info[1]; $image_type = $image_info[2]; switch ( $image_type ) { // snip... case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($imageLocation); break; default: break; } // snip... } </code></pre> <p>Using my mystical powers of <code>println</code> debugging, I've been able to determine that <code>imagecreatefromjpeg</code> is not returning; in fact, the script halts completely when it gets to it. Some facts:</p> <ul> <li>This is correlated to filesize. Images under 1MB appear to be fine (spot-checked), but images around 3MB barf. No clue what the precise cutoff is, though.</li> <li>This is not due to server timeouts; <code>wget</code> returns in &lt;1s on 3MB images, significantly longer on "appropriately small" images (indicating no processing of large images).</li> <li>Prefixing the function call with <code>@</code> to suppress errors has no effect. This matches well with the fact that the script is not throwing an error, it's simply silently terminating upon this function call.</li> </ul> <p>If I had to guess, there may be some GD parameter that I don't know about (or have access to) that limits input file sizes on 1&amp;1's servers &mdash; the config variable guess is due to the fact that it barfs immediately, and doesn't appear (heuristically) to do any actual loading of or computations on the image.</p> <p>Any suggestions? Thanks for the help.</p> <p><strong>Update (courtesy <a href="http://stackoverflow.com/users/5441/darryl-hein">@Darryl's</a> comments):</strong> calls to <code>phpinfo</code> indicate that PHP is updating the <code>max_execution_time</code> and <code>memory_limit</code> variables correctly. This doesn't necessarily mean that these resources are being allocated, simply that they appear to be functioning as expected.</p> <p><strong>Update 2:</strong> following some references from The Google, I tried optimizing the JPEG (reduced in quality from 3MB to 200KB) with no luck, so it's not an image filesize issue. I then tried reducing the number of pixels of the original 3888x2592 image, and the first successful size is 1400x2592 (1401x and 1402x both result in half-parses and errors indicating "malformed JPEG", which doesn't make much sense unless the entire image isn't being loaded). By reducing further to 1300x2592, I can instantiate the 400x300 thumbnail image that I'm actually looking for; at 1400x2592, the <code>imagecreatetruecolor</code> call I'm using to take care of that task fails silently in the same manner as <code>imagecreatefromjpeg</code>.</p> <p>As to why this is, I'm a little uncertain. 1400 * 2592 == 3.5MB gives nothing particularly meaningful, but I have to imagine this is a limit on the number of pixels GD + PHP will process.</p>
<p>Please see <a href="http://pt.php.net/manual/en/function.imagecreatefromjpeg.php#76968" rel="nofollow">this note</a> regarding memory usage on the php website.</p> <p>*"The memory required to load an image using imagecreatefromjpeg() is a function of the image's dimensions and the images's bit depth, multipled by an overhead.</p> <p>It can calculated from this formula:</p> <p>Num bytes = Width * Height * Bytes per pixel * Overhead fudge factor"*</p>
how do you set a max-age for javascript/css? <p>I just ran <a href="http://webpagetest.org/" rel="nofollow">Pagetest</a> and it says I need to set a max-age for my JS/CSS. How do I do that?</p>
<p>Sounds like it's talking about HTTP headers. Basically you'll need to add a couple of HTTP headers to be sent with your Javascript and CSS files (and images too, would be a good idea), looking something like this:</p> <pre><code>Cache-Control: max-age=86400 Expires: Sat, 28 Mar 2009 16:00:00 GMT </code></pre> <p>The first one gives the maximum amount of time, in seconds, that a browser will keep the content (the JS or CSS file) before downloading it again from the server; the second one gives the date and time after which the browser should redownload the content. Yes, these are two ways of saying the same thing, but the <code>Cache-Control</code> header is a little newer and I'm not sure if it's universally supported yet; there's really no harm in specifying both. (<code>Cache-Control</code> takes precedence over <code>Expires</code> if there is a conflict.)</p> <p>As for how you actually configure your server to send these headers: it depends on which web server you're running. If you're using Apache, look at <a href="http://httpd.apache.org/docs/2.2/mod/mod%5Fexpires.html">mod_expires</a>.</p>
How to create an aggregate Atom feed from two Atom feeds using LINQ to XML <p>Just took a stab at creating an aggregate feed - from two separate Atom feeds - sorted descending by published date... </p> <p>UPDATE: Thanks to Martin Honnen (MVP) over at <a href="http://social.msdn.microsoft.com/Forums/en-US/categories/" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/categories/</a> - combined with a safe XElement.Load(url) helper (and iterator block)... I think the code below is a pretty good approach for aggregating Xml documents (aggregate sitemaps in this case - although this can easily be adapted for Atom or RSS feeds).</p> <p>The namespace conversion helper below converts elements only and not attributes (although that too can be added).</p> <pre><code>static void Main(string[] args) { XDocument feed = MergeSiteMaps(new List&lt;string&gt;() { "http://www.58bits.com/blog/googleSitemap.ashx", "http://www.58bits.com/otherblog/googleSiteMap.ashx", "http://www.58bits.com/photos/sitemap.xml"}); XNamespace sm = "http://www.sitemaps.org/schemas/sitemap/0.9"; foreach (XElement location in feed.Root.Elements(sm + "url").Elements(sm + "loc")) { Console.WriteLine((string)location); } } public static XDocument MergeSiteMaps(IEnumerable&lt;string&gt; urls) { XNamespace sm = "http://www.sitemaps.org/schemas/sitemap/0.9"; XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; XNamespace xsd = "http://www.w3.org/2001/XMLSchema"; string schemaLocation = "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"; //Our container sitemap document return new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XElement(sm + "urlset", new XAttribute(XNamespace.Xmlns + "xsi", xsi), new XAttribute(XNamespace.Xmlns + "xsd", xsd), new XAttribute(xsi + "schemaLocation", schemaLocation), new XElement(sm + "url", new XElement(sm + "loc", "http://www.58bits.com/"), new XElement(sm + "lastmod", DateTime.Now.ToString("yyyy-MM-dd")), new XElement(sm + "changefreq", "monthly"), new XElement(sm + "priority", "1.0")), new XElement(sm + "url", new XElement(sm + "loc", "http://www.58bits.com/default.aspx"), new XElement(sm + "lastmod", DateTime.Now.ToString("yyyy-MM-dd")), new XElement(sm + "changefreq", "monthly"), new XElement(sm + "priority", "1.0")), GetElements(sm, urls, "url")) ); } private static IEnumerable&lt;XElement&gt; GetElements(XNamespace ns, IEnumerable&lt;string&gt; urls, string elementLocalName) { XElement source; foreach (string url in urls) { try { source = XElement.Load(url); } catch (Exception ex) { //TODO: Log the Url that failed string message = ex.Message; continue; } XNamespace defaultNamespace = source.GetDefaultNamespace(); bool differentNamespace = (ns != defaultNamespace); foreach (XElement element in source.Elements(defaultNamespace + elementLocalName)) { if (differentNamespace) ChangeNamespace(ns, element); yield return element; } } } private static void ChangeNamespace(XNamespace ns, XElement entry) { foreach (XElement e in entry.DescendantsAndSelf()) { if (e.Name.Namespace != XNamespace.None) { e.Name = ns.GetName(e.Name.LocalName); } } } </code></pre>
<p>I would look into the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx" rel="nofollow">SyndicationFeed</a> Class. Here is a sample of generating a feed using this.</p> <pre><code>private static SyndicationFeed CreateFeed(List&lt;SyndicationItem&gt; items) { // Create the list of syndication items. These correspond to Atom entries SyndicationFeed feed; // create the feed containing the syndication items. feed = new SyndicationFeed() { // The feed must have a unique stable URI id Id = "http://example.com/MyFeed", Title = new TextSyndicationContent("My Feed"), Items = items }; feed.AddSelfLink(WebOperationContext.Current.IncomingRequest.GetRequestUri()); return feed; } private static SyndicationItem CreateItem() { var item = new SyndicationItem() { // Every entry must have a stable unique URI id Id = id.ToString(), Title = new TextSyndicationContent(title), // Every entry should include the last time it was updated LastUpdatedTime = startDate, // The Atom spec requires an author for every entry. If the entry has no author, use the empty string Authors = { new SyndicationPerson() { Name = author.Name, Email = author.EmailAddress, Uri = author.Website } }, // The content of an Atom entry can be text, xml, a link or arbitrary content. In this sample text content is used. Content = new TextSyndicationContent(description), }; return item; } </code></pre>
Does x86 have an atomic increment that keeps the value that was stored? <p>I have found <code>lock inc addr</code> but that doesn't keep a copy of the stored value around and even a read immediately after it in the same thread could come after a competing write.</p> <p>The best solution I have found is a <code>load</code>/<code>inc</code>/<a href="http://en.wikipedia.org/wiki/Compare_and_swap" rel="nofollow"><code>cas</code></a> loop.</p>
<p><code>lock xadd</code> is your friend.</p>
code page values <p>apart from 1252 what other code page values can be used with getencoding() in vb.net?</p> <p>System.Text.Encoding.GetEncoding(1252).Getstring()</p>
<p>Well, any code page that's supported by your system. 437 is one of the old DOS code pages, for example, and 28591 is ISO-Latin-1.</p> <p>Here's a <a href="http://msdn.microsoft.com/en-gb/goglobal/bb964653.aspx">list of lists of code pages</a> from Microsoft, but you should use Encoding.GetEncodings to see what's available on your own machine. I suspect it's not comprehensive though - I'm pretty sure there's a code page for one of the EBCDIC encodings, and I can't see it listed there.</p> <p>Generally though you should know what code page your incoming data is in, so you don't often need to know what other code pages are available.</p>
Is MSXML4 thread safe? <p>I would like to know if I create an instance of Msxml2.FreeThreadedDOMDocument.4.0 in one thread, can I safely manipulate the instance from different threads using raw pointers?</p>
<p>Yes. That is the point of the FreeThreadedDOMDocument. </p> <p>cite: <a href="http://msdn.microsoft.com/en-us/library/ms756987%28VS.85%29.aspx" rel="nofollow">IXMLDOMDocument/DOMDocument</a></p> <blockquote> <p>If you are writing a single threaded application (or a multi-threaded application where only one thread accesses a DOM at one time), then you should use the rental threaded model (Msxml2.DOMDocument.3.0, Msxml2.DOMDocument.4.0, or Msxml2.DOMDocument.6.0). If you are writing an application where multiple threads access will simultaneously access a DOM, then you should use the free threaded model (Msxml2.FreeThreadedDOMDocument.3.0, Msxml2.FreeThreadedDOMDocument.4.0, or Msxml2.FreeThreadedDOMDocument.6.0).</p> </blockquote>
Passing variables and data through a regular web page link? <p>I'm working with a page where I'm trying to submit data when a link is clicked. I already know how to do this with POST and GET using javascript buttons, but how do I get the same effect when I'm working with HTML links?</p>
<p>If you have a plain link you can pass them as query parameters on the link (which is a GET operation)</p> <pre><code>&lt;a href="/myapp/somecontroller.php?id=17&amp;name=fred"&gt;Save&lt;/a&gt; </code></pre> <p>If you have a plain HTML form with no javascript to handle the button press you can put things in hidden fields</p> <pre><code>&lt;form name="theform" method="post" action="/myapp/somecontroller.php"&gt; &lt;input type="hidden" name="id" value="17"&gt; &lt;input type="hidden" name="name" value="fred"&gt; ... &lt;/form&gt; </code></pre> <p>This doesn't require any javascript.</p>
Add or extend file system support under windows <p>I've seen that <a href="http://www.mediafour.com/products/macdrive/" rel="nofollow">Mac Drive 7</a> adds HFS+ and HFS support to windows for both hard-drives and CDs, which includes handling problems like the mac partition format. Clearly that must mean that file system support in windows is extensible somehow, even if it is slow. So where could someone start to write a simple (or not) file system driver for windows? I'm having a lot of trouble googling for this because these are commonly used words.</p>
<p>You need the <a href="http://www.microsoft.com/whdc/devtools/wdk/default.mspx">Windows Driver Kit</a> (WDK). The <a href="http://www.microsoft.com/whdc/devtools/ifskit/default.mspx">Installable File System Kit</a> which is part of the WDK should get you started.</p> <p>Good luck!</p>
Giving candidates interview questions in advance of the interview <p>I'm going to be interviewing for a small team of creative/developers in the next few months. I'm thinking of getting each candidate to put together a short pitch, based on our ideas so I know they get what we're trying to acheive. Of course we'll communicate all that prior to the actual interview, and give them a week or so to prepare.</p> <p>Has anyone had experience of this either from an employer or candidate perspective, what worked, what didn't. Note this part of the interview process isn't technical, it's about understanding the big picture of our business.</p> <p>To re-enforce the programming nature of the question, how do you make sure your new coding hires get what the business is trying to acheive? Technical skill is important, but in our situation they also need to understand our market and products.</p>
<p>What you need is not someone who understand your market/products/big picture, you need someone <em>capable of understanding it</em></p>
Recommended data structure/format for web MVC applications? <p>What's a good data structure for use in MVC web applications to use to pass data into view to ensure standardization and keep the view as non-coder friendly as possible?</p>
<p>Use a custom model class and keep it as non-coder friendly as possible :)<br /> How you construct the model class strongly depends on the specific page.</p>
To get notification after download? <p>imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:srcAddres]];</p> <p>Downloading jpeg to my imagedata will spend some time,for example:2 second,so I want to show an activity indicator until the downloading finished . How can I know when the downloading has finished?</p>
<p>You'll need to use the asynchronous URL loading system instead (<code>NSURLConnection</code> on the iPhone SDK). Here's Apple's documentation:</p> <p><a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html" rel="nofollow">http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html</a></p>
Binding Visible property of a DataGridColumn in WPF DataGrid <p>I cannot bind the Visible property of the WPF datagridtextcolumn to a boolean value.</p> <p>My binding expression is,</p> <pre><code>{Binding Path=DataContext.IsThisColumnVisible, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window},Converter={StaticResource vc}} </code></pre> <p>I have checked that the converter works (bool to the visibility enum) and is in scope.</p> <p>If I use the same expression for the header of the column, the header displays 'false' as expected.</p> <p>Visible is a dependency property so should be bindable.</p> <p>Anyone see what Im doing wrong? Or has anyone else been able to bind to the visible property.</p> <p>Regards,</p> <p>Matt</p>
<p>I worked this out.</p> <p>DataGridCOlumn is not a framework element so the FindAncestor call was failing (DataGridColumn not part of visual tree)</p> <p>Have to set source property of binding expression to a staticresource and it works fine.</p>
Daily risk estimation for your team <p>Assume that you leads team of 4 developers. How often would you estimate the risk of the project? What do you think about the daily estimation? Do you think that the daily updates of the potencial problems (based on the morning stand-up meetings with the team) released as a short summary e-mail is good idea? Maybe you would consider an another form of the risk-analysis document spread among your team?</p>
<p>The daily stand up -- done right -- is a great way to reduce risk on your project because it increases the amount of communication between team members and helps you discover problems earlier. However, the stand-up can't take too long or it will itself become a threat -- people will avoid bringing up potential issues if they think that it will prolong the meeting. I'd not make a formal calculation of risk a part of the daily stand-up, but would use the results of the daily stand-up to trigger a re-analysis as significant new issues arise. You may also want to schedule a regular re-analysis with the frequency depending on the amount of risk you have and are willing to tolerate.</p>
Convert Yahoo Messenger Logs to Adium Logs <p>Is there a way to convert logs from YM for mac to Adium ?</p> <p>Thanks Cezar</p>
<pre><code>#!/usr/bin/perl use warnings; use strict; use File::Find; use File::Copy; use Getopt::Long; my $inDir = undef; my $outDir = undef ; my $adiumUser = undef; my $force = 0; my $foundLogs = 0; my $help = 0; my %Protocols = ( #Map gaim protocol IDs to Adium ones "aim" =&gt; "AIM", "yahoo" =&gt; "Yahoo!", "msn" =&gt; "MSN" #Add the rest here, or tell me what they are, someone who uses other protocols ); sub usage { my $msg = shift; print "Error: $msg\n" if $msg; print "Usage: gaim2adium.pl [--adiumUser &lt;user&gt; | --outDir &lt;output dir&gt;] [--inDir &lt;input dir&gt;] [--yes]\n"; print "Options: (defaults)\n\n"; print "\tinDir:\t\t\tDirectory to import logs from (~/.gaim/logs)\n"; print "\toutDir:\t\t\tDirectory to import logs to (./Logs)\n"; print "\tadiumUser:\t\tAttempt to automatically import logs to the specified Adium user\n"; print "\tyes:\t\t\tDon't prompt before overwriting existing logs\n"; print "\thelp:\t\t\tDisplay this help.\n"; print "\nOnce the logs have been imported, the contents of outDir can be dragged to your Adium log folder\n\n"; exit(1); } sub process_log { -f or return; #gaim logs are LOG_BASE/Protocol/Account/Contact/YYYY-MM-DD-TIME.(html|txt) if($File::Find::name =~ m!^$inDir(?:/)?(.*?)/(.*?)/(.*?)/(\d{4})-(\d{2})-(\d{2})\.(\d{4})(\d{2}).(html|txt)!) { my ($proto,$acct,$contact,$year,$month,$day,$hour,$seconds,$ext) = ($1,$2,$3,$4,$5,$6,$7,$8,$9); return unless defined ($proto = $Protocols{lc $proto}); $foundLogs = 1; #Set the logs found flag my $outFN = "$contact ($year|$month|$day)."; $outFN .= ((lc $ext) eq "html") ? "html" : "adiumLog"; mkdir("$outDir/$proto.$acct"); mkdir("$outDir/$proto.$acct/$contact"); my $file = "$outDir/$proto.$acct/$contact/$outFN"; if(-e $file &amp;&amp; !$force) { # print(($adiumUser?"$adiumUser already has":"There already exists"), # " a log from $proto.$acct to $contact on $day/$month/$year.\n"); `cat '$File::Find::name' &gt;&gt; '$file'`; } else { copy($File::Find::name,$file); } `touch -t $year$month$day$hour.$seconds '$file'`; } } #Sort a list of log files by time sub sort_logs { my @files = @_; return sort logcmp @files; } sub logcmp { my ($t1,$t2); $t1 = $&amp; if $a =~ /\d{6}/; $t2 = $&amp; if $b =~ /\d{6}/; return 0 unless defined($t1) &amp;&amp; defined($t2); return $t1 &lt;=&gt; $t2; } GetOptions( "adiumUser=s" =&gt; \$adiumUser, "inDir=s" =&gt; \$inDir, "outDir=s" =&gt; \$outDir, "yes" =&gt; \$force, "help" =&gt; \$help) or usage(); usage() if $help; usage("You must supply at most one of adiumUser and outDir") if defined($outDir) &amp;&amp; defined($adiumUser); $outDir ||= "$ENV{HOME}/Library/Application Support/Adium 2.0/Users/$adiumUser/Logs" if defined $adiumUser; $outDir ||= "$ENV{PWD}/Logs"; $inDir ||= shift; $inDir ||= "$ENV{HOME}/.gaim/logs"; print "NOTE: Output directory exists, existing logs will be appended to.\n" if(-d $outDir); mkdir($outDir) unless -e $outDir; usage("Output dir must be a directory") unless -d $outDir; usage("Output dir must be writeable") unless -w $outDir; usage("Input directory '$inDir' does not exist") unless -d $inDir; usage("Input directory '$inDir' is not readable") unless -r $inDir; #Spider the logs dir find({wanted =&gt; \&amp;process_log, preprocess =&gt; \&amp;sort_logs}, $inDir); #Warn if we didn't find any logs unless($foundLogs) { print "Warning: No recognized logs found.\n"; print "Note:\tThis script only supports logs generated by gaim 0.73 and above.\n"; print "\tYou may be able to update older gaim logs to the new format using the script from\n"; print "\thttp://sourceforge.net/forum/message.php?msg_id=2392758\n"; exit(1); } exit(0); </code></pre>
Disabling msgbox in access <p>I am trying to make a small form in MS Access 2003 SP3, I use some function that some other people made and these function has msgbox in it. I would like to disable msgbox while I am running the form. Is it possible in Access to disable msgbox?</p>
<p>I created my finction called msgbox. Seems like its working. Thanks everyone for your help.</p> <pre><code>Public Function MsgBox(Prompt, Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title, Optional HelpFile, Optional Context) As VbMsgBoxResult If myProcedureisRunning then VBA.MsgBox Prompt else debug.print prompt endif End Function </code></pre>
Split old .NET code into designer partial class <p>I'm working on an older .NET code base that has all the designer code stuffed into the same code file as my code (pre - partial classes).</p> <p>Is there a mechanism to tell Visual Studio 2008 to go back and refactor designer code into a X.designer.cs partial class file?</p>
<p>What I just did was completely manually:</p> <ol> <li>Create <em>yourform</em>.Designer.cs</li> <li>Add it to Visual Studio (right click, add existing item)</li> <li>Add the <em>partial</em> keyword to your existing class.</li> <li>Add the <em>namespace</em> <strong>exactly like in the original cs</strong> to the <em>yourform</em>.designer.cs</li> <li>Inside this namespace, add the <em>class</em> definition (don't forget to include the <em>partial</em> keyword). <strong>Do not</strong> add inheritance and/or interfaces to this partial class in Designer.cs.</li> <li>After this is done, you're ready to <em>cut</em> and <em>paste</em> the following: </li> </ol> <p>a) Remove the <em>components</em> object you might have in your original Winform. If the application was .NET 1.1 you will have something like this:</p> <pre><code> /// &lt;summary&gt; /// Required designer variable. /// &lt;/summary&gt; private Container components = null; </code></pre> <p>b) Add a new <em>components</em> object in the Designer class:</p> <pre><code> /// &lt;summary&gt; /// Required designer variable. /// &lt;/summary&gt; private System.ComponentModel.IContainer components = null; </code></pre> <p>c) Unless you had a <em>specific</em> dispose method, this is the standard. If you don't have any form Inheritance, I think that base.Dispose can be safety removed:</p> <pre><code> /// &lt;summary&gt; /// Clean up any resources being used. /// &lt;/summary&gt; /// &lt;param name="disposing"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt; protected override void Dispose( bool disposing ) { if ( disposing &amp;&amp; ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } </code></pre> <p>d) Copy <strong>all</strong> the code inside the <strong>#region Windows Form Designer generated code</strong> to the new Designer.cs class. </p> <p>e) You should also copy <strong>all</strong> the member variables for all your objects (labels, texboxes, etc. that you use in the designer).</p> <p>That should be all about it. Save and compile. </p> <h2>Remember that a partial class can be split among N number of files, but all must share the SAME namespace.</h2> <p>Is it worthwhile? Well, in my case, I had a bunch of <strong>huge</strong> winforms with tons of code and controls. VS2008 crawled every time I switched from/to designer. This made the code view more responsive. I remember having to wait for 3-5 seconds before having a responsive code. Now it takes 1…</p> <hr> <h2>UPDATE:</h2> <p>Doing steps 1 to 5 and moving an existing or adding a new control won't automatically move anything to the designer.cs class. New stuff goes to the new Designer class, but old stuff remains where it was, unfortunately. </p> <p>You also have to <em>close</em> and reopen the file (after you have added/created the partial class) for VS to draw correctly in the Designer; failure to do may result in empty forms being drawn.</p>
WPF: XAML Custom Namespace <p>Okay so I have a Window in WPF. I add the following line inside of it:</p> <pre><code>xmlns:controls="clr-namespace:mCubed.Controls" </code></pre> <p>This compiles and runs just fine, but the Visual Studio designer gives me this error:</p> <blockquote> <p>Could not load file or assembly 'mCubed, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.</p> </blockquote> <p>When I remove this line from the Window, it compiles and runs just fine and the Visual Studio designer works like a charm!</p> <p>I'm confused as to why that one line breaks the designer? This occurs <strong><em>REGARDLESS</em></strong> if I have put the following line in the body of the XAML document.</p> <pre><code>&lt;controls:MyControl/&gt; </code></pre> <p>All my .cs files are in the same VS project. I have a mCubed namespace which contains my cleverly named mCubedWindow class. I have all my controls classes defined in the mCubed.Controls namespace. Do NOT tell me this is an assembly problem, ALL MY FILES ARE IN THE SAME VS PROJECT!</p>
<p>Not an assembly problem, just a designer problem. The VS WPF designer in 2008 is primitive at best - completely useless IMHO. I turn it off completely and use the XML editor instead. Hopefully things will improve drastically in 2010.</p>
.NET setup projects using Visual Studio 2008 <p>When you create a Setup project for a Windows/Console application, you find that there are two outputs.</p> <ol> <li>Setup.exe</li> <li>.msi</li> </ol> <p>What does setup.exe and <em>.MSI</em> do? Which one should be used for installation?</p> <p>I have seen that I can install the application using both. But Setup.exe is fairly small file compared to the <em>.MSI</em> file. </p> <p><strong>Questions</strong></p> <ol> <li><p>If I have to ship to the client. I cannot send two files. What's the best approach to merge these two files into one Setup file? </p></li> <li><p>I have read that Setup.exe is a bootstrapper which checks the .NET framework and then calls the .MSI file. Is it correct?</p></li> <li><p>I couldn't test for the unavailability of .NET framework because I'm a .NET developer and also my team works on .NET and have .NET installed. I didn't want to risk the Visual Studio by uninstalling the .NET framework and testing the setup application. </p></li> </ol> <p>How does it install .NET framework? It is 200 MB odd, but my setup is less than 3 MB. </p> <p>Does it give a option to download or something?</p> <p>Any help appreciated.</p> <p>Thanks,</p>
<p>The MSI is the installer for you application. The setup file is a bootstrap that will check for pre-reqs. Like correct version of the windows installer. I think it is also the setup.exe that will allow download of the right version of the .NET framework. You can use the .MSI on its own, you can't use just the setup.exe.</p> <p>You are correct that the setup allows the download of the correct version of .NET framework.</p> <p>There are ways to merge the MSI and the Setup.exe to create a single exe. Things like a self-extracting zip or iexpress.</p> <p>Why can't you send them both files though? I think if you publish the setup and msi on a server for download the setup will find and download your MSI when it is required.</p>
Encoding of string returned by GetUserName() <p>How do I get the encoding that is used for the string returned by <code>GetUserName</code> from the win32 API? I'm using pywin32 and it returns an 8-bit string. On my German XP, this string is obviously encoded using Latin-1, but this might not be the case for other Windows installations.</p> <p>I could use <code>GetUserNameW</code>, but I would have to wrap that myself using ctypes, which I'd like to avoid for now if there is a simpler solution.</p>
<p>You can call <a href="http://msdn.microsoft.com/en-us/library/dd318070%28VS.85%29.aspx">GetACP</a> to find the current ANSI codepage, which is what non-Unicode APIs use. You can also use <a href="http://msdn.microsoft.com/en-us/library/bb202786.aspx">MultiByteToWideChar</a>, and pass zero as the codepage (CP_ACP is defined as zero in the Windows headers) to convert a codepage string to Unicode.</p>
Custom scrollbars <p>I'm working on making an application with adobe air and I have a div that uses overflow-y. In order for the UI to look nice and sexy, what's the best way to replace the ugly <a href="http://grabup.nakedsteve.com/a0fd084a9117dc8b1fe6626eda535d98.png" rel="nofollow">default scrollbar</a> [link broken] with a creation of my own?</p> <p>Thanks</p> <p>EDIT: Everyone remember that this is on adobe air, not on a browser (I know better than to to mess with a scrollbar, that's way web -4.2)</p>
<p>Don't.</p> <p>Users know how to to use the default platform UI widgets: they know what they look like, how they behave, etc. And the platform ones work really well.</p> <p>They won't know how to use your widget. And even if you try and copy the platform one except for appearance, your widget will behave as a cheap knockoff; it will be missing features the user expects:</p> <ul> <li>Does your scroll thumb grow/shrink to show the length of the document, with a minimum size such that its always grab-able — but only on platforms where that is expected?</li> <li>Does middle-click scroll to the position clicked, left-click scroll down only, and right-click scroll up only, and each in proportion to where clicked on the scrollbar — on the platform where this is expected?</li> <li>Does clicking in the blank space between the thumb and up or down arrow work? Does it scroll by the amount the user is expecting, which varies by platform?</li> <li>Does scrolling go at the speed the user expects when the scroll buttons are held down?</li> <li>How is the user dragging the thumb handled when the mouse goes outside the scrollbar? Or middle-click, on the before-mentioned platform.</li> <li>Does your custom scroll bar follow the visual theme the user selected e.g., because he needs extra-high-contrast and/or extra-large widgets due to disability?</li> </ul> <p>The answer to most of those is probably "no". At least, that's been my experience with web sites where the designer decided the platform scroll bars aren't cute enough.</p>
xPath Traversing <p>I am trying to use xPath to traverse through the code of a newspaper (for the sake of practice) right now I'd like to get the main article, it's picture and the small description I get of it. But I'm not that skilled in xPath so far and I can't get to the small description.</p> <p>withing this code:</p> <pre><code>&lt;div class="margenesPortlet"&gt; &lt;div class="fondoprincipal"&gt; &lt;div class="margenesPortlet"&gt; &lt;a href='notas/n1092329.htm' &gt;&lt;img id="LinkNotaA1_Foto" src="http://i.oem.com.mx/5cfaf266-bb93-436c-82bc-b60a78d21fb6.jpg" height="250" width="300" border="0" /&gt;&lt;/a&gt; &lt;div class="piefoto_esto"&gt;Un tubo de 12 pulgadas al lado de la Vialidad Sacramento que provoc&amp;#243; el corte del servicio durante toda la ma&amp;#241;ana y hasta alrededor de las cuatro de la tarde. Foto: El Heraldo de Chihuahua&lt;/div&gt; &lt;div class="cabezaprincesto"&gt;&lt;a href='notas/n1092329.htm' class='cabezaprincesto' &gt;Sin agua 8 mil usuarios&lt;/a&gt;&lt;/div&gt; &lt;div class="resumenesto"&gt;&lt;a href='notas/n1092329.htm' class='resumenesto' &gt;La ruptura de una l&amp;#237;nea en el tanque de rebombeo de agua Sacramento dej&amp;#243; sin servicio a ocho mil usuarios, en once colonias del sur de la ciudad. &lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I've want to get the picture (with or without caption) and then the title of the article. These 3 things I can get by using: </p> <p>//div[@class='fondoprincipal'] &lt;-- gives me the main image and caption</p> <p>//a[@class='cabezaprincesto']/text() &lt;-- gives me the article's title</p> <p>but I can't get ahold of the small description which is the div with class="resumenesto", I haven't tried getting anything by that id because the same id is used over and over through the rest of the HTML so it returns lots of extra items.</p> <p>How can I get this particular one? and then would any of you recommend me a good way of parsing it to another webpage? I was thinking maybe php writing some html using those values but I'm not sure really...</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>What I mean by "this particular one" is how do I get this div class="resumenesto", the one residing within div class="fondoprincipal"...</p> <p><hr /></p> <p><strong>Edit 2</strong></p> <p>Thank you, now xPath Traversing is a little bit more clear. But then about my second question, would any of you recommend me a good way of parsing it to another webpage? I was thinking maybe php writing some html using those values but I'm not sure really..</p>
<p>You say "id" of resumenesto, but in your code example the div you're talking about has a class of resumenesto.</p> <p>Further, when you use an xpath of something like this:</p> <pre><code>//div[@class='resumenesto'] </code></pre> <p>What you're getting is a list of nodes matching that xpath. So if you want to specifically refer only to a single item in that list, you need to specify which item in the list:</p> <pre><code>//div[@class='resumenesto'][1] </code></pre> <p>Further, what do you mean by "this particular one"? The only way to tell xpath specificity is to give it context, for instance "the div with class resumenesto that resides within some other div", or "the first of the divs with class resumenesto".</p> <p>Read <a href="http://www.w3schools.com/xsl/xpath_syntax.asp" rel="nofollow">W3Schools' overview of XPath syntax</a> for some more info.</p> <p>Edit:</p> <p>To get the div residing within "fondoprincipal":</p> <pre><code>//div[@class='fondoprincipal']//div[@class='resumenesto'] </code></pre> <p>This tells xpath to find any descendant div with class fondoprincipal within the document, and within that div, find any descendant div with class resumenesto.</p>
Fluent Nhibernate and pluggable inheritance <p>Is there any way to define/expand inheritance without changing base table mapping with Fluent NHibernate? For example with Castle.ActiveRecord (based on NHibernate) you can define inheritance like this:</p> <pre><code>[ActiveRecord("entity"), JoinedBase] public class Entity : ActiveRecordBase { [PrimaryKey] public int Id { get; set; } } [ActiveRecord("entitycompany")] public class CompanyEntity : Entity { [JoinedKey("comp_id")] public int CompId { get; set; } } </code></pre> <ul> <li>It's possible to add or remove new subclasses without changing base entity mappings.</li> <li>When we call <code>Entity.FindAll()</code> it returns all entities (also those inherited).</li> </ul>
<p>Not right now, no. Certainly not in any way that will require <em>no</em> modifications to your parent class map.</p>
Programmatically printing directory of word documents... last file always skipped <p>I am having a problem when trying to programmatically print a directory of word documents. In this example, I am trying to print only the files with the "3_" prefix. The problem is that the file does not print unless there are two files with the 3_ prefix. I have been looking around forever to figure this problem out. Is there something wrong with the way I am opening the file? It works only when there are two files in the directory, in which case it will print out only one of the two files.</p> <p>Edit: I did try a messagebox and the path is correct. The filename is correct. Also, if I am watching the printer in the printers folder, a document will flash up for a brief second and then disappear ( I have printing paused so that I can see the output). If word is giving me an error, why doesn't it show? And why does this work if there are two files in the directory with the 3_ prefix?</p> <p>Edit: I think it is a problem with the printout() method. When I set the app to visible and run it, the document opens fine, but nothing is printed. I can open the document manually and print (which works fine).</p> <p>Edit: Thank you all for the answers. The background parameter in the printout() method was the issue. The program would quit before printing could fully spool (which is why I would see a document flash in the print queue and disappear. Turning background printing off required the document to stay open and print, which was key. Thank you</p> <pre><code>string[] filesToCheck = Directory.GetFiles(clientDirectoryPath); Object filename = null; for (int i = 0; i &lt; filesToCheck.Count();i++ ) { if(filesToCheck[i].Contains("3_")) { filename = filesToCheck[i]; wrdDoc = wrdApp.Documents.Open(ref filename, ref oMissing, ref oTrue, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); wrdDoc.PageSetup.FirstPageTray = letterHeadTray; wrdDoc.PageSetup.OtherPagesTray = defaultTray; wrdDoc.PrintOut(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing); wrdDoc = null; } } </code></pre>
<p>Try and set the Background parameter (1st param) of the <a href="http://msdn.microsoft.com/en-us/library/bb237242.aspx" rel="nofollow">PrintOut</a>() call to False.</p> <p>Probably the last print job is not completely spooled and canceled since the Word COM object is released too early.</p>
Displaying PDFs in Silverlight <p>I want to make a PDF document reader, and the only thing I've found to help me is "Amyuni PDF Suite" that will turn the PDF into XAML and stream that. Are there any other controls for displaying PDFs in Silverlight? Or could I add an IFrame into Silverlight and let the client render it?</p> <p>Cheers</p> <p>Nik</p>
<blockquote> <p>Or could I add an IFrame into Silverlight and let the client render it?</p> </blockquote> <p>Silverlight doesn't really have that capability. You can make your Silverlight control transparent, and have an HTML div block that sits above your Silverlight control, which you could then load a PDF in, but as for displaying a PDF within Silverlight, I think you're out of luck.</p> <p><strong>Edit:</strong> <a href="http://silverlight.net/forums/t/21927.aspx" rel="nofollow">This question</a> has some info on how to accomplish transparent Silverlight controls, I hope it helps!</p>
ConvertEmptyStringToNull property <p>A) public void GetEmployee( int EmployeeID );</p> <pre><code>&lt;asp:ObjectDataSource SelectMethod=”GetEmployee” …&gt; &lt;SelectParameters&gt; &lt;asp:ControlParameter Name = ”EmployeeID” ...&gt; &lt;/SelectParameters&gt; </code></pre> <p><br /></p> <p>If for whatever reason EmployeeID parameter is NULL, ObjectDataSource will convert Null to zero and passed it as argument to GetEmployee() method.</p> <p>Why does runtime make such a conversion? Wouldn't throwing an exception made more sense? <br /><br /></p> <p>B) “Use the ConvertEmptyStringToNull property to specify whether an empty string value is automatically converted to null when the data field is updated in the data source.” <br /> I don’t quite understand the usefulness of this property. Why would empty string indicate that we want null to be inserted into source’s data field? I’d assume that this data field is of type String? Then why not also have ConvertZeroInt32ToNull etc?</p> <p>bye</p>
<p>A) It appears that the ODS is generating the default value for null of type T. In the case of an int, the default value is a 0.</p> <p>B) There is no way in HTML to represent a null value via an input tag. When an emptry string is passed to an ODS and Convert Empty to Null is set to true, a null value will be set. There is no ConvertZeroToNull property since all textbox data on an HTML or Windows form is of type string.</p>
Displaying a URL in a UITableViewCell in a different color from the rest of the text <p>I'm working through the Stanford iPhone programming course online. The Presence app assignment pulls Twitter and displays each one in a separate UITableViewCell.</p> <p>Updates often include URL's and I'd like to know how to display just the URL text in blue, having it be tappable. I can parse the text for URL's with no problem, just no idea how to display the URL itself.</p> <p>Any advice or suggestions would be greatly appreciated.</p>
<p>As said above a button would work, but in terms of the UI it would probably look more natural if you had a label.</p> <p>Alternatively, you could fill the UITableViewCell with a UIWebView. The UIWebView would hold all the text and you should easily be able to set part of the text as a link (color blue) using html.</p>
Ampersand (&) operator in a SQL Server WHERE Clause <p>Sorry for the very basic question. What does the <code>&amp;</code> operator do in this SQL</p> <pre><code>WHERE (sc.Attributes &amp; 1) = 0 </code></pre> <p><code>sc</code> is an alias for a table which contains a column <code>attributes</code>.</p> <p>I'm trying to understand some SQL in a report and that line is making it return 0 entries. If I comment it out it works. I have limited SQL knowledge and I'm not sure what the <code>&amp; 1</code> is doing.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms174965.aspx">&amp; is the bitwise logical and operator</a> - It performs the operation on 2 integer values. </p> <pre><code>WHERE (sc.Attributes &amp; 1) = 0 </code></pre> <p>The above code checks to see if sc.Attributes is an even number. Which is the same as saying that the first bit is not set. </p> <p>Because of the name of the column though: "Attributes", then the "1" value is probably just some flag that has some external meaning. </p> <p>It is common to use 1 binary digit for each flag stored in a number for attributes. So to test for the first bit you use sc.Attributes&amp;1, to test for the second you use sc.Attributes&amp;2, to test for the third you use sc.Attributes&amp;4, to test for the fourth you use sc.Attributes&amp;8, ...</p> <p>The = 0 part is testing to see if the first bit is NOT set. </p> <p>Some binary examples: (== to show the result of the operation)</p> <pre><code>//Check if the first bit is set, same as sc.Attributes&amp;1 11111111 &amp; 00000001 == 1 11111110 &amp; 00000001 == 0 00000001 &amp; 00000001 == 1 //Check if the third bit is set, same as sc.Attributes&amp;4 11111111 &amp; 00000100 == 1 11111011 &amp; 00000100 == 0 00000100 &amp; 00000100 == 1 </code></pre>
How do can you make redirect_to use a different HTTP request? <p>At the end of one of my controller actions I need to redirect to a page that only accepts put requests. I have been trying to figure out how to get redirect_to to use a put request but to no success. </p> <p>Is this possible? Or is there another way to accomplish this?</p>
<p>I don't think you are able to do this, and I suspect that the limitation is part of HTTP itself.</p> <p>When using <strong>redirect_to</strong> - the redirection happens as a "302 Moved" header unless otherwise specified in the parameters.</p> <p>Having a look at the HTTP Spec itself doesn't reveal any way to change the type of request the browser makes via redirect.</p> <p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3">HTTP Redirects</a>:</p> <blockquote> <p>This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD.</p> </blockquote> <p>I think you may need to use JavaScript to achieve this functionality, or perhaps rethink the flow of control in your application. </p>
jQuery getTime function <p>is it possible to create a jQuery function so that it gets current date and time? I've been looking around documentation but haven't found anything so far...</p>
<p>@nickf's correct. However, to be a little more precise:</p> <pre><code>// if you try to print it, it will return something like: // Sat Mar 21 2009 20:13:07 GMT-0400 (Eastern Daylight Time) // This time comes from the user's machine. var myDate = new Date(); </code></pre> <p>So if you want to display it as mm/dd/yyyy, you would do this:</p> <pre><code>var displayDate = (myDate.getMonth()+1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear(); </code></pre> <p>Check out the <a href="http://www.w3schools.com/jsref/jsref%5Fobj%5Fdate.asp">full reference</a> of the Date object. Unfortunately it is not nearly as nice to print out various formats as it is with other server-side languages. For this reason <a href="http://blog.stevenlevithan.com/archives/date-time-format">there</a>-<a href="http://jacwright.com/projects/javascript/date%5Fformat">are</a>-<a href="http://www.webdevelopersnotes.com/tips/html/10%5Fways%5Fto%5Fformat%5Ftime%5Fand%5Fdate%5Fusing%5Fjavascript.php3">many</a>-<a href="http://www.codeproject.com/KB/scripting/dateformat.aspx">functions</a> available in the wild. </p>
Crash when calling stringByEvaluatingJavaScriptFromString on UIWebView from button <p>I can't find any documentation to confirm this, but it appears that you can only call the method <strong>stringByEvaluatingJavaScriptFromString</strong> in overridden methods from a UIWebView delegate. Can anyone confirm this?</p> <p>Here's what I've tried. I setup a button on a view, link it to a method on my viewcontroller, and make sure it works fine. My view has a UIWebView control on it as well. If I run the project on the simulator or on the iPhone, there are no issues. Then I add this code to the button's method.</p> <pre><code>[theWebView stringByEvaluatingJavaScriptFromString:@"alert('Hi there!');"]; </code></pre> <p>When I run the project, I can click the button and see the 'Hi there' prompt and I can click OK to dismiss it. Usually 4-5 seconds later the simulator crashes. I occasionally see the <code>"__TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION__"</code> error, but not consistently; sometimes there's no error. It also doesn't always crash the first time. Sometimes I go to another page, and then try it again, and it crashes.</p> <p>If I put the same code in the webPageDidFinishLoad event it works fine. But I'd like the code to be called when the user demands it so that event doesn't suit my needs.</p> <p>I'm open to a workaround if you have any ideas? Thanks in advance!</p>
<p>I still don't know the exact reason this didn't work, but I found I could rewrite my code to get called during the UIWebView delegate methods instead.</p>
Default form submit behavior after jQuery forms.js ajaxSubmit executes <p>I'm using the jQuery Form Plugin to bind the submit events for two forms on the same page so that they are submitted to separate PHP scripts that return markup to separate divs on the page.</p> <p>One form refreshes the next. I use "live" so each form has its events re-bound when it is refreshed:</p> <pre><code>$(document).ready(function() { /* Form 1 */ $('#frmSearch').live('submit', function() { $(this).ajaxSubmit({ target: '#divResults', url: 'search_div.php' }); return false; }); /* Form 2 */ $('#frmResults').live('submit', function() { $(this).ajaxSubmit({ target: '#divLookup', url: 'lookup_div.php', }); return false; }); }); </code></pre> <p>So far so good. Each form can be submitted again and again with ajax and all the bindings survive from one submit to the next.</p> <p>The problem arises when I try to bind a third form and fire its submit event in the "success" option of the second form:</p> <pre><code>/* Form 2 */ $('#frmResults').live('submit', function() { $(this).ajaxSubmit({ target: '#divLookup', url: 'lookup_div.php', success: function(responseText){ $('#frmLookup').submit(); } }); return false; }); /* Form 3 */ $('#frmLookup').live('submit', function() { $(this).ajaxSubmit({ target: '#divMappings', url: 'mapped_items_div.php', }); return false; }); </code></pre> <p>When I do this, the ajaxSubmit successfully executes but then the form's default submit is performed as well, causing the page to reload. Notice that I do include the "return false;" to suppress the form's default submit, but for some reason it submits anyway.</p> <p>I've found that if I "bind" on Form 3's "submit" event in Form 2's success function with the same options as the "live" for Form 3, the form's default submit is not performed. This is redundant, though, and if I can I would like to avoid doing it.</p> <p>How can I suppress Form 3's default submit behaviors?</p>
<p>Not sure if it's related to your problem, but <a href="http://docs.jquery.com/Events/live" rel="nofollow"><code>live()</code> does not support the "<code>submit</code>" event</a>:</p> <blockquote> <p>Currently not supported: <code>blur, focus, mouseenter, mouseleave, change, submit</code></p> </blockquote>
How to publish an application in Visual Studio? <p>I'm working on a small console application in Visual Studio C++ 2008 and would like to make an installer that I can distribute to a few friends to test the application. I recall a publish option being under the build menu, but it is not there now. Could I somehow have turned this feature off?</p> <p>Is there a simple way to publish such that my application will be relatively independent of Windows Version?</p> <p>Thanks,</p> <p>Nerf42</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms235317.aspx" rel="nofollow">Deploying Your Program (C++)</a></p>
Managing Unregistered User Posts by Screening <p>I am considering allowing users to post to my site without having them register or provide any identifying information. If each post is sent to a db queue and I then manually screen these posts, what sort of issues might I run into? How might I handle those issues?</p>
<p>Screening every post would be tedious and tiresome. And prone to annoying admin spam. My suggestion would be to automate as much of screening as possible. And besides, providing any identifying information does nothing to prevent spam (a bot will just generate it).</p> <p>A lot of projects implement recognition system: first the user has to post 1-2 posts that are approved, then by IP and (maybe) a cookie he's identified as a trusted poster, so his posts appear automatically (and later can be marked as spam).</p> <p>Also some heuristics on the content of the post could be used (like amount of links in the post) to automatically discard potential spam posts.</p>
Application to reverse engineer MySQL & PostgreSQL DB? <p>Is there an application to reverse engineer an existing database in mysql and/or postgre? </p> <p>I'm interested in obtaining the DB diagram from an existing one, similar as it can be done in MSSQL Server</p>
<p>For MySQL, try <a href="http://dev.mysql.com/workbench/" rel="nofollow">MySQL Workbench</a>.</p> <p>For both MySQL and PostgreSQL, try <a href="http://www.casestudio.com/enu/reverse.aspx" rel="nofollow">TOAD Data Modeler</a>.</p> <p>If you use the open-source diagram app <a href="http://live.gnome.org/Dia" rel="nofollow">Dia</a>, there are <a href="http://wiki.gnome.org/Apps/Dia/Links" rel="nofollow">several tools</a> to generate Dia diagrams from SQL databases including MySQL and PostgreSQL.</p> <hr> <p><strong>update:</strong> MySQL Workbench 5.2 supports reverse-engineering diagrams from a live database in addition to an SQL script. MySQL Workbench 5.2 just <a href="http://wb.mysql.com/?p=569" rel="nofollow">announced</a> their Release Candidate 1 (as of 5/12/2010).</p>
Move all files except one <p>How can I move all files except one? I am looking for something like: </p> <pre><code>'mv ~/Linux/Old/!Tux.png ~/Linux/New/' </code></pre> <p>where I move old stuff to new stuff -folder except <code>Tux.png</code>. !-sign represents a negation. Is there some tool for the job?</p>
<p>If you use bash and have the <code>extglob</code> shell option set (which is usually the case):</p> <pre><code>mv ~/Linux/Old/!(Tux.png) ~/Linux/New/ </code></pre>
Threading in .net <p>I have a simple example of a winforms application where i choose a directory in a directory chooser and click a button to loop through the directory and copy each file in the directory into another directory.</p> <p>i want to do the file copy on a background thread to avoid locking the GUI.</p> <p>i am looking for the simplest solution to:</p> <ol> <li>Create the background thread</li> <li>Pass the source and destinations in</li> <li>Get a callback on progress so i can show a progress bar on the GUI thread</li> </ol>
<p>I would recommend using the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28VS.80%29.aspx" rel="nofollow">BackgroundWorker</a> class.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx" rel="nofollow">Example</a>.</p>
Mac 10.4 Sync Files <p>I am using Google code svn and have a repository setup. Inside the repository I am including TinyMCE and now I want to upgrade all the files in this folder. The problem I am having is if I checkout locally and then download their new version and replace the folder it wipes out all my svn files. So in effect removes it from version control. </p> <p>I was wondering what is the best method to update those folders &amp; files but keep the svn files intact? I have been searching but can't seem to locate any simple method. </p>
<p>What you may want is to setup <a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html" rel="nofollow">svn:externals</a>, or you may also want to take a look at something like <a href="http://piston.rubyforge.org/index.html" rel="nofollow">Piston</a>.</p>
Class in the BCL that will event at a given DateTime? <p>Is there an object that will event at a given DateTime or DateTimeOffset? I am using a Timer to do this operation now but it requires a bit of calculation on my part, was just thinking there might already be something in place.</p>
<p>I don't see how you have to do any calculation:</p> <pre><code>public void StartTimer(DateTime target) { double msec = (target - DateTime.Now).TotalMilliseconds; if (msec &lt;= 0 || msec &gt; int.MaxValue) throw new ArgumentOutOfRangeException(); timer1.Interval = (int)msec; timer1.Enabled = true; } </code></pre>
What is IDL? <p>What is meant by IDL? I have googled it, and found out it stands for Interface Definition Language, which is used for interface definition for components. But, in practice, what is the purpose of IDL? Does Microsoft use it?</p>
<p>An interface definition language (IDL) is used to set up communications between clients and servers in remote procedure calls (RPC). There have been many variations of this such as Sun RPC, ONC RPC, DCE RPC and so on.</p> <p>Basically, you use an IDL to specify the interface between client and server so that the RPC mechanism can create the code stubs required to call functions across the network.</p> <p>RPC needs to create stub functions for the client and a server, using the IDL information. It's very similar to a function prototype in C but the end result is slightly different, such as:</p> <pre><code>+----------------+ | Client | | +----------+ | +---------------+ | | main | | | Server | | |----------| | | +----------+ | | | stub_cli |-------&gt;| stub_svr | | | +----------+ | | |----------| | +----------------+ | | function | | | +----------+ | +---------------+ </code></pre> <p>In this example, instead of calling <code>function</code> in the same program, <code>main</code> calls a client stub function (with the same prototype as <code>function</code>) which is responsible for packaging up the information and getting it across the wire to another process. This can be the same machine or a different machine, it doesn't really matter - one of the advantages of RPC is to be able to move servers around at will.</p> <p>In the server, there's a 'listener' process that will receive that information and pass it to the server. The server's stub receives the information, unpacks it and passes it to the real function.</p> <p>The real function then does what it needs to and returns to the server stub which can package up the return information (both return code and any <code>[out]</code> or <code>[in,out]</code> variables) and pass it back to the client stub.</p> <p>The client stub then unpacks that and passes it back to <code>main</code>.</p> <p>The actual details may differ a little but that explanation should be good enough for a conceptual overview.</p> <p>The actual IDL may look like:</p> <pre><code>[uuid(f9f6be21-fd32-5577-8f2d-0800132bd567), version(0), endpoint("ncadg_ip_udp:[1234]", "dds:[19]")] interface function_iface { [idempotent] void function( [in] int handle, [out] int *status ); } </code></pre> <p>All that stuff at the top is basically networking information, the meat of it is inside the interface section where the prototypes are shown. This allows the IDL compiler to build the x stub and x server functions for compiling and linking with your client and server code to get RPC working.</p> <p>Microsoft does use IDL (I think they have a MIDL compiler) for COM stuff. I've also used third party products with MS operating systems, both DCE and ONC RPC.</p>
Is there a standard place to put the version number in the source code? <p>I want to have one file where I can check which version is installed. Its a PHP program so you can look into the files. I was thinking if there is a standardized place to put it since in the Zend Framework or the HTMLpurifier I can't find the version number at all.</p> <p>I would also want to add it to the Zend Framework and HTMLPurifier if there is no standard location so I always know what version is installed. Having to update a txt file would be another alternative..</p> <p>EDIT: We are thinking of using PHPundercontrol in the very near future but why should it update the Zend Frameworks number? How should it know that I uploaded a new version of it?</p>
<p>I found it..</p> <p>in the Zend Framework they have a file called Zend/Version.php -> Zend_Version this file also has the Version number inside of it:</p> <pre><code>const VERSION = '1.7.5'; </code></pre> <p>In the HTMLPurifier it's located in HTMLPurifier/HTMLPurifier.php</p> <pre><code>/** Version of HTML Purifier */ public $version = '3.3.0'; /** Constant with version of HTML Purifier */ const VERSION = '3.3.0'; </code></pre> <p>I guess for mine I will add the version into a config file then.</p>
Root servers for web development - how much power is enough? <p>I think this question has not to do with programming in general, but nevertheless the answers might be interesting to other web developers.</p> <p>I just wondered how to estimate the minimum requirements to have a fast website. Obviously there are some facts that have to be considered like the expected number of visitors, the derived number of clicks per seconds and so on... Also running services like web servers (Apache/lighttpd) or mail servers (Exim, sendmail, ...) could end up in different needs.</p> <p>Maybe you know a good website or can give some explanations on how to estimate the needed server configuration from such information?</p>
<p>This is arguably more art than science.</p> <p>What you have to remember is that like many things in programming and IT, your website will be as slow as the slowest link in the chain, meaning you will have some bottleneck such as bandwidth, the Web servers, disk I/O, memory, your databases, your firewall, etc that will limit the speed of your Website.</p> <p>Tuning and growing your Web site will involve identifying those issues as you grow and addressing them. At one point you may need to add more RAM, at another you may need another CPU and so on. At other times adding more memory might be useless because memory isn't your problem.</p> <p>Likewise, lack of a certain resource can be masked, like lack of memory can be masked by intensive disk I/O as your system swaps (page faults) constantly but disk I/O isn't the problem.</p> <p>So what do you do?</p> <p>The first thing is you need to identify (or make a reasonable guess) as to what a typical user will do and how much they will do it. Ideally you will be able to model 100 or 1000 or however many users you need with software like JMeter to then get an idea of how your Website scales, how much bandwidth is going to be required and so on. By modelling 100, 500, 1000, 2000 users you will hopefully be able to see how linearly you Web site scales.</p> <p>You may find that supporting 1000 users requires 1 gig of RAM but 2000 requires 4 gigs: that's an example of non-linear scalability that expoes a problem you will have scaling your Web site up. And that's the kind of thing to be revealed by performance testing.</p> <p>Honestly though, hardware is so cheap these days that it's rarely a problem except for the biggest and most popular of sites ($10k can buy you 1 or even 2 servers with 16G of RAM and 4-8 cores each). Shared and VPS hosting are a different story because you'll typically only want to pay for however much memory, bandwidth and disk space you need. Luckily those kinds of solutions tend to alow you to upgrade pretty easily (at least to a point where you'll eventually have to go dedicating hosting).</p> <p>You can make some dirty estimates at the beginning of a project by doing what they call "back of the envelope" estimation. Run key queries say 100 times and work out hwo much CPU time they require, hit a mocked up page 100 times and work out how much bandwidth it generates and so on. These rough estimates combined with guesses about how users will use the site will give you a ballpark (hopefully within a factor of 2-3) of what you'll need.</p>
Cascading style sheets use "id" or "class" <p>when styling specific html elements, i tend to always use the class attribute. the css code looks cleaner imo.</p> <p>why do both exist which one should you use and when ?</p>
<p><strong>id</strong>s <strong>id</strong>entify elements. <strong>class</strong>es <strong>class</strong>ify elements.</p> <p>Put a class on an element if "it's a kind of ..." (e.g. address)</p> <p>Put an ID on an element if "it is <em>the</em> ..." (e.g. navigation)</p>
Read Data from 2 Lists into the Third List in MOSS 2007 <p>I got 2 lists displaying invoice details, now my boss wants to read specific field from these two lists into a third list, any help will from anybody out there? I'm new to SharePoint.</p>
<p>Are the two lists too big? if so you should take a look at the WSS upgrade API. It contains methods to do bulk copies; afterwards, the easiest way to transfer individual items is making an event receiver that listens to the itemAdded event.</p>
How do I get shoes executable into my path? <p>I'm getting started with shoes and the nks docs tell me two write a script and then launch it like this:</p> <pre><code>&gt; shoes myapp.rb </code></pre> <p>the shoes executable is in the Shoes.app I installed. Thus, shoes is not in my path so I can't do this.</p> <p>Tried symlinking shoes into /usr/local/bin but I get this error when I try to start it.</p> <pre><code>&gt; shoes myapp.rb FSPathMakeRef(/usr/local/bin/../../../Shoes.app) failed with error -43. </code></pre> <p>any ideas?</p> <p>Geoff</p> <p>PS. Additional information: OSX Leopard. Shoes version, Raisins. Installed from dmg. The link was made from and absolute path -> </p> <pre><code>&gt; sudo ln -s /Applications/Shoes.app/Contents/MacOS/shoes shoes </code></pre>
<p>You need to give an absolute path when making the symlink</p> <p>and you need to give the path inside the app bundle, such as <code>Shoes.app/Contents/MacOS/Shoes</code> maybe</p> <p>Edit:</p> <p>you could always add the following line to your .profile (assuming bash)</p> <pre><code>export PATH=$PATH:/Applications/Shoes.app/Contents/MacOS/ </code></pre> <p>although it's not a very nice solution</p> <p>Edit:</p> <pre><code>alias shoes=/Applications/Shoes.app/Contents/MacOS/shoes </code></pre> <p>may be a cleaner solution</p>
Trying to override formatting implementation of static method in compiled SDK <p>I am working with the Community Server framework.</p> <p>One of the provided form controls allows the user to update his/her 'status'. For example: 'Joe: is going to get coffee : 12:30am'.</p> <p>I want to change the format of that message before it goes into the database(goes in as formatted HTML). I want to take out the ":" character between the name and the message - or perhaps do other formatting.</p> <p>The formatting is completed via the 'UpdateStatusMessageForm' instantiating 'ActivityMessage' type with the status message the user entered. 'ActivityMessage' calls it's formatting method seen below:</p> <pre><code>public static string GetFormat(IActivityMessage message, string timeCssClass) { return string.Format("&lt;a href=\"{0}\"&gt;{1}&lt;/a&gt;: {2} &lt;span class='{3}'&gt;{4}&lt;/span&gt;", SiteUrls.Instance().UserProfile(message.Author.Username), message.Author.DisplayName, message.Body, timeCssClass, Formatter.FormatTime(message.DateCreated)); } </code></pre> <p>How can I change the implementation of that method if I can't override it? Any suggestions? Thanks!</p>
<p>The short answer is you can't override a static method.</p> <p>The long answer and some workarounds are in <a href="http://blogs.msdn.com/kirillosenkov/archive/2008/02/06/how-to-override-static-methods.aspx" rel="nofollow">this article</a> </p>
Performance of inner join compared to cross join <p>The effect of issuing an inner join is the same as stating a cross join with the join condition in the WHERE-clause. I noticed that many people in my company use cross joins, where I would use inner joins. I didn't notice any significant performance gain after changing some of these queries and was wondering if it was just a coincidence or if the DBMS optimizes such issues transparently (MySql in our case). And here a concrete example for discussion:</p> <pre><code>SELECT User.* FROM User, Address WHERE User.addressId = Address.id; SELECT User.* FROM User INNER JOIN Address ON (User.addressId = Address.id); </code></pre>
<p>Cross Joins produce results that consist of every combination of rows from two or more tables. That means if table A has 6 rows and table B has 3 rows, a cross join will result in 18 rows. There is no relationship established between the two tables – you literally just produce every possible combination.</p> <p>With an inner join, column values from one row of a table are combined with column values from another row of another (or the same) table to form a single row of data.</p> <p>If a WHERE clause is added to a cross join, it behaves as an inner join as the WHERE imposes a limiting factor.</p> <p>As long as your queries abide by common sense and vendor specific <a href="http://forge.mysql.com/wiki/Top10SQLPerformanceTips">performance guidelines</a>, I like to think of the decision on which type of join to use to be a simple matter of taste.</p>
How to get the lists of file and directory names of a site? <p>How exactly do you do this? The reason is my CMS has been breached, well, mainly because the username and password is fairly common (my bad). But I've always thought that it is save, since the directory name is pretty un-common and hard to guess (not the usual /cms/ or /admin/). Brute-forcing from a script? or maybe some Google tricks?</p> <p>update : my CMS is in PHP and I developed it myself. I don't remember putting the link to it everywhere, except once in email I sent to my friend via gmail.</p> <p>update 2 : as this could be used by some people to attack a site, please don't put any script in the answer. My intention is just to know the general ways to do it, so that I could prevent further attacks like this.</p> <p>Thanks in advance.</p>
<p>Did you ever surf somewhere via a link from your CMS? Your browser would have sent a referer (note the misspelling) header, indicating where you came from.</p>
Reference Access database dataset.designer file in WPF? <p>Hey, I've included an MS Access database in my WPF VB app, and I'm trying to link the data to an XCEED Datagrid. I have the following code in my testerDataSet.Designer.vb file which I assume is the funcion I should be referencing</p> <pre><code>Public ReadOnly Property Contact() As ContactDataTable Get Return Me.tableContact End Get End Property </code></pre> <p>I'm trying to get it to fill my datagirid using this</p> <pre><code> &lt;Grid.Resources&gt; &lt;xcdg:DataGridCollectionViewSource x:Key="cvs_contacts" Source="{Binding Path=Contact, *Source={x:Static testerDataSet}*}"/&gt; &lt;/Grid.Resources&gt; &lt;xcdg:DataGridControl Margin="54,18,4,3" Name="DataGridControl1" ItemsSource="{Binding Source={StaticResource cvs_contacts}}"/&gt; </code></pre> <p>Unfortunately the bolded/stared part is givi ng me errors, does anyone know the correct code i should be using here to reference my source?</p> <p>Thanks guys!</p> <p>EDIT: Okay let me try and outline what I've done... I've added an Access 2007 Database called "tester" to my project as an existing item, and VS has gone and made testerDataSet for me, and inside testerDataset.Designer.vb I assume the first code above is the code i need to display my table data.</p> <p>Basically my entire code for Window1.xaml is as follows (its just a test project to see If I can actually get the database working)</p> <pre><code>&lt;Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="369" Width="503" xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid"&gt; &lt;Grid&gt; &lt;Grid.Resources&gt; &lt;xcdg:DataGridCollectionViewSource x:Key="cvs_contacts" Source="{Binding Path=Contact, Source={StaticResource testerDataSet}}"/&gt; &lt;/Grid.Resources&gt; &lt;xcdg:DataGridControl Margin="54,18,4,3" Name="DataGridControl1" ItemsSource="{Binding Source={StaticResource cvs_contacts}}"/&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>What I'm trying to achieve is for the datagrid to display the data in the Contact datatable. I'm probably missing something important here (I'm quite new to coding =/ ) To be perfectly honest I've had a hard time finding appropriate tutorials for this so I'm not entirely sure what I'm doing </p> <p>THanks again</p>
<p>Can you update your sample to include the code for the static resource testerDataSet? </p> <p>One way you can try and work around this problem is to set the Binding directly in imperative code. </p> <pre><code>DataGridControl1.DataContext = testerDataSet.Contact </code></pre> <p>Then you could modify your WPF code to be the following</p> <pre><code>&lt;xcdg:DataGridControl Margin="54,18,4,3" Name="DataGridControl1" ItemsSource="{Binding}" /&gt; </code></pre> <p>That may not be 100% what you're looking for but it should at least temporarily unblock you.</p>
.NET Sample Project Design Patterns Fowler <p>Are there sample ASP.NET projects around using the patterns discussed in the book by Martin Fowler (<a href="http://rads.stackoverflow.com/amzn/click/0321127420" rel="nofollow">Patterns of Enterprise Application Architecture</a>)?</p> <p>I have downloaded the Northwind starters kit and Dinner Now, which are very good. Are there others that use things like Unit of Work, Repository, ...</p> <p>thx, Lieven Cardoen</p>
<p><a href="http://www.dofactory.com/Patterns/Patterns.aspx" rel="nofollow">dofactory.com</a> as C# and VB.NET GoF pattern examples. They also have a full ASP.NET web application example detailing the use of the patterns, although I don't think that is a free download.</p>
Is there a CalDAV client library for Java? <p>I want to communicate using CalDAV protocol with my calendar server. Are there any supported Java client libraries for this?</p>
<p>Try <a href="http://code.google.com/p/caldav4j/">CalDAV4j</a></p>
Using Eclipse Templates for Actionscript <p>One of my favorite features in Eclipse is the templates in PDT. In case you don't know what they are, think of writing "function" and having Eclipse write all the syntactical features and let you jump from variable to variable with a tap of the tab key. So I'm starting to do write AS3 in Eclipse and I miss having the templates at my fingertips. </p> <p>Is there a way I can configure templates in Eclipse for Actionscript development?</p>
<p>What Eclipse Plugin are you using for Actionscript ?</p> <p>I'm using FDT which includes templates (Prefereces>FDT>Editor>Templates).</p> <p>EDIT:</p> <p>It's not directly included in FLEX Builder. Here's a workaround (not tested) :</p> <p><a href="http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&amp;productId=2&amp;postId=13507" rel="nofollow">http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&amp;productId=2&amp;postId=13507</a></p>
Tips for managing a large number of files? <p>There are some very good questions here on SO about file management and storing within a large project.</p> <blockquote> <p><a href="http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay">Storing Images in DB - Yea or Nay?</a><br> <a href="http://stackoverflow.com/questions/662488/would-you-store-binary-data-in-database-or-in-file-system">Would you store binary data in database or in file system?</a></p> </blockquote> <p>The first one having some great insights and in my project i've decided to go the file route and not the DB route.</p> <p>A major point against using the filesystem is backup. But in our system we have a great backup scheme so i am not worried about that.</p> <p>The next path is how to store the actual files. And I've thought about having the files' location static at all times and create a virtual directory system in the database side of things. So links to the file don't change.</p> <p>The system i am building will have one global file management so all files are accessible to all users. But many that have gone the file route talk about physical directory size (if all the files are within one directory for example)</p> <p>So my question is, what are some tips or best practice methods in creating folders for these static files, or if i shouldn't go the virtual directory route at all.</p> <p>(the project is on the LAMP stack (PHP) if that helps at all)</p>
<p>One way is to assign a unique number to each file and use it to look up the actual file location. Then you an use that number to distribute files in different directories in the filesystem. For example you could use something like this scheme:</p> <p><code>/images/{0}/{1}/{2}</code></p> <blockquote> <p><code>{0}: file_number % 100</code><br /> <code>{1}: (file_number / 100) % 100</code><br /> <code>{2}: file_number</code></p> </blockquote>
QSortFilterProxyModel.mapToSource crashes. No info why <p>I have the following code:</p> <pre><code>proxy_index = self.log_list.filter_proxy_model.createIndex(index, COL_REV) model_index = self.log_list.filter_proxy_model.mapToSource(proxy_index) revno = self.log_list.model.data(model_index,QtCore.Qt.DisplayRole) self.setEditText(revno.toString()) </code></pre> <p>The code crashed on the second line. There is no exception raised. No trace back. No warnings. How do I fix this?</p>
<p>It may be that you're using the proxy model's createIndex() method incorrectly. Usually, the createIndex() method is called as part of a model's index() method implementation.</p> <p>Have you tried calling the proxy model's index() method to get a proxy index then mapping that to the source?</p> <p>Perhaps you could show the code in context or explain what you are trying to do.</p>
How do I add a space between two concatenated NSStrings? <p>I have three string objects:</p> <pre><code>NSString *firstName; NSString *lastName; NSString *fullName; </code></pre> <p>The values for <code>firstName</code> and <code>lastName</code> are received from NSTextFields.</p> <p>I then want to concatenate the two strings and place the result in <code>fullname.</code></p> <p>This is the code that I'm using:</p> <pre><code>fullName = [firstName stringByAppendingString:lastName]; </code></pre> <p>However, the result does not put a space between the two names (e.g. JohnSmith).</p> <p>How do I add in the space? I'd like the result to look like (John Smith).</p>
<p>I'm amazed by the length of the other answers:</p> <pre><code>fullname = [NSString stringWithFormat:@"%@ %@", firstname, lastname]; </code></pre>
Static extension methods on Seq module <p>According to <a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2008/09/10/object-oriented-f-extension-everything.aspx">this post</a>, F# supports extension methods on object instances and static classes. For example:</p> <pre><code>module CollectionExtensions = type System.Linq.Enumerable with static member RangeChar(first:char, last:char) = {first .. last} open ExtensionFSharp.CollectionExtensions </code></pre> <p>If I type <code>System.Linq.Enumerable.</code>, the static method <code>RangeChar</code> appears in my Intellisense window.</p> <p>I want to add a static method, <code>for_alli</code>, to the Seq module. I've modified the following code above as follows:</p> <pre><code>module SeqExtensions = type Microsoft.FSharp.Collections.Seq with (* error on this line *) static member for_alli f l = l |&gt; Seq.mapi (fun i x -&gt; i, x) |&gt; Seq.for_all (fun (i, x) -&gt; f i x) </code></pre> <p>Although both snippets of code have the same structure, <code>SeqExtensions</code> doesn't compile. F# highlights the word <code>Seq</code> and returns the error "The type 'Seq' is not defined".</p> <p><strong>How do I create static extension methods on Seq module?</strong></p>
<p>To extend an F# <em>module</em>, just create another module with the same name:</p> <pre><code>module Seq = let myMap f s = seq { for x in s do yield f x } Seq. // see your stuff here alongside normal stuff </code></pre>
how to find a loop in the file system? <p>how to find a loop in the file system in Linux? i am indexing all files for making search fast(O(1))... i am using c programming language to implement by using the library functions in dir.h.... I can scan through entire file system but it goes in a loop if there is loop in the filesystem(example loop mount)... how to find the loop in file system.. i have seen updatedb command reporting when there is loop in file system... i don't understand the logic... can anyone pls help find solution for this?</p>
<p>The general way to prevent re-scanning nodes in a graph is to mark nodes as you pass them, and then ignore nodes that are marked. This isn't terribly practical if you don't want to modify the graph you are scanning over, so you need a way to mark the nodes externally. The easiest way I can think of to do this under linux would be to store a the device/inode for each directory you visit. Then when you look at a directory, first check that you haven't already seen any directories with the same device/inode. This not only handles cycles, but also trees that merge back into each other.</p> <p>To get the device/inode number take a look at the stat/fstat functions and the st_dev and st_ino members of the stat struct.</p> <p>For storing the data, you're probably wanting to look at a <a href="http://www.cl.cam.ac.uk/~cwc22/hashtable/" rel="nofollow">hash-table</a> or a binary tree.</p>
Am I understanding the sequence of events in this Ruby grep example? <p>I'm trying to understand how grep works in this example. The code works but I'm not 100% sure in what sequence the events take place or whether I'm correctly understanding what's being returned when and where.</p> <pre><code>cars = [:Ford, :Toyota, :Audi, :Honda] ucased_cars = cars.collect do |c| c.to_s end .grep(/^Ford/) do |car| puts car.upcase car.upcase end puts "ucased:" + ucased_cars.to_s </code></pre> <p>What I think is happening is:</p> <ol> <li>I define an array of Symbols</li> <li>I call the collect method with a block which causes each Symbol element, c, of the cars array to be converted into a String inside the block. </li> <li>collect returns an array of Strings</li> <li>grep is invoked on the array of Strings returned by collect and grep calls its own block on each array element, car, matching the search pattern, causing the element to be printed, uppercased and returned as part of an array.</li> <li>grep returns an array of uppercased Strings, assigning it to 'ucased_cars'</li> <li>The array, ucased_cars, must be converted to a String before being printed.</li> </ol> <p>As far as step #4 is concerned, which of the following best describes how grep works:</p> <p>[A] grep finds all strings matching the pattern. grep calls the block on this array of matches. grep returns the results of the block to the invoking function.</p> <p>[B] grep finds the first string matching the pattern. grep calls the block on this match. this block's return value is piled up somewhere temporarily. grep searches the next element of the array. if it matches, grep calls the block on this match. grep adds this block's return value to the temporary "storage" of return values. grep looks at the next array element until it finds no more matches. then grep passes the stacked up return values back to the invoking function.</p> <p>My Conclusion:</p> <p>[A] seems to make more sense.</p> <p>[B] seems like a lot of unnecessary fudging and does't seem efficient or likely.</p>
<p>First of all, <a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M003152" rel="nofollow">here's the documentation for grep</a></p> <p>Let me clean up your code and explain it piece by piece</p> <pre><code># 1 cars = [:Ford, :Toyota, :Audi, :Honda] # 2 ucased_cars = cars.collect do |c| c.to_s end.grep(/^Ford/) do |car| # 3 puts car.upcase # 4 car.upcase # 5 end # 6 # 7 puts "ucased:" + ucased_cars.to_s </code></pre> <ol> <li><p>Declare array of symbols</p></li> <li><p>Convert symbols to strings by using collect. You get <code>["Ford", "Toyota", "Audi", "Honda"]</code></p></li> <li><p>Feed this array of strings into grep. Any of the items which match the regexp <code>/^Ford/</code> will get fed to the block</p></li> <li><p>The block prints out the upcased string that it got fed</p></li> <li><p>The block returns the upcased string, which grep then takes as the "match value"</p></li> <li><p>the return value from grep (which is an array of all the "match values") gets assigned to <code>ucased_cars</code>, it is <code>["FORD"]</code>, because that was the only thing that matched the regex.</p></li> <li><p>It then gets printed. doing a <code>to_s</code> on an array just prints all the elements jammedtogetherlikethis. This isn't very useful, you're better off printing <code>ucased_cars.inspect</code></p></li> </ol> <p>To answer your question about how grep works behind the scenes... </p> <p>The above documentation page shows the C source for grep itself. It basically does this:</p> <ul> <li>allocate a new ruby array (dynamically sized)</li> <li>call <code>rb_iterate</code> to walk over each element in the source, passing some grep-specific code in.</li> <li><code>rb_iterate</code> is also used by <code>collect</code>, <code>each_with_index</code> and a bunch of other stuff. </li> </ul> <p>As we know how collect/each/etc all work, we don't need to do any more spelunking in the source code, we have our answer, and it's your [B].</p> <p>To explain in more detail, it does this:</p> <ol> <li>Make a new array to hold return values.</li> <li>Get the next item from the source</li> <li>If it matches the regex: <ul> <li>If a block was given, call the block, and whatever the block returns, put it in the return values.</li> <li>If a block was not given, put the item in the return values</li> </ul></li> <li>Goto 2, repeat until no more items in the source.</li> </ol> <p>As to your comment of "A seems to make a lot more sense" - I don't agree.</p> <p>The idea is that the block does something with <em>each</em> element. If it scanned the source first, and then passed the array of matches to the block, your block would then have to call <code>each</code> itself, which would be cumbersome.</p> <p>Secondly, it would be less efficient. What happens for example, if your block calls <code>return</code> or raises an error? In it's current incarnation, you avoid having to scan the rest of the source. If it had already scanned the entire source list up-front, you'd have wasted all this effort.</p>
Unable to unzip web2py_win.zip. WINZIP says it is an invalid zip format <p>WINZIP 12.0 and also WINRAR are both unable to open web2py_win.zip version 1.59 They both say the zip format is invalid.</p> <p>Please advise what to do.</p> <p>Thanks.</p>
<p><a href="http://www.7-zip.org/" rel="nofollow">get 7-Zip</a> it can handle anything. Tho I just downloaded web2py_win.zip from <a href="http://www.web2py.com/examples/default/download" rel="nofollow">here</a> and had no problem opening it as a compressed folder using plain ol XP. I think you should re-attempt your download / bet it got interrupted</p>
Haskell: How to pipe the contents of one handle into another in real time <p>I am writing a program that runs an external sub process interactively and I need the contents of the output handle to be output to stdout as soon as it is available. I have tried something like this:</p> <pre><code>main = do processInfo &lt;- createProcess (proc "ghci" []){std_out = CreatePipe, std_in = CreatePipe } case processInfo of (Just hIn, Just hOut, _, _) -&gt; do mainloop hIn hOut hClose hIn hClose hOut _ -&gt; do error "Unable to start process" mainloop :: Handle -&gt; Handle -&gt; IO () mainloop inh outh = do ineof &lt;- hIsEOF outh if ineof then return () else do inpStr &lt;- hGetLine outh putStrLn inpStr mainloop inh outh </code></pre> <p>But this doesn't work since it only recognizes output line by line, so any output on the processes output handle that isn't terminated by a newline doesn't show up. I have tried the same thing with hGetContents but it produces the same result. I have read through the documentation of both System.Process and System.IO and haven't really found anything conclusive.</p>
<p><code>hSetBuffering</code> is what you're looking for, the default (on Unix at least) is line buffering. Use it on the stdin before starting the main loop</p> <pre><code>hSetBuffering hIn NoBuffering </code></pre> <p>and optionally also on the output handle if you want to see the results immediately on the output side. Note, however, that disabling buffering can quite drastically decrease performance.</p>
list background colour screwed up in IE7 <p>I've styled some unordered HTML lists and their heading to look like this in Firefox:</p> <p><img src="http://img24.imageshack.us/img24/711/screenshot001nij.png" alt="alt text" /></p> <p>Unfortunately, in IE7, they look like this:</p> <p><img src="http://img11.imageshack.us/img11/8343/screenshot002e.png" alt="alt text" /></p> <p>The relevant HTML is</p> <pre><code>&lt;div class="list-column"&gt; &lt;h4&gt;Types de pêche&lt;/h4&gt; &lt;ul&gt; &lt;li&gt;Pêche en lac&lt;/li&gt; &lt;li&gt;Pêche en Rivière&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>And the CSS is:</p> <pre><code>.list-column { float: left; margin-right: 20px; width: 20em; } div.list-column h4 { background-color: #FDD041; padding: 5px !important; } ul li { background-image: url(images/arrow.gif); background-position: 0 11px; background-repeat: no-repeat; list-style-image: none; list-style-position: outside; list-style-type: none; margin-bottom: 6px; margin-left: -20px; margin-top: 2px; padding: 2px 0 2px 18px; } </code></pre> <p>I suspect the fact that the div containing the list is floated left is probably the root of my problems, but I'm not sure how to workaround the poor display in IE7?</p> <p><strong>Update:</strong> I tried adding a 'zoom: 1' property to the 'ul' elements to see if giving the elements 'layout' would fix the problem in IE, but it didn't.</p> <p>The problem is definitely not related to the rounded corners. I turned them off temporarily but it didn't change anything in IE (apart from the appearance of the corners).</p> <p>Thanks, Don</p>
<p>IE and the other browsers have a different default style sheet.</p> <p>IE indents list items by putting a ‘margin-left’ on the &lt;ul>. The other browsers put a ‘padding-left’ on the &lt;ul>.</p> <p>So if you want to look the same in all browsers, set both ‘margin-left’ and ‘padding-left’ explicitly on &lt;ul>. In your case, you would want to add something like “margin: 0; padding: 24px” on your “div.list-column ul, ul.round” rule.</p> <p>(The default list ‘margin-left’ in IE is, to be precise, ‘30pt’.)</p>
Relational Operator Implementation Dilemma <p>I'm in the process of designing several classes that need to support operators <code>!=</code>, <code>&gt;</code>, <code>&lt;=</code>, and <code>&gt;=</code>. These operators will be implemented in terms of operators <code>==</code> and <code>&lt;</code>.</p> <p>At this stage, I need to make a choice between inheritance¹ and forcing my consumers to use <code>std::rel_ops</code>² "manually".</p> <p>[1] Inheritance (possible implementation):</p> <pre><code>template&lt;class T&gt; class RelationalOperatorsImpl { protected: RelationalOperatorsImpl() {} ~RelationalOperatorsImpl() {} friend bool operator!=(const T&amp; lhs, const T&amp; rhs) {return !(lhs == rhs);} friend bool operator&gt;(const T&amp; lhs, const T&amp; rhs) {return (rhs &lt; lhs);} friend bool operator&lt;=(const T&amp; lhs, const T&amp; rhs) {return !(rhs &lt; lhs);} friend bool operator&gt;=(const T&amp; lhs, const T&amp; rhs) {return !(lhs &lt; rhs);} }; template&lt;typename T&gt; class Foo : RelationalOperatorsImpl&lt; Foo&lt;T&gt; &gt; { public: explicit Foo(const T&amp; value) : m_Value(value) {} friend bool operator==(const Foo&amp; lhs, const Foo&amp; rhs) {return (lhs.m_Value == rhs.m_Value);} friend bool operator&lt;(const Foo&amp; lhs, const Foo&amp; rhs) {return (lhs.m_Value &lt; rhs.m_Value);} private: T m_Value; }; </code></pre> <p>[2] <code>std::rel_ops</code> glue:</p> <pre><code>template&lt;typename T&gt; class Foo { public: explicit Foo(const T&amp; value) : m_Value(value) {} friend bool operator==(const Foo&amp; lhs, const Foo&amp; rhs) {return (lhs.m_Value == rhs.m_Value);} friend bool operator&lt;(const Foo&amp; lhs, const Foo&amp; rhs) {return (lhs.m_Value &lt; rhs.m_Value);} private: T m_Value; }; void Consumer() { using namespace std::rel_ops; //Operators !=, &gt;, &gt;=, and &lt;= will be instantiated for Foo&lt;T&gt; (in this case) on demand. } </code></pre> <p>I'm basically trying to avoid code repetition. Any thoughts as to which method "feels" better?</p>
<p>Have you considered using <a href="http://www.boost.org/doc/libs/1%5F38%5F0/libs/utility/operators.htm" rel="nofollow">boost</a>, and having your class inherit from <code>boost::less_than_comparable&lt;T&gt;</code> and <code>boost::equality_comparable&lt;T&gt;</code>? It is akin to your first suggestion, with some pros and cons. Pros: avoids code duplication; Cons: creates a dependency on boost.</p> <p>Since boost is a very common C++ library (if you don't use it already, you should seriously consider start using it), the con factor is dimmed.</p>
How Does sizeof(Array) work <p>How does c find at run time the size of array? where is the information about array size or bounds of array stored ? </p>
<p><code>sizeof(array)</code> is implemented entirely by the C compiler. By the time the program gets linked, what looks like a <code>sizeof()</code> call to you has been converted into a constant.</p> <p>Example: when you compile this C code:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main(int argc, char** argv) { int a[33]; printf("%d\n", sizeof(a)); } </code></pre> <p>you get</p> <pre><code> .file "sz.c" .section .rodata .LC0: .string "%d\n" .text .globl main .type main, @function main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $164, %esp movl $132, 4(%esp) movl $.LC0, (%esp) call printf addl $164, %esp popl %ecx popl %ebp leal -4(%ecx), %esp ret .size main, .-main .ident "GCC: (GNU) 4.1.2 (Gentoo 4.1.2 p1.1)" .section .note.GNU-stack,"",@progbits </code></pre> <p>The <code>$132</code> in the middle is the size of the array, 132 = 4 * 33. Notice that there's no <code>call sizeof</code> instruction - unlike <code>printf</code>, which is a real function.</p>
REQUIRES_NEW annotated method is executed without a transaction? <p>I have a stateless bean resposible for persisting entities to a database. This stateless bean is called by a message bean's onMessage method. The wired thing is that on the first message everything works fine, but on the next message the method responsible for persisting is invoked outside a transaction, even though the method is annotated with REQUIRES_NEW. </p> <pre><code>@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public StateChange persistChange(long deviceId, ...) { ... StateChange change = new StateChange(...); em.persist(change); em.refresh(change); // To provoke the error return change; } </code></pre> <p>Calling refresh triggers the following exception:</p> <blockquote> <p>Caused by: javax.persistence.TransactionRequiredException: no transaction is in progress</p> </blockquote> <p>Any ideas? I'm fairly new to JTA so I might have missed something important? </p>
<p>I tried a lot to solve it and after about 16 hours or so it seems to be working. I'm not sure exactly what did the trick, but it might be the upgrade to Glassfish 2.1. </p> <p>Finally able to sleep at night again!</p>
Hibernate not reflecting changes <p>I have a struts application that uses Hibernate to access a MYSQL DB. I have a number of pages that make changes to the DB. These changes go through fine, data is update in the DB. However when browsing to the page that should show this updated information its often not there, and even after a few page refreshes it still isn't there. Eventually it will turn up. I'm assuming this has something to do with hibernate caching data, but how can I ensure that data is up to date? I had assumed that as it all went through the hibernate session it would pick up changes? The code i'm using to do the update is :</p> <pre><code> hSession = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = hSession.getTransaction(); tx.begin(); hSession.update(user) ; </code></pre> <p>Then to pull that user out again:</p> <pre><code>org.hibernate.Session hSession = HibernateUtil.getSessionFactory() .getCurrentSession(); Transaction tx = hSession.beginTransaction(); User u= (User) hSession.load(User.class, userID); </code></pre>
<p>Too little information to really give an answer. But some points to check:</p> <ul> <li><p>You are using transactions. Are you properly committing them? Maybe at some point your code cannot see changes, because the are not yet commited (or because the reading code is in another transaction which uses previous state).</p></li> <li><p>The cache might also be a problem. To check, you could explicitly flush the cache after each change to the DB (Session.flush()). This will probably degrade performance, but might help you narrow down the problem.</p></li> </ul>
Can I detect IE6 with PHP? <p>Is there a way to use PHP to detect if the page is being loaded using IE6?</p>
<p>Try checking their user agent for <code>'MSIE 6.'</code>.</p> <pre><code>$using_ie6 = (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.') !== FALSE); </code></pre> <p>This is based on <a href="http://www.useragentstring.com/pages/Internet%20Explorer/">this user agent information</a>.</p>
Building a user interface to an Excel model <p>I built an excel model used to analyze real estate transactions. I would like to create a user interface to overlay the model so that the file can be distributed to clients to evaluate potential investments </p> <p>The interface will serve two primary functions: 1)Enhance the user experience by creating an easy to follow input page. The entered data will then flow through to the model from which reports will be generated for the user to view. 2)Protect the intellectual property of the model by restricting the user from the underlying model. The user will not be able to view or edit the formulas in the excel file.</p> <p>I believe this can be done using MS Acess/Visual Basics but I was hoping to find a program that is more professional looking. Can anyone suggest a program/programming language in which this type of user interface could be created?</p> <p>Thank you in advance for your help.</p>
<p>You don't have to use Access, VBA (Visual Basic For Applications) is built right into Excel. There are <a href="http://www.techbookreport.com/tbr0037.html" rel="nofollow">good books available</a> and lots of web resources. Your main problem seems to be the UI is not professional - I'd disagree, out of the box it will look like an application developed 5-10 years ago, but it will still work and look ok. </p> <p>If you want a really slick interface, I'd suggest you look at WPF and integrating that into Excel. However there is a big learning curve to get that going, I'd get a basic UI going, show/sell that to your customers, and then ask them what they want.</p>
Simple CRUD Generator for C# <p>I am looking for a simple CRUD (or DAL) Generator for C#. I don't want anything heavyweight since I only have a couple of tables in a SQL Server 2008 database.</p> <p>Any suggestions? I know .netTiers, but it is way too much for what I need.</p> <p>Thanks!</p> <p>UPDATE: I tried LINQ to SQL and it doesn't work well for my needs.</p>
<p>I have used SubSonic on past projects, it's lightweight and easy to use.</p> <p>They offer a simple <a href="http://www.wekeroad.com/webcasts/subsonicintro/intro.html" rel="nofollow">tutorial video</a> and it should take no more than 10 minutes to get it completely setup. I recommend watching the second half of the video that deals with Web Application Projects because it shows you how to create a customized Visual Studio button that creates the DAL for you whenever you click on it instead of using a custom build-provider as they suggest in first half of the video.</p> <p>It offers several ways to access your data, Active Record, generating typed stored-procedures and views, or <a href="http://subsonicproject.com/querying/select-queries/" rel="nofollow">a query language</a> that you can use.</p> <p>After using it, I have found a few quirks:</p> <ul> <li>If you use a generated stored-procedure that does not have a parameter, it will throw a <code>NullReferenceException</code>. A workaround is to create a dummy parameter that isn't used in the procedure</li> <li>The <code>DeepSave()</code> function does not work in the current 2.1 version, you'll have to individually save data from joined tables</li> <li>When you use a coditional (e.g. <code>Where(Tag.Columns.TagName).IsEqualTo("subjective")</code>, make sure you use the string value <code>Tag.Columns.TagName</code> to reference the column - otherwise an exception will be thrown if you try to use the <code>Column.Schema</code></li> </ul>
Comparing String to Integer gives strange results <p>I'm really confused as to why this operation works. Can someone explain it?</p> <pre><code>$test1 = "d85d1d81b25614a3504a3d5601a9cb2e"; $test2 = "3581169b064f71be1630b321d3ca318f"; if ($test1 == 0) echo "Test 1 is Equal!?"; if ($test2 == 0) echo "Test 2 is Equal!?"; // Returns: Test 1 is Equal!? </code></pre> <p>For clarification, I am trying to compare the string <code>"0"</code> to the <code>$test</code> variables. I already know to fix the code I can just enclose (as I should have) the <code>0</code> in <code>""</code>s</p> <p>I'm wondering if this is a PHP bug, a server bug, or somehow a valid operation. According to <a href="http://us3.php.net/types.comparisons">http://us3.php.net/types.comparisons</a> this <strong>should not</strong> have worked.</p> <p><strong>Edit:</strong> Scratch that, apparently it does mention that Loose comparisons between string and 0 is true. But I still don't know why.</p> <p><strong>Edit 2:</strong> I've revised my question, why does the <code>$test2</code> value of <code>"3581169b064f71be1630b321d3ca318f"</code> not work?</p>
<p><a href="http://il.php.net/manual/en/language.types.string.php#language.types.string.conversion">From the PHP manual</a>:</p> <blockquote> <p><strong>String conversion to numbers</strong></p> <p>When a string is evaluated in a numeric context, the resulting value and type are determined as follows.</p> <p>The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.</p> <p>The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.</p> </blockquote>
How do I get a code window to split vertically in Visual Studio 2008? (not HTML mode) <p>In Visual Studio 2008, it seems that <strong>Window -> Split</strong> only gives me a horizontal split, and <strong>Window -> New horizontal tab group</strong> does not allow me to edit the same file in both panes.</p> <p>Note that I am talking about C# code windows, <strong>not</strong> HTML editing mode.</p> <p>I want to edit the same file in two horizontally arranged panes.</p> <p>Is this possible? Free add-ons are fine.</p> <p><strong>Edit:</strong> I have CodeRush Express installed, and it seems to have done <em>something</em> to my code window borders. </p> <p><strong>Edit #2:</strong> It's not CodeRush. I tried on VM with no CodeRush, and I have exactly the same issue.</p>
<p>Ok, I found the solution <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=344036">here</a>.</p> <p>The answer is:</p> <ol> <li>Window -> New Window</li> <li>Window -> New Vertical Tab Group</li> </ol> <p>This duplicates the current tab so you'll get <code>[Form1.cs:1]</code> and <code>[Form1.cs:2]</code> tabs; and <strong>then</strong> you can use a vertical tab group to view them side by side.</p>
smlnj rephrased question for listdir(filename, directoryname) <p>i am a newbie learning sml and the question i am thrown with involves IO functions that i have no idea how it works even after reading it. Here is the 2 questions that i really need help with to get me started, please provide me with codings and some explaination, i will be able to trial and error with the code given for the other questions.</p> <p>Q1) listdir(filename,directoryname), which given the name of a directory, list its contents in a text file. The listing is in a form that makes it easy to seperate filenames, dates and sizes from each other. (similar to what msdos does with "dir" but instead of just listing it out, it places all the files and details into a text file.</p> <p>Q2) readlist(filename) which reads a list of filenames (each of which were produced by listdir in (Q1) and combines them into one large list. (reads from the text file in Q1 and then assigning the contents into 1 big list containing all the information)</p> <p>Thing is, i only learned from the lecturer in school on the introduction section, there isnt even a system input or output example shown, not even the "use file" function is taught. if anyone that knows sml sees this, please help. Thanks to anyone who took the effort helping me.</p> <p>Thanks for the reply, current I am using SMLNJ to try and do this. Basically, Q1 requires me to list the directory's files of the "directoryname" provided into a text file in "filename". The Q2 requires me to read from the "filename" text file and then place the contents into one large list.</p> <p>Duplicate of: <a href="http://stackoverflow.com/questions/672065/smlnj-listdir">smlnj listdir</a></p>
<p>As a hint I will say that you have to make use of these functions: </p> <p>OS.FileSys.OpenDir(directoryname) - this will open directory stream for you (Q1) TextIO.openOut(filename) - this will open the file stream (Q2)</p> <p>TextIO.openIn(filename)- this will open the file (Q2) If you are stuck and dont' know how to do the progs then I will post the full code here, but i suggest you first give a try.</p> <p><hr /></p> <p>zubair sheikh</p>
What are some hints that an algorithm should parallelized? <p>My experience thus far has shown me that even with multi-core processors, parallelizing an algorithm won't always speed it up noticably. In fact, sometimes it can slow things down. What are some good hints that an algorithm can be sped up significantly by being parallelized?</p> <p>(Of course given the caveats with premature optimization and their correlation to evil)</p>
<p>To gain the most benefit from parallelisation, a task should be able to be broken into similiar-sized course-grain chunks that are independent (or mostly so), and require little communication of data or synchronisation between the chunks.</p> <p>Fine-grain parallelisation, almost always suffers from increased overheads, and will have a finite speed-up regardless of the number of physical cores available.</p> <p>[The caveat to this, is those architectures that have a very large no. of 'cores' (such as the connection machines 64,000 cores). These are well suited to calculations that can be broken into relatively simple actions assigned to a particular topology (like a rectangular mesh).]</p>
jQuery Thickbox Issue <p>I'm a jQuery newb. I'm building a Online Shop and I'm using jQuery plugin 'Thickbox' (<a href="http://jquery.com/demo/thickbox" rel="nofollow">http://jquery.com/demo/thickbox</a>). The Online Shop is set up to display a 'Enlarged Image' which runs the Thickbox JS script and shows an image.</p> <p>A problem occurs as the data is placed on the page thru a CMS system (using Ajax I believe?). When you choose another product from the 'Choose Type' select drop down new data from the CMS system is placed on the page and the Thickbox script isn't applied as it can't see the new data.</p> <p>I've been playing around with a fix I've found (<a href="http://www.codynolden.com/blog/2009/01/thickbox-and-ajax-using-livequery" rel="nofollow">http://www.codynolden.com/blog/2009/01/thickbox-and-ajax-using-livequery</a>) but I can't seem to apply it to my website?</p> <p>A live example of my site: <a href="http://madisonlane.businesscatalyst.com/%5Fproduct%5F36331/AAA-%5FAutumn%5FDress" rel="nofollow">http://madisonlane.businesscatalyst.com/_product_36331/AAA-_Autumn_Dress</a></p> <p>Any ideas?</p>
<p>in thickbox.js:</p> <pre><code>$(domChunk).click(function(){ </code></pre> <p>was replaced with this:</p> <pre><code>$(domChunk).live(click, function(){ </code></pre>
How to implement a thread safe timer on linux? <p>As we know, doing things in signal handlers is really bad, because they run in an interrupt-like context. It's quite possible that various locks (including the malloc() heap lock!) are held when the signal handler is called.</p> <p>So I want to implement a thread safe timer without using signal mechanism.</p> <p>How can I do?</p> <p>Sorry, actually, I'm not expecting answers about thread-safe, but answers about implementing a timer on Unix or Linux which is thread-safe.</p>
<p>Use usleep(3) or sleep(3) in your thread. This will block the thread until the timeout expires.</p> <p>If you need to wait on I/O and have a timer expire before any I/O is ready, use select(2), poll(2) or epoll(7) with a timeout.</p> <p>If you still need to use a signal handler, create a pipe with pipe(2), do a blocking read on the read side in your thread, or use select/poll/epoll to wait for it to be ready, and write a byte to the write end of your pipe in the signal handler with write(2). It doesn't matter what you write to the pipe - the idea is to just get your thread to wake up. If you want to multiplex signals on the one pipe, write the signal number or some other ID to the pipe.</p>
Java Pattern to match any sequence of characters except a given list <p>How do I write a Pattern (Java) to match any sequence of characters except a given list of words?</p> <p>I need to find if a given code has any text surrounded by tags like besides a given list of words. For example, I want to check if there are any other words besides "one" and "two" surrounded by the tag .</p> <pre><code>"This is the first tag &lt;span&gt;one&lt;/span&gt; and this is the third &lt;span&gt;three&lt;/span&gt;" </code></pre> <p>The pattern should match the above string because the word "three" is surrounded by the tag and is not part of the list of given words ("one", "two").</p>
<p>Look-ahead can do this:</p> <pre><code>\b(?!your|given|list|of|exclusions)\w+\b </code></pre> <p>Matches</p> <ul> <li>a word boundary (start-of-word)</li> <li>not followed by any of "your", "given", "list", "of", "exclusions"</li> <li>followed by multiple word characters</li> <li>followed by a word boundary (end-of-word)</li> </ul> <p>In effect, this matches any word that is not excluded.</p>
Creating a database from .mdf file in MS Access <p>I have a .mdf which I need to import into MS Access. I have read that .mdf is a Sql Server format so Access wont recognize it. But is there some way I can get the database created in MS Access. I am using Access 2003 and Sql Server 2005</p>
<p>Why not right click the database in SQL Management Studio, click export and then specify the required parameter?</p> <p>I just checked. Works in my installation of SQL Server 2008.</p>
Consuming XML/SOAP web service in RoR <p>I know they removed ActionService out of RoR and opted for RESTful web services. I want to know if Rails is a good choice of a framework for consuming XML/SOAP based web services. Can anyone point out some nice resources/tutorials on how to consume a SOAP based web service in ROR?</p>
<p>This is a pretty good step-by-step tutorial for soap4r: [link no longer works]</p>
Java: Google Maps alternative <p>I'm really tired of using the Google Web Toolkit for accessing Google Maps in Java using Netbeans... Does anybody know of a good alternative providing a simple(r) API? </p> <p>Any help would really be appreciated!</p>
<p><a href="http://openstreetmap.org/" rel="nofollow">OpenStreetMap</a> has a good <a href="http://wiki.openstreetmap.org/wiki/API" rel="nofollow">API</a> in combination with <a href="http://www.openlayers.org/" rel="nofollow">OpenLayers</a>.<br /> Good luck with that!</p> <p>Driving instructions are included, but since OSM is user-generated, you cannot rely 100% on this information. See <a href="http://wiki.openstreetmap.org/wiki/Routing" rel="nofollow">OSM-Wiki article "Routing"</a></p>
How to make the vertical scrollbar follow the data? <p>In a VC++ 6.0 MFC of mine, I added an EditBox with Vertical Scrollbar, every 10 seconds I am reading data from serial port and I have to display through EditBox(IDC_EDIT1), I done it without any problems.</p> <p>But one typical problem I am facing which is that, whenever a new data displayed in the EditBox the vertical scrollbar goes up and data remains down, I have to scroll down every time to read the data.</p> <p>So my question is whenever a new data display in EditBox the vertical scrollbar also has to move down along with the data.</p> <p>How can i do this?</p>
<p>You will need to send the edit control an EM_SETSEL message with the length of the string as the parameters.</p>
JDBC generation of SQL in PreparedStatement <p>I had a really huge problem recently which took me a lot of time to debug. I have an update statement which updates 32 columns in table. I did that with PreparedStatement. Accidentaly I deleted one setParameter() call so update could not be finished successfully. </p> <p>I got exception from JDBC (Apache Derby) telling: "At leas one parameter is not initialized" and was not able to figure out which parameter is not set since driver would not tell you nothing about name or ordinal number of at least first parameter which is not set... </p> <p>I was googleing unsuccessfully for some utility which will produce plain old SQL out of (nearly-finished) prepared statement. It would help a lot in situations like this one, since I will be able to see what is not set. </p> <p>Have anyone faced this problem? Got any solution? </p>
<p>Have a look at <a href="http://www.p6spy.com/" rel="nofollow">P6Spy</a>. It can intercept all your JDBC calls and log them before forwarding them onto your database.</p> <p>Alternatively, think about using Springs JDBCTemplate which can take out alot of your boilerplate JDBC coding and help avoid these kind of mistakes. You don't need the rest of the Spring framework to use this bit.</p>
When to include a design pattern name in class name? <p>During my last project I noticed, that it is very convenient, to include design patterns names in class names. For example:</p> <ul> <li>ContextLazyFactory</li> <li>RunOnceMediator</li> <li>ThirdPartyMediator</li> <li>MyProjectCliFacade</li> <li>BinaryGate</li> </ul> <p>It makes the project easy to read. Additional benefit is that you will not use your own names like "RunOnceManager", "ContextDelayedConstruction", "ThirdPartyInterface", etc. which may have sharp meaning only for the author. On the other hand, I would not like to see classes like vector_container in the STL. How do you think?</p> <p>My current view on this topic is: classes that are important nodes in class hierarchy should have their design pattern in their name, to emphasis the hierarchy structure and make the project much easier to read.</p>
<p>It seems natural to me in many cases:</p> <ul> <li>Design patterns are named to explain what they do</li> <li>Classes are named to explain what they do</li> </ul> <p>When the simplest way of explaining a class's purpose is in design pattern terms, why not use it?</p> <p>On the other hand, when the design pattern is mostly <em>incidental</em> then exclude it. For example, a class may happen to be a singleton, but that's not its main purpose in life, so I wouldn't expect to see "Singleton" in the name. Compare that with a factory whose main purpose is to be a factory for other objects - "FooFactory" makes perfect sense.</p>
What is the use of passing const references to primitive types? <p>In a project I maintain, I see a lot of code like this for simple <code>get</code>/<code>set</code> methods</p> <pre><code>const int &amp; MyClass::getFoo() { return m_foo; } void MyClass::setFoo(const int &amp; foo) { m_foo = foo; } </code></pre> <p>What is the point in doing that instead of the following?</p> <pre><code>int MyClass::getFoo() { return m_foo; } // Removed 'const' and '&amp;' void MyClass::setFoo(const int foo) { m_foo = foo; } // Removed '&amp;' </code></pre> <p>Passing a reference to a primitive type should require the same (or more) effort as passing the type's value itself, right?<br /> It's just a number after all...<br /> Is this just some attempted micro-optimization or is there a true benefit?</p>
<p>The difference is that if you get that result into a reference yourself you can track the changes of the integer member variable in your own variable name without recalling the function. </p> <pre><code>const &amp;int x = myObject.getFoo(); cout&lt;&lt;x&lt;&lt;endl; //... cout&lt;&lt;x&lt;&lt;endl;//x might have changed </code></pre> <p>It's probably not the best design choice, and it's very dangerous to return a reference (const or not), in case a variable that gets freed from scope is returned. So if you return a reference, be careful to be sure it is not a variable that goes out of scope.</p> <p>There is a slight difference for the modifier too, but again probably not something that is worth doing or that was intended.</p> <pre><code>void test1(int x) { cout&lt;&lt;x&lt;&lt;endl;//prints 1 } void test2(const int &amp;x) { cout&lt;&lt;x&lt;&lt;endl;//prints 1 or something else possibly, another thread could have changed x } int main(int argc, char**argv) { int x = 1; test1(x); //... test2(x); return 0; } </code></pre> <p>So the end result is that you obtain changes even after the parameters are passed.</p>
TabPages for newly opened Windows Forms C# <p>I want to add a new tab page for every newly opened form.</p> <p>Example:</p> <pre><code>frmReport reportform = new frmReport(); report.Show(); </code></pre> <p>When I open the <code>frmReport</code> form, it must be opened in a new TabPage, as in Windows Internet Explorer 7-8 tabpages.</p>
<p>What you would like to achive here is to have "windows inside tab pages". This is not like it supposed to be! It looks like this:</p> <ul> <li>Windows OS</li> <li>Windows of applications (Window class)</li> <li>Containers placed on Window (for example: Panel, TabControl!)</li> <li>Controls placed on Windows and Containers (for example: Button, but also containers like Panel!)</li> </ul> <p>So when you look on this you see that it's not ok to put Windows class into TabControl! </p> <p>So what to do?</p> <p>Create for example UserControl class and move all your controls from Window to this new UserControl. Next place on your Window TabControl nad on one of it's TabPages put this newly created UserControl.</p> <p>In this way you'll have a good designed UI. Once again: You do not put Window on your TabPage!</p>
Component Vs Control <p>In the world of WinForms .Net controls</p> <p>What is the difference between Component and Control?</p> <p>Can a Control contain Components ? Can a Component contain Controls ?</p>
<p>A Control has all the plumbing required to act as a window. The ability to respond to Window messages (WndProc) and having a Handle being foremost. Component is missing all that. It is really rather simple, it has design time support and it can be disposed, that's about it.</p> <p>Components still can have a runtime representation, OpenFileDialog being the best example. But that is actually a dialog built into Windows, not Windows Forms.</p>
C++ development on linux Code::Blocks, EMACS or GVIM <p>I am not looking for an IDE suggestion for C++ development. I have found many discussions on that and tried EMACS, GVIM and Code::Blocks. I liked Code::Blocks very much than the other two. But it looks like most of the developer community is using tools like EMACS or GVIM. Is there a reason for this? Why Code::Blocks is less used?</p> <p>I found EMACS and GVIM is less user friendly. You have to put more effort to get it working, but Code::Blocks take advantage here. It is easy to start and compile. Or do I miss something?</p> <p>Thanks</p>
<p>Whatever editor you ultimately end up using, it is worth taking a few minutes to at least learn to navigate around and perform basic editing tasks in Vim, since a vi of some flavour is the most commonly available editor in especially the more specialised distros.</p>
What are the most common (and often overlooked) causes of memory leaks in managed (.net) applications? <p>Please can anyone recommend a quick checklist / best practice guide to help us avoid simple (but subtle) mistakes that cause could cause memory leaks in .net apps</p> <p>I find it difficult and quite painful to begin searching for the cause of a memory leakage when i'm in the testing phase of a project.</p> <p>If there are 'rules of thumb' to completely guide against memory leaks in managed applications, i implore you to please share your experience.</p> <p>Thanks.</p> <p>(I thought Managed applications are suppose to be 'memory managed' i.e. the GC? Why then do we still find leakages in purely managed code?)</p>
<p>There are many forms of leaks:</p> <ul> <li>Unmanaged leaks (code that allocates unmanaged code)</li> <li>Resource leaks (code that allocates and uses unmanaged resources, like files, sockets)</li> <li>Extended lifetime of objects</li> <li>Incorrect understanding of how GC and .NET memory management works</li> <li>Bugs in the .NET runtime</li> </ul> <p>The first two is usually handled by two different pieces of code:</p> <ul> <li>Implementing IDisposable on the object and disposing of the unmanaged memory/resource in the Dispose method</li> <li>Implementing a finalizer, to make sure unmanaged resources are deallocated when GC has found the object to be eligible for collection</li> </ul> <p>The third, however, is different.</p> <p>Say you are using a big list holding thousands of objects, totalling a significant size of memory. If you keep around a reference to this list for longer than you need to, you will have what looks like a memory leak. In addition, if you keep adding to this list, so that it grows with more data periodically, and old data is never reused, you definitely have a memory leak.</p> <p>One source of this I've seen frequently is to attach methods to event handlers but forget to unregister them when you're done, slowly bloating the event handler both in size and code to execute.</p> <p>The fourth, an incorrect understanding of how .NET memory management works can mean that you look at the memory usage in a process viewer and notice that your app keeps growing in memory usage. If you have lots and lots of memory available, GC might not run that often, giving you an incorrect picture of the current <em>usage</em> of memory, as opposed to mapped memory.</p> <p>The fifth, that's harder, I've only seen one resource management bug in .NET so far and afaik it has been slated for fix in .NET 4.0, it was with copying the desktop screen into a .NET image.</p> <p><hr /></p> <p><strong>Edit</strong>: In response to the question in the comments, how to avoid keeping references longer than necessary, then the only way to do that is to to just that.</p> <p>Let me explain.</p> <p>First, if you have a long-running method (for instance, it might be processing files on disk, or downloading something, or similar), and you used a reference to a big data-structure early in the method, before the long-running part, and then you don't use that data structure for the rest of the method, then .NET, in release-builds (and not running under a debugger) is smart enough to know that this reference, though it is held in a variable that is technically in scope, is eligible for garbage collection. The garbage collector is really aggressive in this respect. In debug-builds and running under a debugger, it will keep the reference for the life of the method, in case you want to inspect it when stopped at a breakpoint.</p> <p>However, if the reference is stored in a field reference in the class where the method is declared, it's not so smart, since it's impossible to determine whether it will be reused later on, or at least very very hard. If this data structure becomes unnecessary, you should clear the reference you're holding to it, so that GC will pick it up later.</p>
Frames in HTML? <p>Actually...im having one left frame and one right frame....</p> <ol> <li><p>In Left Frame , i'm having one treeview (which is static)</p></li> <li><p>In Right Frame , based on the click (that is based on the selected child i have to show the corresponding web page )</p></li> </ol> <p>How to achieve this ???</p>
<p>Use a frameset</p> <pre><code>&lt;frameset cols="150,*" frameborder="NO" marginwidth=0 marginheight=0&gt; &lt;frame src="left.html" frameborder="NO" &gt; &lt;frame src="right.html" frameborder="NO" name="subwindow"&gt; &lt;/frameset&gt; &lt;noframes&gt; &lt;body&gt;&lt;p&gt;This web page uses frames.&lt;/p&gt;&lt;/body&gt; &lt;/noframes&gt; &lt;/frameset&gt; </code></pre> <p>and make your links to target window like;</p> <pre><code>&lt;A HREF="main.html" target="subwindow"&gt; </code></pre>
Map unknown amount of columns to Dictionary <p>I have a legacy system that dynamically augments a table with additional columns when needed. Now I would like to access said table via C#/NHibernate.<br /> There is no way to change the behaviour of the legacy system and I dynamically need to work with the data in the additional columns. Therefore dynamic-component mapping is not an option since I do not know the exact names of the additional columns.</p> <p>Is there a way to put all unmapped columns into a dictionary (column name as key)? Or if that's not an option put all columns into a dictionary?</p> <p>Again, I do not know the names of the columns at compile time so this has to be fully dynamic.</p> <p>Example:</p> <pre><code>public class History { public Guid Id { get; set; } public DateTime SaveDateTime { get; set; } public string Description { get; set; } public IDictionary&lt;string, object&gt; AdditionalProperties { get; set; } } </code></pre> <p>So if the table History contains the Columns <em>Id</em>, <em>SaveDateTime</em>, <em>Description</em>, <em>A</em>, <em>B</em>, <em>C</em> and <em>D</em> I would like to have "A", "B", "C" and "D" in the IDictionary. Or if that's too hard to do simply throw all columns in there.</p> <p>For starters I would also be fine with only using string columns if that helps.</p>
<p>You probably need an ADO.NET query to get this data out. If you use NH, even with a SQL query using SELECT *, you'll not getting the column names.</p> <p>You can try using SMO (SqlServer management objects, a .NET Port to the SqlServer) or some other way to find the table definitions. Then you build up the mapping using <a href="http://fluentnhibernate.org/" rel="nofollow">Fluent NHibernate</a> with a dynamic component. I'm not sure if you can change the mappings after you already used the session factory. It's worth a try. Good luck :-)</p>
Clear/Standard name for a Unit Range [0->1] <p>I'm writing a Range class at the moment and I'm looking for a good name for the common range [0->1]. If it was a vector of length 1, I would call it a Unit vector. Is there a clear name to give this range/interval? Possibly a <em>Unit Range</em>?</p>
<p>The closed range between [0,1] is typically called the <a href="http://mathworld.wolfram.com/UnitInterval.html">closed unit interval</a>. If you do not include the endpoints it would be the open unit interval.</p>
Error while copying from network share "This page has an unspecified potential security flaw." <p>I recently reinstalled XP and then SP3 and I'm currently getting an error whenever I try and copy something from a network share.</p> <pre><code>Title: Internet Explorer Message: This page has an unspecified potential security flaw. Would you like to continue? </code></pre> <p>I believe it's related to <a href="http://support.microsoft.com/kb/921398" rel="nofollow">KB921398 (MS06-045)</a> and I'm currently uninstalling SP3, but does anyone know if there is another way to disable this specific update? It does not appear in Add &amp; Remove Programs.</p> <p>There's a temporary fix by adding any network ip masks to the trusted intranet zones in Internet Explorer's Security settings, but it's no fix :(</p>
<blockquote> <p>There's a temporary fix by adding any network ip masks to the trusted intranet zones</p> </blockquote> <p>That's the real fix. The error message occurs when you are trying to copy files out of the Internet Zone. And it is indeed risky if you really are dragging files out of a public-internet network share, so the message isn't really wrong (just vague and misleading).</p> <p>To avoid the error popping up in your intranet — and because it's the right thing to do anyway — you need to make sure Windows sees the intranet as being in the Local intranet Zone.</p> <p>Go to Control Panel -> Internet Options-> Security -> Local intranet -> Sites. If “Automatically detect intanet network” is ticked, untick it as obviously the automatic detection isn't working. Turn on the top two; if you're sure that you will never be accessing network shares outside the intranet (eg. because a firewall prevents it), you can tick “Include all network paths”.</p> <p>If this doesn't work add the folder path as a trusted Local Intranet site.</p>
how to draw line chart using Google charts <p>Why the line is starting at 100 on y-axis, Can any body solve my problem.</p> <p>code:</p> <pre><code>&lt;img src="http://chart.apis.google.com/chart? chs=500x200 &amp;amp;chd=t:533,100,423,200|179,50 &amp;amp;cht=lc &amp;amp;chxt=x,y &amp;amp;chxl=0:|JAN|FEB|MAR|APR|MAY|JUNE|JULY|AUG|SEP|OCT|NOV|DEC| 1:||20|40|60|80|100 &amp;amp;chco=FF9900,FF0000,0000FF" alt="Sample chart" /&gt; </code></pre> <p>if i changed the y-axis values the line is coming at 1000!</p> <pre><code>1:||200|400|600|800|1000 </code></pre> <p>how can i get that starting point at 533 ? </p> <p>thanks</p>
<p>Axis 1 is the left y-Axis and with the <code>chxl</code> parameter you have specified labels of 0,20,40,60,80 and 100.</p> <p>You could change the top value to 533 but I think this would look odd.</p> <p>The thing to realise is that the labels work independently of the values. You change the <a href="http://code.google.com/apis/chart/formats.html#data%5Fscaling" rel="nofollow">scale of your data using the <code>chds</code> parameter</a>.</p> <p>So I think you should specify a round value on the Y-axis label like 600 and scale the data to match.</p> <p>Try this:</p> <pre><code>&lt;img src="http://chart.apis.google.com/chart? chs=500x200 &amp;amp;chd=t:533,100,423,200|179,50 &amp;amp;chds=0,600 &amp;amp;cht=lc &amp;amp;chxt=x,y &amp;amp;chxl=0:|JAN|FEB|MAR|APR|MAY|JUNE|JULY|AUG|SEP|OCT|NOV|DEC| 1:|0|300|600 &amp;amp;chco=FF9900,FF0000,0000FF" alt="Sample chart" /&gt; </code></pre> <blockquote> <p><img src="http://chart.apis.google.com/chart?chs=500x200&amp;chd=t:533,100,423,200|179,50&amp;chds=0,600&amp;cht=lc&amp;chxt=x,y&amp;chxl=0:|JAN|FEB|MAR|APR|MAY|JUNE|JULY|AUG|SEP|OCT|NOV|DEC|1:|0|300|600&amp;chco=FF9900,FF0000,0000FF" alt="Graph" /></p> </blockquote>
Dispose on user controls, really meant to edit the .designer.cs file? <p>For a user control with internal data structures that must be disposed, is the correct place to add that code to the Dispose method in the .designer.cs file, or is there an event or something we're meant to use instead?</p> <p><strong>Edit</strong>: This is a winforms user control.</p>
<p>If you're talking about WinForms I usually take one of two approaches to solve this problem.</p> <p><strong>Approach 1</strong></p> <p>Open the Form.Designer.cs file. Inside the generated dispose method I add a call to DisposeCore. I then go back to Form.cs and add a DisposeCore method that will now be called during dispose. I add all of my dispose logic into this method.</p> <p>Editing the designer file is technically not supported. However I've found that this particular edit will not be washed away when the designer regenerates code.</p> <p><strong>Approach 2</strong></p> <p>Add a event handler to Form.Disposed and do my dispose logic in the handler. This is the preferable way because it's a supported operation and won't be affected by some designer generation you have yet to encounter. </p>
Remove project .jars from project explorer view in Eclipse <p>The list of jars just takes up too much space. Can I collapse it or hide it?</p>
<p>Another solution would be using the Package Explorer view.</p>
What is a correct way to initiate user control from code behind <p>Basically I want to create a user control in code behind, DataBind() it and then insert the control into current page</p> <p>I'm currently trying this:</p> <pre><code>var comment = new IncidentHistoryGroupComment(); comment.LoadControl("~/Controls/IncidentHistoryGroupComment.ascx"); comment.LoadTemplate("~/Controls/IncidentHistoryGroupComment.ascx"); comment.InitializeAsUserControl(this); comment.AttachmentActions = group.HastAttachmentActions ? group.AttachmentActions : null; comment.Comment = group.Comment; comment.NextStep = group.NextStep; comment.IsInitiationStep = group.InitializationEntry != null; comment.DataBind(); </code></pre> <p>But still all controls inside it are null. For example i have a pane with id pnlComments and when I try to access it in IncidentHistoryGroupComment.DataBind() method I get null. I also checked Controls property to see if there is something there but Controls.Count == 0</p> <p>So the question is how to correctly initialize a user control from code behind so that all controls would be assigned to their instances in IncidentHistoryGroupComment.designer.cs so I could access them easily.</p>
<pre><code>MyControl myControl = (MyControl)LoadControL("~/MyControl.ascx"); </code></pre> <p>I changed the name of your control for readability.</p>
Merge two arrays (key and content) in PHP <p>I have an array like the following</p> <p>Array ( [0] => "txt1" [1] => "txt2" [2] => "txt3")</p> <p>I have another array like it but with different content : Array ( [0] => on [2] => on)</p> <p>The aim is to get a final array with the keys of the second and the content of the first, it's like merging them.</p> <p>So that the final result is : Array ( [0] => "txt1" [2] => "txt3") It would be better to change the keys to 0 - 1, but that a trivial issue, let's focus on merging them one to one.</p>
<p>The easiest way to do this is with <code>array_intersect_key</code> (<a href="http://ca.php.net/manual/en/function.array-intersect-key.php" rel="nofollow">See the PHP Docs</a>). It grabs the values from the first array passed corresponding to the keys present in all other arrays passed.</p> <p>So, your example would look like this:</p> <pre><code>$a = array(0 =&gt; "txt1", 1 =&gt; "txt2", 2 =&gt; "txt3"); $b = array(0 =&gt; 1, 2 =&gt; 1); $c = array_intersect_key($a, $b); print_r($c); </code></pre> <p>prints:</p> <pre><code>Array ( [0] =&gt; txt1 [2] =&gt; txt3 ) </code></pre>
how do I print an unsigned char as hex in c++ using ostream? <p>I want to work with unsigned 8-bit variables in C++. Either <code>unsigned char</code> or <code>uint8_t</code> do the trick as far as the arithmetic is concerned (which is expected, since AFAIK <code>uint8_t</code> is just an alias for <code>unsigned char</code>, or so the debugger presents it.</p> <p>The problem is that if I print out the variables using ostream in C++ it treats it as char. If I have:</p> <pre><code>unsigned char a = 0; unsigned char b = 0xff; cout &lt;&lt; "a is " &lt;&lt; hex &lt;&lt; a &lt;&lt;"; b is " &lt;&lt; hex &lt;&lt; b &lt;&lt; endl; </code></pre> <p>then the output is:</p> <pre><code>a is ^@; b is 377 </code></pre> <p>instead of </p> <pre><code>a is 0; b is ff </code></pre> <p>I tried using <code>uint8_t</code>, but as I mentioned before, that's typedef'ed to <code>unsigned char</code>, so it does the same. How can I print my variables correctly?</p> <p><strong>Edit:</strong> I do this in many places throughout my code. Is there any way I can do this <em>without</em> casting to <code>int</code> each time I want to print?</p>
<p>I would suggest using the following technique:</p> <pre><code>struct HexCharStruct { unsigned char c; HexCharStruct(unsigned char _c) : c(_c) { } }; inline std::ostream&amp; operator&lt;&lt;(std::ostream&amp; o, const HexCharStruct&amp; hs) { return (o &lt;&lt; std::hex &lt;&lt; (int)hs.c); } inline HexCharStruct hex(unsigned char _c) { return HexCharStruct(_c); } int main() { char a = 131; std::cout &lt;&lt; hex(a) &lt;&lt; std::endl; } </code></pre> <p>It's short to write, has the same efficiency as the original solution and it lets you choose to use the "original" character output. And it's type-safe (not using "evil" macros :-))</p>
How can i use MYSQL database connection in iphone application useing cocos2d? <p>I am working on project and i need to connect MYSQL database. I am success to connect SQLite in my project ( using cocos2d).But i can not connect MYSQL database in my project. I any one do like this than help me for how to connect . Give me the necessary information.</p>
<p>You will not be able to connect to MySQL directly from the iPhone. You <strong>must</strong> use some intermediate layer such as a Web application with PHP.</p> <p>So, you will have something like this:</p> <ol> <li>iPhone POSTING a request to the WebServer using HTTP</li> <li>Web Server connecting to the MySQL database</li> <li>Web Server returning data to the iPhone (XML, plain text)</li> <li>iPhone processing the data</li> </ol> <p>You can use this technique to query and insert/update/delete data.</p>
Assembly to Bytes <p>My scenario - I am trying to send a Assembly File from Server to Client (via direct TCP connection). But the major problem is- how do I convert this Assembly to bytes to that it can be readily transferred? I used following - </p> <pre><code>byte[] dllAsArray; using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream,loCompiled.CompiledAssembly); dllAsArray = stream.ToArray(); } </code></pre> <p>But when I use - </p> <pre><code>Assembly assembly = Assembly.Load(dllAsArray); </code></pre> <p>I get an exception - </p> <blockquote> <p>Could not load file or assembly '165 bytes loaded from Code generator server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Please help!!!</p> </blockquote>
<p>Wouldn't that just be the raw dll contents, as though you had saved it to disk? i.e. the equivalent of <code>File.ReadAllBytes</code>?</p> <p>It sounds like the dll is generated - can you save it anywhere? (temp area, memory stream, etc)?</p> <p><strong>edit</strong> Since it seems you are using code-dom, try using <code>PathToAssembly</code> (on the compiler-results) and <code>File.ReadAllBytes</code> (or a similar streaming mechanism).</p>
ASP.Net Custom controls vs. user controls: Are these two the same <p>If they are different, under what circumstances should we decide to use either approach?</p> <p>Also, what is the advantage of ascx over aspx?</p>
<p>user controls are a form of custom control, that gives you a visual designer. They are ideal for use when you want a reusable control within the same web site. (It is possible to create and package user controls as seperate assemblies but that is beyond the scope of this question and I know has been asked on SO). </p> <p>A custom control is typically used to refer to a Web Control, or a Composite Control which is specialized form of a web control. These controls have no designer and are usually implemented in seperate projects from your web allowing them to be reused accross many sites.</p> <p>Now your second question, ASCX and ASPX are two different things. ASCX is the extension for a User Control, where as ASPX is an ASP.Net Page. You cannot use an ASCX by itself it must be placed onto an ASPX or Master page.</p> <p>One way I like to use user controls is I have for example a very complex page which have 7 tabs, 5 of those have grids, of those grids three of them are identicle. Well what I can do is create a seperate user control for the content of the tabs, this now reduces the code I need down significantly (Since three grids are identicle except for the data). </p> <p>Further more it allows multiple to work on various parts of the page, and it helps me keep everything straight since I am reducing the complexity of the page. You do not use User Controls instead of Pages, you use them in conjuction with a page.</p> <h1>Edit</h1> <p>You do not use ascx over aspx. You use ascx to complement. For example on my site every page has the same footer, but I don't want every page to derive from a single master page. I can create my footer as an acsx control and put it in each of my master pages. </p> <p>Another example, I have a form that lets a user enter three different date ranges. (And we have other forms). So I put the logic to enable a calender button, and a text box that when clicked on opens up the calender, in a user control. I can then reuse that user control in all my aspx pages. </p>