input
stringlengths
51
42.3k
output
stringlengths
18
55k
Is there a function in Delphi to get the current executing thread? <p>I want a function like GetCurrentThread which returns a TThread object of the current executing thread. I know there is a Win32 API call GetCurrentThread, but it returns the thread Id. If there is a possibility to get TThread object from that ID that's also fine.</p>
<p>The latest version of Delphi, Delphi 2009, has a CurrentThread class property on the TThread class.</p> <p>This will return the proper Delphi thread object if it's a native thread. If the thread is an "alien" thread, i.e. created using some other mechanism or on a callback from a third party thread, then it will create a wrapper thread around the thread handle.</p>
How do I specify the exit code of a console application in .NET? <p>I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this?</p>
<p>You can return it from <code>Main</code> if you declare your <code>Main</code> method to return <code>int</code>, or call <a href="https://msdn.microsoft.com/en-us/library/system.environment.exit.aspx"><code>Environment.Exit(code)</code></a>.</p>
Invert 4x4 matrix - Numerical most stable solution needed <p>I want to invert a 4x4 matrix. My numbers are stored in fixed-point format (1.15.16 to be exact).</p> <p>With floating-point arithmetic I usually just build the adjoint matrix and divide by the determinant (e.g. brute force the solution). That worked for me so far, but when dealing with fixed point numbers I get an unacceptable precision loss due to all of the multiplications used. </p> <p>Note: In fixed point arithmetic I always throw away some of the least significant bits of immediate results.</p> <p>So - What's the most numerical stable way to invert a matrix? I don't mind much about the performance, but simply going to floating-point would be to slow on my target architecture.</p>
<p>Meta-answer: Is it really a general 4x4 matrix? If your matrix has a special form, then there are direct formulas for inverting that would be fast and keep your operation count down.</p> <p>For example, if it's a standard homogenous coordinate transform from graphics, like:</p> <pre><code>[ux vx wx tx] [uy vy wy ty] [uz vz wz tz] [ 0 0 0 1] </code></pre> <p>(assuming a composition of rotation, scale, translation matrices)</p> <p>then there's an <a href="http://graphics.stanford.edu/courses/cs248-98-fall/Final/q4.html" rel="nofollow">easily-derivable direct formula</a>, which is</p> <pre><code>[ux uy uz -dot(u,t)] [vx vy vz -dot(v,t)] [wx wy wz -dot(w,t)] [ 0 0 0 1 ] </code></pre> <p>(ASCII matrices stolen from the linked page.)</p> <p>You probably can't beat that for loss of precision in fixed point.</p> <p>If your matrix comes from some domain where you know it has more structure, then there's likely to be an easy answer.</p>
Remote print module in Java <p>I am working on an application that will sport a web-based point of sale interface.</p> <p>The point of sale PC (I am not sure as of now whether it will run on Linux or Windows) must have a fiscal printer attached to it, but like any web app, it is the server which processes all stuff. Both server and PoS machines are on the same LAN.</p> <p>I must send the sale data in real time, and via the fiscal printer which uses the serial port, so printing a PDF or even a web page is not an option.</p> <p>I've been told I could have a little app listening on web services on the client, which in turn talks to the printer instead of the server or the browser, but don't have a clue how to do it. Also, I'll most likely need to listen to any printer feedback (coupon number, for instance, which is generated by the printer) and hand it back to the server.</p> <p>Any ideas?</p>
<p>I did something similar to this a couple of yrs. ago. But in my case the server and the PC where in the same lan. Is your PoS within the lan? If so, I'll explain it to you.</p> <p>In the mean time, if you have the "little app" covered you can take a look at the following:</p> <p><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html" rel="nofollow">http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html</a></p> <p>The print service have a method to discover the printers registered within machine it is running on. So after you receive the message from the server on your app you just have to do something similar to the code shown in the link above:</p> <p>Taked from, <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html" rel="nofollow">http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html</a></p> <pre><code>DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT; PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet(); aset.add(MediaSizeName.ISO_A4); PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset); if (pservices.length &gt; 0) { DocPrintJob pj = pservices[0].createPrintJob(); // InputStreamDoc is an implementation of the Doc interface // Doc doc = new InputStreamDoc("test.ps", flavor); try { pj.print(doc, aset); } catch (PrintException e) { } } </code></pre>
Safehandle in C# <p>What is SafeHandle? how does it differ from IntPtr? When should I use one? What are its advantages?</p>
<p>I think <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx">MSDN</a> is pretty clear in definition:</p> <blockquote> <p>The SafeHandle class provides critical finalization of handle resources, preventing handles from being reclaimed prematurely by garbage collection and from being recycled by Windows to reference unintended unmanaged objects. Before the .NET Framework version 2.0, all operating system handles could only be encapsulated in the IntPtr managed wrapper object.</p> <p>The SafeHandle class contains a finalizer that ensures that the handle is closed and is guaranteed to run, even during unexpected AppDomain unloads when a host may not trust the consistency of the state of the AppDomain. </p> <p>For more information about the benefits of using a SafeHandle, see Safe Handles and Critical Finalization.</p> <p>This class is abstract because you cannot create a generic handle. To implement SafeHandle, you must create a derived class. To create SafeHandle derived classes, you must know how to create and free an operating system handle. This process is different for different handle types because some use CloseHandle, while others use more specific methods such as UnmapViewOfFile or FindClose. For this reason, you must create a derived class of SafeHandle for each operating system handle type; such as MySafeRegistryHandle, MySafeFileHandle, and MySpecialSafeFileHandle. Some of these derived classes are prewritten and provided for you in the Microsoft.Win32.SafeHandles namespace.</p> </blockquote>
How do I configure visual studio to use the code view as the default view for Webservices? <p>When you double click on a class (in 'solution explorer')... if that class happens to be an .asmx.cs webservice... then you get this...</p> <blockquote> <p>To add components to your class, drag them from the Toolbox and use the Properties window to set their properties. To create methods and events for your class, click here to switch to code view.</p> </blockquote> <p>...it's a 'visual design surface' for webservices.</p> <p>(Who actually uses that surface to write webservices?)</p> <p>So what I want to know, how do I configure visual studio to never show me that design view?</p> <p>Or at least, to show me the code view by default?</p>
<p>You can set the default editor for any given file type (.cs, .xml, .xsd, etc). To change the default editor for a given type:</p> <ol> <li>Right-click a file of that type in your project, and select "Open With..."</li> <li>Select your preferred editor. You may want "CSharp Editor".</li> <li>Click "Set as Default".</li> </ol> <p>I don't see the behavior you see with web services, but this should work with all file types in Visual Studio.</p>
How do I declare an impicitly typed variable in VB inline in an ASP.Net page? <p>I want to do the following but in VB: </p> <p>&lt;%=var t = ViewData.Model%></p>
<pre><code>&lt;% Dim t = ViewData.Model %&gt; </code></pre> <p>VB doesn't use a special keyword for implicitly typed variables... just Dim.</p>
PHP Session data not being saved <p>I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $_SESSION['foo'] = "foo" and print it back out on the same page just fine. But when I try to use that same variable on another page it is not set! Is there any php functions or information I can use on my hosts server to see what is going on?</p> <p>Here is an example script that does not work on my hosts' server as of right now:</p> <pre><code>&lt;?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views']+ 1; else $_SESSION['views'] = 1; echo "views = ". $_SESSION['views']; echo '&lt;p&gt;&lt;a href="page1.php"&gt;Refresh&lt;/a&gt;&lt;/p&gt;'; ?&gt; </code></pre> <p>The 'views' variable never gets incremented after doing a page refresh. I'm thinking this is a problem on their side, but I wanted to make sure I'm not a complete idiot first.</p> <p>Here is the phpinfo() for my hosts' server (PHP Version 4.4.7): <img src="http://i.stack.imgur.com/3bv0K.png" alt="alt text"></p>
<p>Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php_sessions which didn't exist anymore. A solution would have been to declare <code>ini_set(' session.save_path','SOME WRITABLE PATH');</code> in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles.</p>
Launch web page from my application in Linux <p>I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build.</p> <p>Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each time and doesn't show the URL that I pass in. I would like it to NOT launch a new version each time but just open a new page in the current open one if it is already running. </p> <p>For windows I use:</p> <pre><code>ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL); </code></pre> <p>For Linux I currently use:</p> <pre><code>pid_t pid; char *args[2]; char *prog=0; char firefox[]={"/usr/bin/firefox"}; if(strstri(filename,".html")) prog=firefox; if(prog) { args[0]=(char *)filename; args[1]=0; pid=fork(); if(!pid) execvp(prog,args); } </code></pre>
<p>If you're writing this for modern distros, you can use <code>xdg-open</code>:</p> <pre><code>$ xdg-open http://google.com/ </code></pre> <p>If you're on an older version you'll have to use a desktop-specific command like <code>gnome-open</code> or <code>exo-open</code>.</p>
Source code management strategies - branching, tagging, forking, etc. - for web apps <p>This posting here (<a href="http://stackoverflow.com/questions/156044/how-do-you-manage-database-revisions-on-a-medium-sized-project-with-branches">http://stackoverflow.com/questions/156044/how-do-you-manage-database-revisions-on-a-medium-sized-project-with-branches</a>) got me wondering how best to work on a web project using branching and deploying to dev, staging, and production (along with local copies).</p> <p>We don't have "releases" per se: if a feature is big enough to be noticeable, we push it live (after requisite testing/etc.), otherwise we batch a few up and, when it feels "comfortable", push those live. The goal is to never have a deploy more than once or twice a month or so because a constantly shifting site tends to make the users a bit uneasy.</p> <p>Here's how we do it, and it feels sort of brittle (currently using svn but considering a switch to git):</p> <ol> <li>Two "branches" - DEV and STAGE with a given release of STAGE marked as TRUNK</li> <li>Developer checks out a copy of TRUNK for every change and creates a branch for it</li> <li>Developer works locally, checking in code frequently (just like voting: early and often)</li> <li>When Developer is comfortable it isn't totally broken, merge the branch with DEV and deploy to the development site.</li> <li>Repeat 3-4 as necessary until the change is "finished"</li> <li>Merge change branch with STAGING, deploy to stage site. Do expected final testing.</li> <li>After some period of time, mark a given revision of STAGE as the TRUNK, and push trunk live</li> <li>Merge TRUNK changes back down to DEV to keep it in sync</li> </ol> <p>Now, some of these steps have significant complexity hand-waved away and in practice are very difficult to do (TRUNK -> DEV always breaks) so I have to imagine there's a better way.</p> <p>Thoughts?</p>
<p>Branching is handy if you expect the work to NOT be completed on time, and you do not have a sufficient body of tests to make continuous integration work. I tend to see branch-crazy development in shops where the programming tasks are far too big to complete predictably and so management wants to wait until just before a release to determine what features should ship. If you are doing that kind of work, then you might consider using distributed version control, where EVERY working directory is a branch naturally and you get all the local check-in and local history you can eat without hurting anyone. You can even cross-merge with other developers outside of the trunk.</p> <p>My preference is when we work in an unstable trunk with branches for release candidates, which are then tagged for release, and which then become the stream for emergency patches. In such a system, you very seldom have more than three branches (last release, current release candidate, unstable trunk). This works if you are doing TDD and have CI on the unstable trunk. And if you require all tasks to be broken down so you can deliver code as often as you desire (usually a task should be only one to two days, and releasable without all the other tasks that compose its feature). So programmers take work, check-out the trunk, do the work, sync up and check in any time all the tests pass. The unstable trunk is always available to branch as a release candidate (if all tests pass) and therefore release becomes a non-event.</p> <p>Overall, better means: fewer branches, shorter tasks, shorter time to release, more tests.</p>
Python Dependency Injection Framework <p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
<p><a href="http://springpython.webfactional.com">Spring Python</a> is an offshoot of the Java-based Spring Framework and Spring Security, targeted for Python. This project currently contains the following features:</p> <ul> <li><a href="http://martinfowler.com/articles/injection.html">Inversion Of Control (dependency injection)</a> - use either classic XML, or the python @Object decorator (similar to the Spring JavaConfig subproject) to wire things together. While the @Object format isn't identical to the Guice style (centralized wiring vs. wiring information in each class), it is a valuable way to wire your python app.</li> <li><a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect-oriented Programming</a> - apply interceptors in a horizontal programming paradigm (instead of vertical OOP inheritance) for things like transactions, security, and caching.</li> <li>DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest.</li> <li>Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated.</li> <li>Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization.</li> <li>Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change.</li> <li>Samples - to help demonstrate various features of Spring Python, some sample applications have been created: <ul> <li>PetClinic - Spring Framework's sample web app has been rebuilt from the ground up using python web containers including: <a href="http://cherrypy.org/">CherryPy</a>. Go check it out for an example of how to use this framework. (NOTE: Other python web frameworks will be added to this list in the future).</li> <li>Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo!</li> <li>Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project.</li> </ul></li> </ul>
Using Mercurial, is there an easy way to diff my working copy with the tip file in the default remote repository <p>When using mercurial, I'd like to be able to diff the working copy of a file with the tip file in my default remote repository. Is there an easy way to do this?</p> <p>I know I can do an "hg incoming -p" to see the patch sets of changes coming in, but it'd be nice to just directly see the actual changes for a particular file that I'd get if I do a pull of the latest stuff (or what I might be about put push out).</p> <p>The easiest thing I can think of right now is to create a little script that takes a look at the default location in .hg/hgrc and downloads the file using curl (if it's over http, otherwise scp it over ssh, or just do a direct diff if it's on the local file system) and then to diff the working copy or the tip against that temporary copy.</p> <p>I'm trying to sell mercurial to my team, and one of my team members brought this up today as something that they're able to do easily in SVN with their GUI tools.</p>
<p>After some digging, I came across the "http://www.selenic.com/mercurial/wiki/index.cgi/RdiffExtension'>rdiff" extension that does most of what I want it to.</p> <p>It doesn't come with mercurial, but it can be installed by cloning the repository:</p> <pre><code>hg clone http://hg.kublai.com/mercurial/extensions/rdiff </code></pre> <p>And then modifing your ~/.hgrc file to load the extension:</p> <pre><code>[extensions] rdiff=~/path/to/rdiff/repo/rdiff.py </code></pre> <p>It's a little quirky in that it actually modifies the existing "hg diff" command by detecting if the first parameter is a remote URL. If it is then it will diff that file against your tip file in your local repo (not the working copy). This as the remote repo is first in the arguments, it's the reverse of what I'd expect, but you can pass "--reverse" to the hg diff command to switch that around.</p> <p>I could see these being potential enhancements to the extension, but for now, I can work around them with a bash/zsh shell function in my starup file. It does a temp checkin of my working copy (held by the mercurial transaction so it can be rolled back), executes the reverse diff, and then rolls the transaction back to return things back to the way they were:</p> <pre><code>hgrdiff() { hg commit -m "temp commit for remote diff" &amp;&amp; hg diff --reverse http://my_hardcoded_repo $* &amp;&amp; hg rollback # revert the temporary commit } </code></pre> <p>And then call it with:</p> <pre><code>hgrdiff &lt;filename to diff against remote repo tip&gt; </code></pre>
Get timer ticks in Python <p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
<p>In the <code>time</code> module, there are two timing functions: <code>time</code> and <code>clock</code>. <code>time</code> gives you "wall" time, if this is what you care about.</p> <p>However, the python <a href="http://docs.python.org/lib/module-time.html">docs</a> say that <code>clock</code> should be used for benchmarking. Note that <code>clock</code> behaves different in separate systems:</p> <ul> <li>on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with "resolution typically better than a microsecond". It has no special meaning, it's just a number (it starts counting the first time you call <code>clock</code> in your process).</li> </ul> <pre> # ms windows t0= time.clock() do_something() t= time.clock() - t0 # t is wall seconds elapsed (floating point) </pre> <ul> <li>on *nix, <code>clock</code> reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code:</li> </ul> <pre> # linux t0= time.clock() do_something() t= time.clock() - t0 # t is CPU seconds elapsed (floating point) </pre> <p>Apart from all that, the <a href="http://docs.python.org/lib/module-timeit.html">timeit</a> module has the <code>Timer</code> class that is supposed to use what's best for benchmarking from the available functionality.</p> <p>¹ unless threading gets in the way…</p> <p>² Python ≥3.3: there are <a href="http://www.python.org/dev/peps/pep-0418/#id18"><code>time.perf_counter()</code> and <code>time.process_time()</code></a>. <code>perf_counter</code> is being used by the <code>timeit</code> module.</p>
Get all items from thread Queue <p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
<p>If you're always pulling all available items off the queue, is there any real point in using a queue, rather than just a list with a lock? ie:</p> <pre><code>from __future__ import with_statement import threading class ItemStore(object): def __init__(self): self.lock = threading.Lock() self.items = [] def add(self, item): with self.lock: self.items.append(item) def getAll(self): with self.lock: items, self.items = self.items, [] return items </code></pre> <p>If you're also pulling them individually, and making use of the blocking behaviour for empty queues, then you should use Queue, but your use case looks much simpler, and might be better served by the above approach.</p> <p><strong>[Edit2]</strong> I'd missed the fact that you're polling the queue from an idle loop, and from your update, I see that the problem isn't related to contention, so the below approach isn't really relevant to your problem. I've left it in in case anyone finds a blocking variant of this useful:</p> <p>For cases where you do want to block until you get at least one result, you can modify the above code to wait for data to become available through being signalled by the producer thread. Eg.</p> <pre><code>class ItemStore(object): def __init__(self): self.cond = threading.Condition() self.items = [] def add(self, item): with self.cond: self.items.append(item) self.cond.notify() # Wake 1 thread waiting on cond (if any) def getAll(self, blocking=False): with self.cond: # If blocking is true, always return at least 1 item while blocking and len(self.items) == 0: self.cond.wait() items, self.items = self.items, [] return items </code></pre>
Regexp recognition of email address hard? <p>I recently read somewhere that writing a regexp to match an email address, taking into account all the variations and possibilities of the standard is extremely hard and is significantly more complicated than what one would initially assume.</p> <p>Can anyone provide some insight as to why that is? </p> <p>Are there any known and proven regexps that actually do this fully?</p> <p>What are some good alternatives to using regexps for matching email addresses?</p>
<p>For the <em>formal</em> e-mail spec, yes, it is technically impossible via Regex due to the recursion of things like comments (especially if you don't remove comments to whitespace first), and the various different formats (an e-mail address isn't always someone@somewhere.tld). You can get close (with some massive and incomprehensible Regex patterns), but a far better way of checking an e-mail is to do the very familiar handshake:</p> <ul> <li>they tell you their e-mail</li> <li>you e-mail them a confimation link with a Guid</li> <li><p>when they click on the link you know that:</p> <ol> <li>the e-mail is correct</li> <li>it exists</li> <li>they own it</li> </ol></li> </ul> <p>Far better than blindly accepting an e-mail address.</p>
How to write an Excel workbook to a MemoryStream in .NET? <p>How do I write an Excel workbook to a <code>MemoryStream</code> without first saving it to the file system?</p> <p>All options within the <code>Microsoft.Office.Interop.Excel.WorkBook</code> save options take a filename.</p>
<p>I have done extensive work with the PIA and with storing Excel files in a document repository and streaming it out to the browser, and I have not been able to find a solution to using the PIA without first writing the contents to the file system first.</p> <p>I think that you are going to have to swallow the bullet and deal with the file system as an intermediary. The good news is that you can just give the file a unique name like a guid or use some other tempfilename method (not sure if one exists in .net) and just delete the contents when you are done.</p>
Increase Stack Size on Windows (GCC) <p>Is there a way to increase the stack size of a Windows application at compile/link time with GCC?</p>
<p>IIRC, In GCC you can provide the --stack,[bytes] parameter to ld.</p> <p>E.g.</p> <pre><code>gcc -Wl,--stack,16777216 -o file.exe file.c </code></pre> <p>To have a stack of 16MiB, I think that the default size is 8MiB.</p>
What is the best way to handle English and Chinese in a Flex application? <p>I have a requirement to be able to provide a flex component in English and several asian languages. I have looked at the flex documentation and it seems that I have to build several swf's, which feels wrong. </p> <p>Does anyone know of a straightforward and practical way of bundling string resources in different languages and handling the fonts?</p>
<p>I guess you know the basics of how to localize a Flex application, but if you would like to know more there's a good and thorough description here: <a href="http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:_Runtime_Localization" rel="nofollow">Runtime Localization</a>.</p> <p>In Flex 3 you have three options on how to solve your problem:</p> <ol> <li>compile all languages into the SWF and switch language at runtime</li> <li>compile a separate SWF for each language</li> <li>compile no, or a default, language into the SWF and load additional languages at runtime</li> </ol> <p>The first option is probably the most common, the least complex and doesn't have many drawbacks. The other two can be used if you have special needs, like having to keep down the size of the SWF at all cost, or need to load all strings from a database at runtime.</p> <p>To implement the first option you create a resource bundle for each language (basically a number of <code>.properties</code> files that lives in a directory named after the locale, for example en_US for US English or sv_SE for Swedish). In the code you refer to strings by calling the resource manager:</p> <pre><code>&lt;Label text="{resourceManager.getString('mybundle', 'mystring")'}/&gt; </code></pre> <p>That will retrieve a string called "mystring" in the resource bundle compiled from "mybundle.properties" in the current locale.</p> <p>To make sure each locale is actually compiled into the application you add <code>-locale=en_US,sv_SE</code> to the compiler flags (but change the <code>en_US,sv_SE</code> part to the languages you have resource bundles for). You also need to add the location of the directories to the source path: <code>-source-path+=locale/{locale}</code> (the "<code>{locale}</code>" part will automatically be replaced by the values of the <code>-locale</code> flag).</p> <p>Now you have compiled all your languages into the SWF and can change languages at runtime. The way to do that is to modify the <code>localeChain</code> property of the resource manager:</p> <pre><code>resourceManager.localeChain = ["sv_SE", "en_US"]; </code></pre> <p>With the settings shown above the resource manager will first look in the Swedish resource bundle, and secondly in the one for US English. You can set another order at any time, and doing so will change all texts in the application then and there.</p> <p>I encourage you to read <a href="http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:_Runtime_Localization" rel="nofollow">the description I referred to above</a>, it explains this in greater detail, and most likely in a more understandable way. It also explains how to do some preparations you need to do before you can compile applications with locales other than en_US.</p> <p>The other problem you have is with fonts. That one is trickier. The best thing would be to have a font that had the full Unicode range of characters, that way you would only need to embed that and any text could be displayed. However, that means that your options are a bit more limited. I know that there is at least one version of Aria in Windows that has an enourmous number of characters, and on the Mac there is a Helvetica (I think, or it might be Lucida Grande, or both) that also has most of the ones you need to display many asian languages.</p> <p>Embedding all languages into the same SWF usually does very little to increase the file size, because text is very lightweight, but fonts are definitely not. Embedding a the whole Unicode version of Arial can increase the file size of a SWF by several megabyte, which kind of sucks for web applications. Depending on the situation you may have to compile one SWF per language, just because the font data would otherwise make the SWF unwieldy.</p>
Does the last element in a loop deserve a separate treatment? <p>When reviewing, I sometimes encounter this kind of loop:</p> <pre><code>i = begin while ( i != end ) { // ... do stuff if ( i == end-1 (the one-but-last element) ) { ... do other stuff } increment i } </code></pre> <p>Then I ask the question: would you write this?</p> <pre><code>i = begin mid = ( end - begin ) / 2 // (the middle element) while ( i != end ) { // ... do stuff if ( i &gt; mid ) { ... do other stuff } increment i } </code></pre> <p>In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements:</p> <pre><code>i = begin mid = ( end - begin ) / 2 //(the middle element) while ( i != mid ) { // ... do stuff increment i } while ( i != end ) { // ... do stuff // ... do other stuff increment i } </code></pre> <p>Now I even saw a <a href="http://stackoverflow.com/questions/151046/c-last-loop-iteration-stl-map-iterator">question</a> on SO on how to write the <code>if</code>-clause in a nice way... And I got sad: something isn't right here.</p> <p>Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time?</p>
<p>I don't think this question should be answered by a principle (e.g. "in a loop, treat every element equally"). Instead, you can look at two factors to evaluate if an implementation is good or bad:</p> <ol> <li>Runtime effectivity - does the compiled code run fast, or would it be faster doing it differently?</li> <li>Code maintainability - Is it easy (for another developer) to understand what is happening here? </li> </ol> <p>If it is faster and the code is more readable by doing everything in one loop, do it that way. If it is slower and less readable, do it another way. </p> <p>If it is faster and less readably, or slower but more readable, find out which of the factors matters more in your specific case, and then decide how to loop (or not to loop).</p>
What do you like/dislike about development user groups? <p>I run a non profit based .net user group called DevEvening (<a href="http://www.devevening.co.uk" rel="nofollow">http://www.devevening.co.uk</a>) and am always looking to improve it. </p> <p>I wondered what people liked and disliked about user groups and what could persuade people to attend who did not already? </p> <p>Since your using this site I guess you have some outside of work interest in development - do you attend user groups?</p> <p>I have been to a number of events and different user groups and although the quality of presentations etc have been mixed I find it is always interesting and useful talking to other developers. </p>
<p>I don't much like developer user groups, as I find that the quality of feedback you get in a site such as this is so much better than you get in a limited geographical area. The principal reason i'd attend is to meet someone I already knew from the web and maybe have a few beers. That said, Microsoft are really making a more imaginative effort in this area, as shown by the <a href="https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032389585&amp;Culture=en-IE" rel="nofollow">emailed link</a> I got this morning. Way to go.</p>
Hooking up Reporting Services 2005SP2 to SQL Server 2008 <p>I am trying to configure Reporting Services 2005SP2 on a machine with SQL 2008 on another hosting the ReportServer DB.</p> <p>When I create the ReportServerDB the DB is created as version C.0.9.45:</p> <p>When, afterwards, I try to initialise Reporting Services, I get an error about an incorrect version number. Reporting Services created a ReportServer DB version C.0.9.45 but now expects a version C.0.8.54.</p> <p>Changing compatibility settings of the DB doesn’t have an effect. And changing the version number sproc in the DB to return what Reporting Services wants to hear only delays the crash until initialisation has started.</p> <p>Any ideas?</p>
<p>I got a reply from microsoft support saying that it is impossible on the same box.</p> <p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=4153333&amp;SiteID=1" rel="nofollow">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=4153333&amp;SiteID=1</a></p>
Is there any website which showcase nice / comprehensive build.xml? <p>What i mean exactly is that build.xml that actually included those plugins like findbugs etc. Or nicely done build.xml </p>
<p>A great resource for sample Ant build files is Google code search. <a href="http://code.google.com/search/#q=build.xml" rel="nofollow">Search Google Code for build.xml</a>. Once you search, narrow it down to "Project Hosting" to get the real meat. You will find dozens of examples of real, working, usable build.xml files.</p> <p>For example, here's the <a href="http://code.google.com/p/fbug/source/browse/branches/firebug1.3/build.xml" rel="nofollow">build file for Firebug</a>, the <a href="http://code.google.com/p/clojure-contrib/source/browse/branches/lazy/build.xml" rel="nofollow">build file for the Clojure language</a>, the <a href="http://code.google.com/p/google-web-toolkit/source/browse/trunk/build.xml?spec=svn5418&amp;r=5418" rel="nofollow">build file for GWT</a> and the <a href="http://code.google.com/p/google-guice/source/browse/build.xml" rel="nofollow">build file for Google Guice</a>.</p> <p>Of course, there are other fine repositories of source code, here is a <a href="https://github.com/search?type=Code&amp;language=XML&amp;q=build.xml&amp;repo=&amp;langOverride=&amp;x=12&amp;y=13&amp;start_value=1" rel="nofollow">build.xml file search on GitHub</a>, a <a href="http://www.google.com/search?q=site%3Asourceforge.net+build.xml" rel="nofollow">Google search of SourceForge.net for build.xml files</a> and a <a href="http://www.google.com/search?q=site%3Asvn.riaforge.org+build.xml" rel="nofollow">Google search of RIAForge.org for build.xml files</a></p> <p>Another good way to find quality build files is a <a href="http://www.google.com/search?q=allinurl%3Abuild.xml" rel="nofollow">Google search for build.xml in the URL</a>, which will result with a good variety. Add to that query an aspect or programming language of choice, and you will have what you need in no time.</p>
Silverlight display problem <p>I have created a nice silverlight control doing exactly what I want it to do, and it looks great :) When I host it in the test projects ASPX sample file or the HTML sample file it shows up nicely.</p> <p>I now have to use the control in my existing ASP.NET 2.0 project, which has a fancy design. The problem I'm having is that the control don't show up exactly how it should:</p> <ul> <li>The loading progress don't show</li> <li>The control usually don't become visible before I move my mouse over the aria where it's contained</li> </ul> <p>Obviously it's something with my HTML/CSS design causing this, but it will be extremely time consuming to find the issue - so does anyone have knowledge in this area? What are the rules around how to make sure the control is displayed properly? What CSS properties should be used?</p> <p>PS: Since I have a 2.0 app, I'm using the object tag approach to Silverlight, and it's contained in a DIV with height and width set in style.</p> <p>Code snippet was requested. It's something like this (basically a copy of the HTML test page from the silverlight test project (which work perfectly)):</p> <pre><code>&lt;div id="silverlightControlHost" style="height: 300px; width: 750px;"&gt; &lt;object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="100%" height="100%"&gt; &lt;param name="source" value="Contiki.SilverLight.FileUploader.xap" /&gt; &lt;param name="onerror" value="onSilverlightError" /&gt; &lt;param name="background" value="white" /&gt; &lt;a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;"&gt; &lt;img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" /&gt; &lt;/a&gt; &lt;/object&gt; &lt;iframe style='visibility: hidden; height: 0; width: 0; border: 0px'&gt;&lt;/iframe&gt; &lt;/div&gt; </code></pre> <p>This DIV is contained in a cell in a table, which again is part of a larger design. There's a lot of CSS as mentioned. Don't know if this helps...</p>
<p>Found the cause myself...</p> <p>It turns out Silverlight has a display problem when the control is placed in a html table. <a href="http://silverlight.net/forums/p/20863/72280.aspx" rel="nofollow">Found information about this on the silverlight forum</a>. It was about the beta 2, but I have upgraded to the release version, and it's still a problem.</p> <blockquote> <p>Try this. Add a height and a width to the table containing the Silverlight control. You may also want to add a single character of white space inside the TD containing the control.</p> <p>Basically when the table was rendered it couldn't 'see' the size of the contents so it either didn't render at all or only rendered to the size of a single white-space character.</p> <p>-- John Stockton</p> </blockquote> <p>My design is quite complex with nested tables, so I haven't actually been able to make it work yet.</p> <p><strong>UPDATE:</strong></p> <p>The actual fix I ended up implementing was a small JavaScript that "refreshes" the containing &lt;DIV&gt;. Here it is:</p> <pre><code>&lt;script type="text/javascript"&gt; function refreshSL() { var div = document.getElementById('silverlightControlHost'); div.style.display = 'block'; } refreshSL(); &lt;/script&gt; </code></pre> <p>I placed this in my HTML below the actual SL markup, and then it worked (I guess calling it on the page loaded event would be the proper thing to do.</p>
Download files to local drive when sshed <p>What is the best way to download files to local hard drive when logged in to another computer using ssh in bash. I'm aware of sftp, but it is not convienent, e.g. it lacks tab completion of directory names. I'm using Ubuntu 8.04.1 . I don't have a public IP and would not like to setup dynamic Dynamic DNS solution.</p>
<p>I'm also running Ubuntu 8.04.1, and if I type</p> <pre><code>$ scp me@myserver.mydomain.com:.bashr&lt;TAB&gt; </code></pre> <p>I do indeed get tab completion (i.e. bash is sshing to my server and getting completion results from the filesystem there). Then</p> <pre><code>$ scp me@myserver.mydomain.com:.bashrc . </code></pre> <p>copies my .bashrc from my server to the current directory on my local machine.</p> <p>If you don't get this, try <code>sudo apt-get install bash-completion</code>, and check that your .bashrc contains the following lines (mine did by default):</p> <pre><code># enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). if [ -f /etc/bash_completion ]; then . /etc/bash_completion fi </code></pre>
database synchronization - SFTP / RMAN / By codes? <p>Which method you all will recommend and why?</p>
<p>Since you mention RMAN, may I assume that you are talking in particular about an Oracle database? Or are you talking about a more generic problem?</p> <p>What is the business purpose of synchronizing the databases? That is going to strongly influence the choice of technology. In the Oracle world, you would have DataGuard if you wanted to have a hot standby, RAC if you wanted to have a single database with load spread across multiple physical nodes of a cluster, Streams and multi-master replication if you wanted to have load spread across multiple geographically distributed databases, RMAN if you wanted to periodically clone a test database from production, etc.</p>
How to communicate between CE 6.0 device (as server) and PC (as client) <p>We're in the process of developing a measurement device that will be running CE 6.0 with CF 3.5 on x86 embedded hardware, a PC is used to control the device and is connected with it using ethernet.</p> <p>We would like to communicate using interfaces (using DCOM (we know it is not supported by default on CE6), .NET Remoting or Web services) instead of using some sort of (custom) protocol. Calling methods defined in an interface is so much easier and elegant then parsing raw data.</p> <p>What would be the best solution in this case?</p>
<p>If you're using CE 6 and .NET Compact Framework 3.5, have you considered using the Windows Communication Foundation (WCF)? You'd have to write your own transport, but when that is done, you will be able to consume your service interfaces with relative ease. </p>
Controlling the WCF XmlSerializer <p>I have some REST web services implemented in WCF. I wish to make these services return "Bad Request" when the xml contains invalid elements.</p> <p>The xml serialization is being handled by XmlSerializer. By default XmlSerializer ignores unknown elements. I know it is possible to hook XmlSerializer.UnknownElement and throw an exception from this handler, but because this is in WCF I have no control over serialization. Any ideas how I might implement this behavior.</p>
<p><em>"I know it is possible to hook XmlSerializer.UnknownElement and throw an exception from this handler, but because this is in WCF I have no control over serialization"</em></p> <p>Its actually possible to do this...</p> <p>In a WCF project that I worked on, we did something similar using the IDispatchMessageFormatter interface.</p> <p>More information can be found here <a href="http://nayyeri.net/blog/use-idispatchmessageformatter-and-iclientmessageformatter-to-customize-messages-in-wcf/" rel="nofollow">http://nayyeri.net/blog/use-idispatchmessageformatter-and-iclientmessageformatter-to-customize-messages-in-wcf/</a> </p> <p>It allows you peak at the message headers, control serialization/deserialization, return status codes etc.</p>
Classic ASP Intranet and New ASP.NET Applications <p>We have an existing classic ASP intranet consisting of hundreds of pages. Its directory structure looks like this...</p> <pre><code>/root app_1 app_2 ... img js style </code></pre> <p>Obviously app_1 and so on have better names in the actual directory structure.</p> <p>Even though the many applications have different behaviour, they are all part of the same intranet and therefore share a common look and feel by including stylesheets via /style, images via /img and client script via /js.</p> <p>The trouble (for me at least) comes when I want to add an intranet application in ASP.NET.</p> <p>Ultimately, I'd like this structure:</p> <pre><code>/root app_1 app_2 dotnetapp_1 dotnetapp_2 ... img js style </code></pre> <p>It seems to me that ASP.NET "applications" like to think of themselves as separate from everything around them (this may just be my comprehension of how they are). You create a new "project" in Visual Studio and it's like you have a new "root" a level below the actual root I want to use. It's like this new application is a thing, standing alone, with its own images and style and whatnot. However, I want it to be a sub-part of the existing intranet.</p> <p>Ultimately I want to be able to make my whole classic ASP intranet the "root" and have ASP.NET "sub-applications" that can still access /style and /img and, I guess for ASP.NET I'll have /masterpages.</p> <p>I've tried this before, but I think VS choked on the couple of hundred classic ASP pages that it added to the "project" when I made my existing intranet root directory the ASP.NET project root (via File->Open->Web Site). I'd be nice to edit my existing classic ASP intranet using VS 2008 SP1 (I currently use the excellent <a href="http://notepad-plus.sourceforge.net/uk/site.htm" rel="nofollow">Notepad++</a>) because I'd like to get more hands on with VS but I guess this isn't absolutely necessary.</p> <p>I also tried treating each new ASP.NET application as an application in its own right, effectively making the /dotnetapp_1 directory the "root" of the application (again, via File->Open->Web Site in VS2008). However, VS then complained when I tried to reference /masterpages because it "belonged to another application." I think I kludged it by adding a virtual directory inside each ASP.NET directory that "pointed" to the root /masterpages but I'm not sure VS was able to happily provide WYSIWYG editing when I did this, as opposed to making a copy of the masterpage in every ASP.NET application I add to the intranet.</p> <p>I'm also quite likely to visit the .NET MVC framework so please offer any answers with that framework in mind. I'm hoping "projects" aren't quite to important with MVC and that rather it's just a bunch of files that creates an application that contributes to the whole (that being the intranet).</p> <p>So, the question is: <strong>How I can best add-on ASP.NET applications to an existing classic ASP intranet (I'm not concerned about the technicalities of session sharing between classic ASP and ASP.NET, only the structural layout of directories and projects) and be able to edit these separate applications in Visual Studio 2008 SP1 and yet have these application "related" to each other by a common, intranet look and feel*?</strong></p> <ul> <li>Please don't just post the answer "use MasterPages." I appreciate MasterPages are .NET's method of sharing styles (and more probably) between related pages in the <em>same</em> application. I get that. What I'm looking for is the best method of adding ASP.NET applications into the existing intranet as smoothly as I can that makes editing each application simple and where each application can share (if possible) an intranet-common style.</li> </ul>
<p>One solution would be to use IIS Manager to configure the website (created for your ASP.NET app by Visual Studio) and add a virtual directory for each of the common folders so that (by the 'virtual' nature of the virtual directory) they will 'appear' to be in the same root folder as your ASP.NET app.</p> <pre><code>/root app_1 app_2 dotnetapp_1 &lt;virtual&gt;img &lt;virtual&gt;js ... img js style </code></pre> <p>You can probably script IIS or edit an XML file if you need to do this in bulk, and I'm sure there must be an even more elegant way to do something similar that doesn't require to much mouse work!</p>
Is the web hosting location important these days? <p>I was recently looking at some web hosting solutions and some of the providers offered various hosting locations e.g. US or UK based servers.</p> <p>My question is: does it really make a difference from the performance point of view? Lets say that I am expecting most of the traffic coming from continental Europe? </p> <p>Would the fact that the servers are based in UK make bigger difference if the traffic was coming from the UK.</p> <p>Any pros and cons of having a website hosted in the same county as the most of the expected traffic?</p>
<p>Yes, distance = latency = slower. That's why Google, Amazon, and the other big sites have multiple datacenters in different regions and even continents.</p>
iSeries SQL Procedure - Check if already exists <p>I have an script that falls over if any of the procedures it is trying to create already exists. How can I check/drop if this procedure is already created?</p>
<p>I would guess something along the lines of:</p> <pre><code>IF EXISTS ( SELECT * FROM SYSPROCS WHERE SPECIFIC_SCHEMA = ??? AND SPECIFIC_NAME = ??? AND ROUTINE_SCHEMA = ??? AND ROUTINE_NAME = ??? ) DROP PROCEDURE ??? </code></pre> <p>I don't know if you actually need the SPECIFIC_* information or not and I don't know how to handle cases where you have two procedures with the same name but different call signatures, but hopefully this gets you on the right track.</p>
In javaDoc, what's the best way of representing attributes in XML? <p>When you're adding javaDoc comments to your code and you're outlining the structure of an XML document that you're passing back, what's the best way to represent attributes? Is there a best practice for this?</p> <p>My general structure for my javaDoc comments is like this:</p> <pre><code>/** * ... * * @return XML document in the form: * * &lt;pre&gt; * &amp;lt;ROOT_ELEMENT&amp;gt; * &amp;lt;AN_ELEMENT&amp;gt; * &amp;lt;MULTIPLE_ELEMENTS&amp;gt;* * &amp;lt;/ROOT_ELEMENT&amp;gt; * &lt;/pre&gt; */ </code></pre>
<p>Not sure I clearly understand your question.</p> <p>My preferred solution would be to embed the schema XSD or DTC in the description of the return parameter. Your solution seems to lead to personal idioms on how to represent things like multiple elements or others. Using a standard like XSD or DTD allows you to have a well know and recognized language on how to describe the structure of a XML document.</p> <p>Regarding the JavaDoc representation if you are using Eclipse you can specify under Save Actions to format your document. This way you can write normally with &gt; and &lt; and see it converted to the escaped HTML codes.</p>
What's the best way to loop through a set of elements in JavaScript? <p>In the past and with most my current projects I tend to use a for loop like this:</p> <pre><code>var elements = document.getElementsByTagName('div'); for (var i=0; i&lt;elements.length; i++) { doSomething(elements[i]); } </code></pre> <p>I've heard that using a "reverse while" loop is quicker but I have no real way to confirm this:</p> <pre><code>var elements = document.getElementsByTagName('div'), length = elements.length; while(length--) { doSomething(elements[length]); } </code></pre> <p>What is considered as best practice when it comes to looping though elements in JavaScript, or any array for that matter?</p>
<p>Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, <strong>you must be careful</strong>, you <strong>can't use it if any of the values in array could be "falsy"</strong>. In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar.</p> <pre><code>var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}]; for (var i=0, item; item = list[i]; i++) { // Look no need to do list[i] in the body of the loop console.log("Looping: index ", i, "item" + item); } </code></pre> <p>Note that this can also be used to loop backwards (as long as your list doesn't have a <code>['-1']</code> property)</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}]; for (var i = list.length - 1, item; item = list[i]; i--) { console.log("Looping: index ", i, "item", item); }</code></pre> </div> </div> </p>
Dynamically instantiate a Ruby class similar to Java <p>How can this line in Java be translated to Ruby:<br /> String className = "java.util.Vector";<br /> ...<br /> Object o = Class.forName(className).newInstance(); </p> <p>Thanks!</p>
<pre><code>Object::const_get('String').new() </code></pre>
Singular/plural searches and stemming <p>I'm discovering a simple solution for singular-plural keywords searches. I heard about stemming but I don't want to use all its features, only plural/singular transformation. The language is Dutch. Have looked at <a href="http://www.snowball.tartarus.org" rel="nofollow">http://www.snowball.tartarus.org</a> before. Does anyone know the simple solution for singular|plural relevant searches? Thanks in advance.</p>
<p>Use a dictionary, a list of stopwords (those you don't want to singularize) plus the rules for the language. If you don't know Dutch then I cannot help you, but show you how it'd be done in Spanish, for instance:</p> <ul> <li>Plurals end with s, if it doesn't then it's done <ul> <li>If it ends with s, <ul> <li>check if it's a verb or conjugation ending with s if it is one, then it's done (verbs could be added to the stopwords list)</li> <li>if it's not a verb, remove s </li> <li>if the word exists in the dictionary, done</li> <li>if it doesn't remove the previous letter, and check it in the dictionary.</li> <li>if it's still not there it's an exception you'll need to check manually to code in the exceptions (I cannot right now think of any, but they always exist :)</li> </ul></li> </ul></li> </ul> <p>Of course this will not translate directly to Dutch.</p> <p>In general stemmers are already done and provide most of what you need, why don't you want them?</p>
Data generators for SQL server? <p>I would like to receive suggestions on the data generators that are available, for SQL server. If posting a response, please provide any features that you think are important. </p> <p>I have never used a application like this, so I am looking to be educated on the topic. Thank you.</p> <p>(My goal is to fill a database with 10,000+ records in each table, to test an application.)</p>
<p>I have used the <a href="http://www.generatedata.com/#generator">data generator</a> in the past. May be worth a look.</p>
Table Column Formatting <p>I'm trying to format a column in a <code>&lt;table/&gt;</code> using a <code>&lt;col/&gt;</code> element. I can set <code>background-color</code>, <code>width</code>, etc., but can't set the <code>font-weight</code>. Why doesn't it work?</p> <pre><code>&lt;table&gt; &lt;col style="font-weight:bold; background-color:#CCC;"&gt; &lt;col&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
<p>As far as I know, you can only format the following using CSS on the <code>&lt;col&gt;</code> element: </p> <ul> <li>background-color</li> <li>border</li> <li>width</li> <li>visibility</li> </ul> <p>This <a href="http://www.quirksmode.org/css/columns.html">page</a> has more info.</p> <p>Herb is right - it's better to style the <code>&lt;td&gt;</code>'s directly. What I do is the following:</p> <pre><code>&lt;style type="text/css"&gt; #mytable tr &gt; td:first-child { color: red;} /* first column */ #mytable tr &gt; td:first-child + td { color: green;} /* second column */ #mytable tr &gt; td:first-child + td + td { color: blue;} /* third column */ &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table id="mytable"&gt; &lt;tr&gt; &lt;td&gt;text 1&lt;/td&gt; &lt;td&gt;text 2&lt;/td&gt; &lt;td&gt;text 3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;text 4&lt;/td&gt; &lt;td&gt;text 5&lt;/td&gt; &lt;td&gt;text 6&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>This won't work in IE however.</p>
CSS Layout, Vis Studio 2005, and AJAX Tab Container <p>In a C# Web app, VS 2005 (I am avoiding 2008 because I find the IDE to be hard to deal with), I am getting into a layout stew.</p> <p>I am moving from absolute positioning toward CSS relative positioning.</p> <p>I'd like to divide the screen into four blocks: top (header band), middle left (a stacked menu), middle right (content - here the AJAX tab container), and bottom (footer band), with all 4 blocks positioned relatively, but the controls in the middle right (content) block positioned absolutely relative to the top left corner of the block. A nice side benefit would be to have the IDE design window show all controls as they actually would be displayed, but I doubt this is possible. The IDE is positioning all controls inside the tab panels relative to the top left of the design window; quite a mess.</p> <p>Right now, my prejudice is that CSS is good for relatively positioning blocks, artwork, text etc, but not good for input forms where it is important to line up lots of labels, text boxes, ddl's, check boxes, etc.</p> <p>At any rate, my CSS is not yet up to the task - does anyone know of a good article, book, blog, etc which discusses CSS as it is implemented in ASP.NET, and which might include an example with an AJAX tab control? Any help would be appreciated. </p> <p>Many thanks</p> <p>Mike Thomas </p>
<p>So far as I know, there's nothing specific to ASP.NET, and you are right (at least in 2008) about it not using referenced stylesheets.</p> <p>These may be of use to you, however:</p> <p><a href="http://www.positioniseverything.net/" rel="nofollow">http://www.positioniseverything.net/</a> - Position is Everything, an excellent CSS resource.</p> <p><a href="http://www.alistapart.com/topics/code/css/" rel="nofollow">http://www.alistapart.com/topics/code/css/</a> - A List Apart's CSS section, advice on specific techniques.</p> <p>Essentially, what you want is 4 main divs for your sight: header, footer, menu, content. Position each div as you like, and then adjust the positioning of their children, which most browsers will treat as 'position relative to my parent' (unless it's absolute, IIRC).</p>
How to position one element relative to another with jQuery? <p>I have a hidden DIV which contains a toolbar-like menu.</p> <p>I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them.</p> <p>Is there a built-in function which will move the menu DIV to the top right of the active (mouse hover) DIV? I'm looking for something like <code>$(menu).position("topright", targetEl);</code></p>
<p><strong>tl;dr:</strong> (try it <a href="http://jsfiddle.net/wjbuys/QrrpB/">here</a>)</p> <p>If you have the following HTML:</p> <pre><code>&lt;div id="menu" style="display: none;"&gt; &lt;!-- menu stuff in here --&gt; &lt;ul&gt;&lt;li&gt;Menu item&lt;/li&gt;&lt;/ul&gt; &lt;/div&gt; &lt;div class="parent"&gt;Hover over me to show the menu here&lt;/div&gt; </code></pre> <p>then you can use the following JavaScript code:</p> <pre><code>$(".parent").mouseover(function() { // .position() uses position relative to the offset parent, var pos = $(this).position(); // .outerWidth() takes into account border and padding. var width = $(this).outerWidth(); //show the menu directly over the placeholder $("#menu").css({ position: "absolute", top: pos.top + "px", left: (pos.left + width) + "px" }).show(); }); </code></pre> <p><strong>But it doesn't work!</strong></p> <p>This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the <code>#menu</code> element is, use:</p> <pre><code>$(this).append($("#menu")); </code></pre> <p>just before the line that positions the <code>#menu</code> element.</p> <p><strong>But it still doesn't work!</strong></p> <p>You might have some weird layout that doesn't work with this approach. In that case, just use <a href="http://jqueryui.com/demos/position/">jQuery.ui's position plugin</a> (as mentioned in an <a href="http://stackoverflow.com/a/2781557/22107">answer</a> below), which handles every conceivable eventuality. Note that you'll have to <code>show()</code> the menu element before calling <code>position({...})</code>; the plugin can't position hidden elements.</p> <p><strong>Update notes 3 years later in 2012:</strong></p> <p>(The original solution is archived <a href="http://jsfiddle.net/wjbuys/LCt7z/">here</a> for posterity)</p> <p>So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:</p> <ul> <li>the menu's offset parent is not the placeholder's offset parent</li> <li>the placeholder has a border/padding</li> </ul> <p>Luckily, jQuery introduced methods (<code>position()</code> and <code>outerWidth()</code>) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, <code>append</code>ing the menu element to the placeholder works (but will break CSS rules based on nesting).</p>
Math.IEEERemainder returns negative results. Why? <p>The .net framework includes Math.IEEERemainder(x, y) in addition to the standard mod operator. What is this function really doing? I dont understand the negative numbers that this produces.</p> <p>Example:</p> <pre><code>Math.IEEERemainder(0, 2) = 0 Math.IEEERemainder(1, 2) = 1 Math.IEEERemainder(2, 2) = 0 Math.IEEERemainder(3, 2) = -1 </code></pre>
<p>If you read the example given at <a href="http://msdn.microsoft.com/en-us/library/system.math.ieeeremainder.aspx" rel="nofollow">System.Math.IEEERemainder's MSDN page</a>, you'll notice that two positive numbers can have a negative remainder.</p> <blockquote> <p><strong>Return Value</strong></p> <p>A number equal to <em>x - (y Q)</em>, where <em>Q</em> is the quotient of <em>x / y</em> rounded to the nearest integer (if <em>x / y</em> falls halfway between two integers, the even integer is returned).</p> </blockquote> <p>So: 3 - (2 * (round(3 / 2))) = -1</p> <pre><code>/* ... Divide two double-precision floating-point values: 1) The IEEE remainder of 1.797693e+308/2.00 is 0.000000e+000 2) The IEEE remainder of 1.797693e+308/3.00 is -1.000000e+000 Note that two positive numbers can yield a negative remainder. */ </code></pre> <h2>Epilogue</h2> <p>The actual question could be, "Why do we have two remainder operations?" When dealing with floating point data, you always need to be cognizant of your floating point standard. Since we're in the 21st century, most everything is on IEEE 754 and very few of us worry about say VAX F_Float versus IEEE 754.</p> <p>The <a href="http://stackoverflow.com/questions/127776/where-can-you-find-the-c-language-specifications">C# standard</a> states that the remainder operator (Section 7.7.3), when applied to floating point arguments, is analogous to the remainder operator when applied to integer arguments. That is, the same mathematical formula<sup>1</sup> is used (with additional considerations for corner cases associated with floating point representations) in both integer and floating point remainder operations.</p> <p>Therefore, if you are looking to have your remainder operations on floating point numbers conform to your current IEEE 754 rounding modes, it is advisable to use <strong>Math.IEEERemainder</strong>. However, if your usage is not particularly sensitive to the subtle difference in rounding produced by the C# remainder operator, then continue using the operator.</p> <ol> <li>Given: z = x % y, then z = x - (x / y) * y</li> </ol>
Upgrading SVN 1.4 to 1.5.3 and CC.Net from 1.3 to 1.4 <p>I think this is a multi-part question, so bear with me.</p> <p>Currently all of our developers use the version of Tortise built for SVN 1.4 and our SVN server is running 1.4. Our build server is running CC.Net and is using SVN 1.4.</p> <p>We want to upgrade. </p> <p>I've established that upgrading our clients to 1.5, then our server to 1.5 will work for us. However, the question comes in with CC.Net. Can we just upgrade the install of SVN on our build server to SVN 1.5? Or do we have to upgrade the install of CC.Net too? We'd like to also take this time to upgrade CC.Net, however, we'd like to make sure the SVN upgrade is done first, then come back and do CC.Net.</p> <p>Also adding to this mix is that in some of our projects we maintain a 'tools' folder that may or may not contain the binaries for SVN due to the nAnt scripts we use in those projects. I assume that if we upgrade the CC.Net server install of SVN to 1.5, we'll also need to update all of those projects as the CI server uses the same working directory as the nAnt scripts that get executed.</p> <p>clear as mud?</p>
<p>Hard to answer as it seems you're asking for a plan for your environment, which I'm not in.</p> <p>However, here's what I'd do:</p> <ul> <li>Upgrade cc.net (you have a known good starting point, and this is the most likely breaking step. do it without any other variables so it is easier to roll back)</li> <li>Test &amp; Verify</li> <li>Upgrade all the svn clients including the binaries in your "tools" folder</li> <li>Test &amp; Verify</li> <li>Upgrade the svn server</li> <li>Test &amp; Verify</li> <li>Test &amp; Verify</li> </ul>
How do I set up a mock queue using mockrunner to test an xml filter? <p>I'm using the mockrunner package from <a href="http://mockrunner.sourceforge.net/" rel="nofollow">http://mockrunner.sourceforge.net/</a> to set up a mock queue for JUnit testing an XML filter which operates like this:</p> <ol> <li>sets recognized properties for an ftp server to put and get xml input and a jms queue server that keeps track of jobs. Remotely there waits a server that actually parses the xml once a queue message is received.</li> <li>creates a remote directory using ftp and starts a queue connection using mqconnectionfactory to the given address of the queue server.</li> <li>once the new queue entry is made in 2), the filter waits for a new queue message to appear signifying the job has been completed by the remote server. The filter then grabs the modified xml file from the ftp and passes it along to the next filter. </li> </ol> <p>The JUnit test I am working on simply needs to emulate this environment by starting a local ftp and mock queue server for the filter to connect to, then waiting for the filter to connect to the queue and put the new xml input file on a local directory via a local ftp server, wait for the queue message and then modify the xml input slightly, put the modified xml in a new directory and post another message to the queue signifying the job has completed. </p> <p>All of the tutorials I have found on the net have used EJB and JNDI to lookup the queue server once it has been made. If possible, I'd like to sidestep that route by just creating a mock queue on my local machine and connecting to it in the simplest manner possible, not using EJB and JNDI.</p> <p>Thanks in advance!</p>
<p>I'd recommend having a look at using <a href="http://activemq.apache.org/camel/" rel="nofollow">Apache Camel</a> to create your test case. Then its really easy to switch your test case from any of the <a href="http://activemq.apache.org/camel/components.html" rel="nofollow">available components</a> and most importantly Camel comes with some really handy <a href="http://activemq.apache.org/camel/mock.html" rel="nofollow">Mock Endpoints</a> which makes it super easy to test complex routing logic particularly with asynchronous operations.</p> <p>If you also use Spring, then maybe start by trying out these <a href="http://activemq.apache.org/camel/spring-testing.html" rel="nofollow">Spring unit tests with mock endpoints in Camel</a> which let you inject the mock endpoints to perform assertions on together with the ProducerTemplate object to make it really easy to fire your messages for your test case. e.g. see the last example on that page.</p> <p>Start off using simple endpoints like the <a href="http://activemq.apache.org/camel/seda.html" rel="nofollow">SEDA endpoint</a> - then when you've got your head around the core spring/mock framework, try using the <a href="http://activemq.apache.org/camel/jms.html" rel="nofollow">JMS endpoint</a> or <a href="http://activemq.apache.org/camel/ftp.html" rel="nofollow">FTP endpoint</a> endpoints etc.</p>
Tool for translation of Oracle PL/SQL into Postgresql PL/pgSQL <p>Is there a tool (preferably free) which will translate Oracle's PL/SQL stored procedure language into Postgresql's PL/pgSQL stored procedure language?</p>
<p>There is a tool available at <a href="http://ora2pg.darold.net/" rel="nofollow">http://ora2pg.darold.net/</a> which can be used to transalate Oracle Schemas to Postgres schemas, but I'm not sure if it will also translate the stored procedures. But it might provide a place to start.</p>
http/AJAX (GWT) vs Eclipse gui for thin client deployment <p>I am starting a project for which we will have a thin client, sending requests and getting responses from a server.</p> <p>We are still in the planning stages, so we have a choice to settle on either an Eclipse based GUI (Eclipse plugin) or using GWT as a fromtend for the application.</p> <p>I am not very familiar with Eclipse as a GUI (Nor with GWT) but do know 'normal' Java.</p> <p>What would be the main benefits and drawbacks of either approach?</p> <p><strong>Edit:</strong> Addressing the questions posed:</p> <ul> <li>The project, if Eclipse based, would be using the core Eclipse gui (No coding tools, just bare bones) and the GUI would be packaged with it.</li> <li>I have been looking at GWT and so far seems the best choice, but still have some research to do.</li> <li>Communication method is a variant of CORBA (In house libraries)</li> </ul>
<p>Coming from someone who has just as much experience as you do (haven't developed any Eclipse based plugins or anything with GWT), this is purely an opinion from another set of eyes on your problem.</p> <p>Purely from the standpoint of this application being served from a thin client, I would think GWT would fit the bill for this situation a bit better. It would certainly be a bit lighter and would not require the overhead that an Eclipse Plugin would.</p> <p>I also think this would make deploying updates a lot easier.</p>
Performance Testing MSMQ Server <p>Has anyone done any sort of performance tests against MSMQ?</p> <p>We have a solution in prod environment where errors are added to a MSMQ for distribution to databases or event monitors.</p> <p>We need to test the capacity of this system but not sure how to start.</p> <p>Anyone know any tools or have any tips?</p>
<p>try overloading it with a test program and see where it balks/fails</p> <p>[analgous to "destructive testing" in materials engineering]</p>
What is the best way to separate UI (designer/editor) logic from the Package framework (like Visual Studio Package) <p>I want to separate concerns here. Create and embed all the UI logic for the Custom XML designer, object model, validations etc in to a separate assembly. Then the Package framework should only register the designer information and ask for a UI Service and everything works magically.</p> <p>This way I don't need to play with the Package framework (Visual Studio Package) assembly, when I need to modify the UI designer.</p> <p>This question also applies to anything where you have to separate the UI logic from the Skeleton framework that loads it up, like a plugin.</p> <p>I have several choices a ServiceProvider model, a plugin model or may be other.</p> <p>Any samples, suggestions for patterns, links are welcome.</p> <p>Update 1: What I am looking for is a thought such as - "Does Prism (Composite WPF) fit the bill? Has anyone worked on a project/application which does the separation of concerns just like I mentioned above? etc" (I am still looking out for answers)</p>
<p>I've created a VSPackage that loads an editor. The Editor sits in a separate assembly and implements an interface that I defined. The VSPackage works with the interface, so any changes I make to the editor (and its assembly) does not affect the VSPackage as long as I don't change the interface.</p>
Search file in directory using complex pattern <p>I am looking for a C# library for getting files or directory from a directory using a complex pattern like the one used in Ant:</p> <ul> <li><code>dir1/dir2/**/SVN/*</code> --> Matches all files in SVN directories that are located anywhere in the directory tree under dir1/dir2</li> <li><code>**/test/**</code> --> Matches all files that have a test element in their path, including test as a filename.</li> <li>...</li> </ul> <p>Do I need to code it myself? extract what I want from NAnt? Or this library exists and my google skill sucks.</p> <p><code>Directory.GetFiles(String path, String searchPattern)</code> doesn't handle directory pattern and <a href="http://www.codeplex.com/FileDirectoryPath" rel="nofollow">NDepend.Helpers.FileDirectoryPath</a> neither (it's a great library for path manipulation by the way)</p>
<p>Coding it yourself wouldnt be that hard.</p> <p>Just use a correctly formulated regular expression with System.IO methods to build the full path</p>
In PowerShell, how can I determine the root of a drive (supposing it's a networked drive) <p>In PowerShell, even if it's possible to know if a drive is a network drive: see <a href="http://stackoverflow.com/questions/158359/in-powershell-how-can-i-determine-if-the-current-drive-is-a-networked-drive-or">http://stackoverflow.com/questions/158359/in-powershell-how-can-i-determine-if-the-current-drive-is-a-networked-drive-or</a></p> <p>When I try to get the "root" of the drive, I get back the drive letter.</p> <p>The setup: MS-Dos "net use" shows that H: is really a mapped network drive:</p> <pre><code>New connections will be remembered. Status Local Remote Network ------------------------------------------------------------------------------- OK H: \\spma1fp1\JARAVJ$ Microsoft Windows Network The command completed successfully. </code></pre> <p>Get-PSDrive tells us that the Root is H:</p> <pre><code>PS:24 H:\temp &gt;get-psdrive h Name Provider Root CurrentLocation ---- -------- ---- --------------- H FileSystem H:\ temp </code></pre> <p>and using system.io.driveinfo does not give us a complete answer:</p> <pre><code>PS:13 H:\ &gt;$x = new-object system.io.driveinfo("h:\") PS:14 H:\ &gt;$x.DriveType Network PS:15 H:\ &gt;$x.RootDirectory Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 29/09/2008 16:45 h:\ </code></pre> <p>Any idea of how to get that info?</p> <p>Thanks</p>
<p>The trick is that the attribute name is different than expected. Try:</p> <p><code>(Get-PSDrive h).DisplayRoot</code></p>
How do you find the largest font size that won't break a given text? <p>I'm trying to use CSS (<strong>under <code>@media print</code></strong>) and JavaScript to print a one-page document with a given piece of text made as large as possible while still fitting inside a given width. The length of the text is not known beforehand, so simply using a fixed-width font is not an option.</p> <p>To put it another way, I'm looking for proper resizing, so that, for example, "IIIII" would come out in a much larger font size than "WWWWW" because "I" is much skinnier than "W" in a variable-width font.</p> <p>The closest I've been able to get with this is using JavaScript to try various font sizes until the <code>clientWidth</code> is small enough. <strong>This works well enough for screen media, but when you switch to print media</strong>, is there any guarantee that the 90 DPI I appear to get on my system (i.e., I put the margins to 0.5in either side, and for a text resized so that it fits just within that, I get about 675 for <code>clientWidth</code>) will be the same anywhere else? How does a browser decide what DPI to use when converting from pixel measurements? Is there any way I can access this information using JavaScript?</p> <p>I would love it if this were just a CSS3 feature (<code>font-size:max-for-width(7.5in)</code>) but if it is, I haven't been able to find it.</p>
<p>The CSS font-size property accepts <a href="http://htmlhelp.com/reference/css/units.html#length" rel="nofollow">length units</a> that include absolute measurements in inches or centimeters: </p> <blockquote> <p>Absolute length units are highly dependent on the output medium, and so are less useful than relative units. The following absolute units are available:</p> <ul> <li>in (inches; 1in=2.54cm)</li> <li>cm (centimeters; 1cm=10mm)</li> <li>mm (millimeters)</li> <li>pt (points; 1pt=1/72in)</li> <li>pc (picas; 1pc=12pt)</li> </ul> </blockquote> <p>Since you don't know how many characters your text is yet, you may need to use a combination of javascript and CSS in order to dynamically set the font-size property correctly. For example, take the length of the string in characters, and divide 8.5 (assuming you're expecting US letter size paper) by the number of characters and that gives you the size in inches to set the font-size to for that chunk of text. Tested the font-size with absolute measurements in Firefox, Safari, and IE6 so it should be pretty portable. Hope that helps.</p> <p><strong>EDIT</strong>: Note that you may also need to play around with settings such as the letter-spacing property as well and experiment with what font you use, since the font-size setting isn't really the width of the letters, which will be different based on letter-spacing, and font, proportional to length. Oh, and using a monospace font helps ;)</p>
Can you combine multiple images into a single one using JavaScript? <p>I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?</p> <p><strong>Update Oct 1, 2008:</strong></p> <p>Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <code>&lt;div&gt;</code> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.</p> <p>It then got me thinking about online image editors like <a href="http://www.picnik.com/">Picnik</a> and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?</p>
<p>I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.</p> <pre><code>&lt;img id="img1" src="imgfile1.png"&gt; &lt;img id="img2" src="imgfile2.png"&gt; &lt;canvas id="canvas"&gt;&lt;/canvas&gt; &lt;script type="text/javascript"&gt; var img1 = document.getElementById('img1'); var img2 = document.getElementById('img2'); var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); canvas.width = img1.width; canvas.height = img1.height; context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 0.5; //Remove if pngs have alpha context.drawImage(img2, 0, 0); &lt;/script&gt; </code></pre> <p>Or, if you want to load the images on the fly:</p> <pre><code>&lt;canvas id="canvas"&gt;&lt;/canvas&gt; &lt;script type="text/javascript"&gt; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); Image img1 = new Image(); Image img2 = new Image(); img1.onload = function() { canvas.width = img1.width; canvas.height = img1.height; img2.src = 'imgfile2.png'; }; img2.onload = function() { context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 0.5; //Remove if pngs have alpha context.drawImage(img2, 0, 0); }; img1.src = 'imgfile1.png'; &lt;/script&gt; </code></pre>
Using Linq with WCF <p>I am looking for any examples or guides to using Linq over WCF (n-tier application). Please specify if you are showing something for Linq-to-SQL or Linq-to-entities. I would like to see usage examples for both. </p> <p>I am wondering how things like deffered execution works over WCF (if it works at all)? Cyclic references support and so on... </p> <p>Any information to make this a quick start guide to using Linq with WCF is helpful.</p>
<p>There isn't any LINQ provider that I'm aware of for generic WCF-based queries. <a href="http://blogs.msdn.com/astoriateam/archive/2007/12/11/linq-to-ado-net-data-services.aspx" rel="nofollow">LINQ to ADO.NET Data Services</a>, however, lets you query an Entity model over WCF/REST.</p> <p>From <a href="http://blogs.msdn.com/aconrad/archive/2007/12/10/linq-to-rest.aspx" rel="nofollow">Andy Conrad's blog</a>:</p> <pre><code> static void Main(string[] args) { var context=new WebDataContext("http://localhost:18752/Northwind.svc"); var query = from p in context.CreateQuery&lt;Product&gt;("Products") where p.UnitsInStock &gt; 100 select p; foreach (Product p in query) { Console.WriteLine(p.ProductName+", UnitsInStock="+p.UnitsInStock); } } </code></pre>
Update fonts recursively on a Delphi form <p>I'm trying to iterate all the controls on a form and enable ClearType font smoothing. Something like this:</p> <pre><code>procedure TForm4.UpdateControls(AParent: TWinControl); var I: Integer; ACtrl: TControl; tagLOGFONT: TLogFont; begin for I := 0 to AParent.ControlCount-1 do begin ACtrl:= AParent.Controls[I]; // if ParentFont=False, update the font here... if ACtrl is TWinControl then UpdateControls(Ctrl as TWinControl); end; end; </code></pre> <p>Now, is there a easy way to check if <code>ACtrl</code> have a <code>Font</code> property so i can pass the <code>Font.Handle</code> to somethink like:</p> <pre><code>GetObject(ACtrl.Font.Handle, SizeOf(TLogFont), @tagLOGFONT); tagLOGFONT.lfQuality := 5; ACtrl.Font.Handle := CreateFontIndirect(tagLOGFONT); </code></pre> <p>Thank you in advance.</p>
<p>You use TypInfo unit, more specifically methods IsPublishedProp and GetOrdProp.</p> <p>In your case, it would be something like:</p> <pre><code>if IsPublishedProp(ACtrl, 'Font') then ModifyFont(TFont(GetOrdProp(ACtrl, 'Font'))) </code></pre> <p>A fragment from one of my libraries that should put you on the right path:</p> <pre><code>function ContainsNonemptyControl(controlParent: TWinControl; const requiredControlNamePrefix: string; const ignoreControls: string = ''): boolean; var child : TControl; iControl: integer; ignored : TStringList; obj : TObject; begin Result := true; if ignoreControls = '' then ignored := nil else begin ignored := TStringList.Create; ignored.Text := ignoreControls; end; try for iControl := 0 to controlParent.ControlCount-1 do begin child := controlParent.Controls[iControl]; if (requiredControlNamePrefix = '') or SameText(requiredControlNamePrefix, Copy(child.Name, 1, Length(requiredControlNamePrefix))) then if (not assigned(ignored)) or (ignored.IndexOf(child.Name) &lt; 0) then if IsPublishedProp(child, 'Text') and (GetStrProp(child, 'Text') &lt;&gt; '') then Exit else if IsPublishedProp(child, 'Lines') then begin obj := TObject(cardinal(GetOrdProp(child, 'Lines'))); if (obj is TStrings) and (Unwrap(TStrings(obj).Text, child) &lt;&gt; '') then Exit; end; end; //for iControl finally FreeAndNil(ignored); end; Result := false; end; { ContainsNonemptyControl } </code></pre>
Get the NTLM credentials from the Response on an APSX page <p>I have an ASPX page (On server A) which is invoked using NTLM credentials. Part of that page's job is to call an HTML page (On server B) and proxy it back to the client. (The firewall allows access to A, but not to B. The user would normally be allowed access to both servers.). Server B is also not open to anonymous access, so I need to supply credentials to it.</p> <p>If I hardcode some credentials (as per the attached code), it works, but ideally I would echo the credentials that were received by the .aspx page. Is there some way to get those NetworkCredentials so I can pass them on?</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { Response.Clear(); WebClient proxyFile = new WebClient(); CredentialCache cc = new CredentialCache(); cc.Add(new Uri("http://serverB/"), "NTLM", new NetworkCredential("userName", "password", "domain")); proxyFile.Credentials = cc; Stream proxyStream = proxyFile.OpenRead("http://serverB/Content/webPage.html"); int i; do { i = proxyStream.ReadByte(); if (i != -1) { Response.OutputStream.WriteByte((byte)i); } } while (i != -1); Response.End(); } </code></pre>
<p>You can certainly obtain the login name of the caller, but not the password. NTLM uses a challenge/response mechanism, so the password is never transmitted. Your server must have access to a password-equivalent (a hash) in order to form the challenge and check the response, but even if you can get hold of it that password-equivalent will be no use to you in trying to form credentials that will be accepted by server B.</p> <p>If you can set up impersonation, as described in another answer, even that doesn't necessarily get you what you want. By default, an impersonating server process is not allowed to transmit its identity to another server. That second hop is known as delegation and needs to be configured explicitly on the servers involved (and/or in Active Directory).</p> <p>Apart from delegation I think your only option is to maintain a database of credentials that server A can access and present to server B. Building that in a secure manner is a subtle and time-consuming process. On the other hand, there is a reason why delegation is disabled by default. When I log into a server, do I want it to be allowed to use my identity for accessing other servers? Delegation is the simplest option for you, but you'll need to be sure that server A can't be compromised to do irresponsible things with your users' identities.</p>
Easiest way to migrate Word 2003 custom macro toolbars into Word 2007? <p>I have a series of macros and toolbars that I developed for Word 2003. Now that my office is upgrading to Word 2007, I need to migrate them. The macros themselves migrate with zero effort, but the toolbars are a different issue. A random subset of the toolbars show up in the "Add-Ins" ribbon tab, but I haven't found a way to control which ones. </p> <p>Something that may be a complication is that I deploy the macros by placing a template into a user's Word STARTUP folder (C:\Documents and Settings\username\Application Data\Microsoft\Word\STARTUP). While I can add macros from normal.dot into the Quick Access Toolbar, I cannot add macros from this startup template. I'd like a better, more structured layout anyway. </p> <p>So, what's the easiest way to replicate my custom macro toolbars in Word 2007?</p>
<p>The macros and toolbars that I developed for Word 2003 are in a number of .dot files. I simply put these .dot files into my Startup folder. I restarted Word'07 an wallah, these Macro toolbars appeared in the Add-Ins ribbon.</p> <p>Good Luck</p>
Resetting Buffers in Vim <p>Is it possible to reset the alternate buffer in a vim session to what it was previously?</p> <p>By alternate buffer, I mean the one that is referred to by #, i.e. the one that is displayed when you enter cntl-^.</p> <p>Say I've got two files open main.c and other.c and :ls gives me:</p> <pre><code> 1 %a "main.c" lines 27 2 # "other.c" lines 56 </code></pre> <p>Say I open another file, e.g. refer.c, :ls will now give me:</p> <pre><code> 1 %a "main.c" lines 27 2 "other.c" lines 56 3 # "refer.c" lines 125 </code></pre> <p>If I delete the buffer containing refer.c, :ls now shows:</p> <pre><code> 1 %a "main.c" lines 27 2 "other.c" lines 56 </code></pre> <p>But if I do a cntl-^, refer.c will be displayed again!</p> <p>Is there some way to get vim to reset the alternate buffer back to what it last was automatically? A "history" of alternate buffers?</p> <p>Or am I stuck with doing a :2 b to reload other.c into the alternate buffer?</p> <p>Or maybe there is a good reason for this behaviour?</p>
<p>In this case, "alternate" just means "previous". So, yes, :b2 (or 2 ctrl-6) is probably the easiest way to change which two buffers will be toggled by ctrl-6.</p> <p>Also, take a look at the :keepalt command.</p>
Eclipse RCP Toolbar buttons with the Eclipse Look <p>In Eclipse, its easy to specify buttons for your toolbar using the ActionSets extension point. However, when I need to specify some items programmatically, I can't get the same look. I don't believe that the framework is using native buttons for these, but so far, I can't find the right recipe to match the Eclipse look. I wanted to see if anyone has found the right snippet to duplicate this functionality in code.</p>
<p>It's difficult to tell from your question, but it sounds like you may be attempting to add a ControlContribution to the toolbar and returning a Button. This would make the button on the toolbar appear like a native button like you seem to be describing. This would look something like this:</p> <pre><code>IToolBarManager toolBarManager = actionBars.getToolBarManager(); toolBarManager.add(new ControlContribution("Toggle Chart") { @Override protected Control createControl(Composite parent) { Button button = new Button(parent, SWT.PUSH); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Perform action } }); } }); </code></pre> <p>Instead you should add an Action to the toolbar. This will create a button on the toolbar that matches the standard eclipse toolbar buttons. This would look something like this:</p> <pre><code>Action myAction = new Action("", imageDesc) { @Override public void run() { // Perform action } }; IToolBarManager toolBarManager = actionBars.getToolBarManager(); toolBarManager.add(myAction); </code></pre>
RAII vs. exceptions <p>The more we use RAII in C++, the more we find ourselves with destructors that do non-trivial deallocation. Now, deallocation (finalization, however you want to call it) can fail, in which case exceptions are really the only way to let anybody upstairs know of our deallocation problem. But then again, throwing-destructors are a bad idea because of the possibility of exceptions being thrown during stack unwinding. <code>std::uncaught_exception()</code> lets you know when that happens, but not much more, so aside from letting you log a message before termination there's not much you can do, unless you're willing to leave your program in an undefined state, where some stuff is deallocated/finalized and some not.</p> <p>One approach is to have no-throw destructors. But in many cases that just hides a real error. Our destructor might, for example, be closing some RAII-managed DB connections as a result of some exception being thrown, and those DB connections might fail to close. This doesn't necessarily mean we're ok with the program terminating at this point. On the other hand, logging and tracing these errors isn't really a solution for every case; otherwise we would have had no need for exceptions to begin with. With no-throw destructors we also find ourselves having to create "reset()" functions that are supposed to be called before destruction - but that just defeats the whole purpose of RAII.</p> <p>Another approach is just to <a href="http://www.kolpackov.net/projects/c++/eh/dtor-1.xhtml">let the program terminate</a>, as it's the most predictable thing you can do.</p> <p>Some people suggest chaining exceptions, so that more than one error can be handled at a time. But I honestly never actually seen that done in C++ and I've no idea how to implement such a thing.</p> <p>So it's either RAII or exceptions. Isn't it? I'm leaning toward no-throw destructors; mainly because it keeps things simple(r). But I really hope there's a better solution, because, as I said, the more we use RAII, the more we find ourselves using dtors that do non-trivial things.</p> <p><strong>Appendix</strong></p> <p>I'm adding links to interesting on-topic articles and discussions I've found:</p> <ul> <li><a href="http://www.kolpackov.net/projects/c++/eh/dtor-1.xhtml">Throwing Destructors</a></li> <li>StackOverflow discussion on the <a href="http://stackoverflow.com/questions/164372/is-there-a-good-way-around-the-problems-of-structured-exception-handling-try-ex">problems with SEH</a></li> <li>StackOverflow discussion on <a href="http://stackoverflow.com/questions/130117/throwing-exceptions-out-of-a-destructor#130123">throwing-destructors</a> (thanks, Martin York)</li> <li><a href="http://www.joelonsoftware.com/items/2003/10/13.html">Joel on Exceptions</a></li> <li><a href="http://blogs.msdn.com/larryosterman/archive/2004/09/10/228068.aspx">SEH Considered Harmful</a> </li> <li><a href="http://bartdesmet.net/blogs/bart/archive/2006/04/04/clr-exception-handling-from-a-to-z-everything-you-didn-t-want-to-know-about-try-catch-finally-fault-filter.aspx">CLR Exception Handling</a> which also touches on exception chaining</li> <li><a href="http://www.gotw.ca/gotw/047.htm">Herb Sutter on std::uncaught_exception</a> and why it's not as useful as you think</li> <li><a href="http://www.cpptalk.net/1-vt12438.html?postdays=0&amp;postorder=asc&amp;start=0">Historical discussion</a> on the matter with interesting participants (long!)</li> <li>Stroustrup explaining <a href="http://www.research.att.com/~bs/bs_faq2.html#finally">RAII</a></li> <li>Andrei Alexandrescu's <a href="http://www.ddj.com/cpp/184403758">Scope Guard</a></li> </ul>
<p>You <b>MUST NOT</b> throw an exception out of a destructor.<br> If an exception is already propagating then the application will terminate.<br></p> <p>By terminate I mean stop immediately. Stack unwinding stops. No more destructors are called. All bad stuff. See the discussion here.</p> <p><a href="http://stackoverflow.com/questions/130117/throwing-exceptions-out-of-a-destructor#130123">http://stackoverflow.com/questions/130117/throwing-exceptions-out-of-a-destructor#130123</a></p> <p>I don't follow (as in disagree with) your logic that this causes the destructor to get more complicated.<br> With the correct usage of smart pointers this actually makes the destructor simpler as everything now becomes automatic. Each class tides up its own little piece of the puzzle. No brain surgery or rocket science here. Another Big win for RAII.</p> <p>As for the possibility of std::uncaught_exception() I point you at <a href="http://www.gotw.ca/gotw/047.htm">Herb Sutters article about why it does not work</a></p>
Do OCUnit and OCMock work on the iPhone SDK? <p>I simply could not make it work, and I am wondering if I am wasting my time, or if I am simply stupid!</p> <p>Sorry I don't have the exact error I have right now. But I just want to know if it work or not!</p>
<p>I don't know whether OCUnit works with iPhone, but there is an <a href="http://code.google.com/p/google-toolbox-for-mac/wiki/iPhoneUnitTesting">iPhoneUnitTesting</a> framework available from Google Code.</p>
What tasks do you use JavaScript for the most? <p>What types of JavaScript scripts do find most useful in your work? What tasks do you use JavaScript for the most? Are there scripts that you wished were out there but just haven't been able to find? I'm trying to create a library of MooTools plugins and so I'm always looking for inspiration and advice. I'm trying to concentrate on utility more than anything else, but any suggestions are okay. I'm really not looking for code examples but rather descriptions of the tasks that you most often perform or would like to perform with JavaScript.</p>
<p>I use JavaScript the most for:</p> <ul> <li>Form validation</li> <li>DOM manipulation</li> <li>AJAX</li> </ul>
Reset Expander to default collapse behavior <p>I'm using an expander inside a <a href="http://kentb.blogspot.com/2007/04/resizer-wpf-control.html" rel="nofollow">Resizer</a> (a ContentControl with a resize gripper), and it expands/collapses properly when the control initially comes up. Once I resize it, the Expander won't properly collapse, as documented below. I ran Snoop on my application, and I don't see any heights set on Expander or its constituents. </p> <p>How would I go about convincing Expander to collapse properly again? Or modifying Resizer to not make Expander sad would work as well.</p> <p>Expander documentation says:</p> <blockquote> <p>"For an Expander to work correctly, do not specify a Height on the Expander control when the ExpandDirection property is set to Down or Up. Similarly, do not specify a Width on the Expander control when the ExpandDirection property is set to Left or Right. When you set a size on the Expander control in the direction that the expanded content is displayed, the area that is defined by the size parameter is displayed with a border around it. This area displays even when the window is collapsed. To set the size of the expanded window, set size dimensions on the content of the Expander control or the ScrollViewer that encloses the content."</p> </blockquote>
<p>I resolved the problem by moving the Resizer inside the Expander, but I've run into the Expander issue elsewhere, so would still like an answer if someone has it.</p> <p>thanks</p>
Way to go from recursion to iteration <p>I've used recursion quite a lot on my many years of programming to solve simple problems, but I'm fully aware that sometimes you need iteration due to memory/speed problems.</p> <p>So, sometime in the very far past I went to try and find if there existed any "pattern" or text-book way of transforming a common recursion approach to iteration and found nothing. Or at least nothing that I can remember it would help.</p> <ul> <li>Are there general rules?</li> <li>Is there a "pattern"?</li> </ul>
<p>Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.</p> <pre><code>Stack&lt;Object&gt; stack; stack.push(first_object); while( !stack.isEmpty() ) { // Do something my_object = stack.pop(); // Push other objects on the stack. } </code></pre> <p>Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:</p> <pre><code>foo(first); foo(second); </code></pre> <p>has to be replaced by</p> <pre><code>stack.push(second); stack.push(first); </code></pre> <p>Edit: The article <a href="http://cs.saddleback.edu/rwatkins/CS2B/Lab%20Exercises/Stacks%20and%20Recursion%20Lab.pdf">Stacks and Recursion Elimination</a> (or <a href="https://web.archive.org/web/20120227170843/http://cs.saddleback.edu/rwatkins/CS2B/Lab%20Exercises/Stacks%20and%20Recursion%20Lab.pdf">Article Backup link</a>) goes into more details on this subject.</p>
What is the best client side browser library to upload multiple files over http? <p>What is the best client side http library to upload multiple files? If it can handle directories that's a huge bonus. I'm looking for something that is open source or free. I'm looking for something like FTP, but that works over http, through the browser. Uploading multiple files through a normal HTML 4.x form is a bit of a hassle when it comes to uploading more than 5-6 files.</p> <p>Feel free to share your personal experiences.</p>
<p><a href="http://www.uploadify.com/" rel="nofollow">Uploadify</a> is also another great multiple file uploader. It was built off of SWFUpload and they added new features to it. </p> <p>Some of the features that I have found most helpful are: </p> <blockquote> <p>The user can upload all the files at once using ctrl + clicking on all of the files</p> <p>As the files are being downloaded a queue is displayed which shows the files being downloaded including a completeion bar. </p> <p>As files are completed they are removed from the queue</p> <p>It also allows you to specify which file types the user is able to download (they can only see the ones you choose)</p> </blockquote>
What is the naming convention in Python for variable and function names? <p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
<p>See Python <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>.</p> <blockquote> <p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p> <p>mixedCase is allowed only in contexts where that's already the prevailing style</p> </blockquote> <p>Variables...</p> <blockquote> <p>Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.</p> </blockquote> <p>Personally, I deviate from this because I also prefer <code>mixedCase</code> over <code>lower_case</code> for my own projects.</p>
Determine if a program is running on a Remote Desktop <p>Is there a way my program can determine when it's running on a Remote Desktop (Terminal Services)?</p> <p>I'd like to enable an "inactivity timeout" on the program when it's running on a Remote Desktop session. Since users are notorious for leaving Remote Desktop sessions open, I want my program to terminate after a specified period of inactivity. But, I don't want the inactivity timeout enabled for non-RD users.</p>
<p>GetSystemMetrics(SM_REMOTESESSION) (as described in <a href="http://msdn.microsoft.com/en-us/library/aa380798.aspx">http://msdn.microsoft.com/en-us/library/aa380798.aspx</a>)</p>
Changing short date format in Ubuntu <p>How do I change the system-wide short date format in Ubuntu? For example, Thunderbird is showing dates in the DD/MM/YY format, and I would like to change it to MM/DD/YY or YYYY-MM-DD.</p> <p>The best information I can find so far is in this thread:</p> <p><a href="http://ubuntuforums.org/showthread.php?t=193916" rel="nofollow">http://ubuntuforums.org/showthread.php?t=193916</a></p> <p>Edit: I want to change the system-wide date format, so that all my applications use this new date format.</p>
<p>I've written a <a href="http://ccollins.wordpress.com/2009/01/06/how-to-change-date-formats-on-ubuntu/" rel="nofollow">mini Howto</a> on this. It's not as easy as I had expected, but shouldn't pose too many problems.</p>
What is the difference between Ruby and Python versions of"self"? <p>I've done some Python but have just now starting to use Ruby<br /> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br /> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br /> Python methods receive self as an explicit argument, whereas Ruby does not.<br /> Ruby sometimes has methods explicitly defined as part of self using dot notation.</p> <p><strong>Initial Googling reveals</strong><br /> <a href="http://rubylearning.com/satishtalim/ruby_self.html">http://rubylearning.com/satishtalim/ruby_self.html</a><br /> <a href="http://www.ibiblio.org/g2swap/byteofpython/read/self.html">http://www.ibiblio.org/g2swap/byteofpython/read/self.html</a> </p>
<p>Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly.</p> <p>Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). The language was built such that self is a reserved keyword that returns the current instance wherever you are.</p> <p>If you're inside an instance method of one of your class, self is a reference to said instance. </p> <p>If you're in the definition of the class itself (not in a method), self is the class itself:</p> <pre><code>class C puts "I am a #{self}" def instance_method puts 'instance_method' end def self.class_method puts 'class_method' end end </code></pre> <p>At class definition time, 'I am a C' will be printed.</p> <p>The straight 'def' defines an instance method, whereas the 'def self.xxx' defines a class method.</p> <pre><code>c=C.new c.instance_method #=&gt; instance_method C.class_method #=&gt; class_method </code></pre>
How to put breakpoint in every function of .cpp file? <p>Is there a macro that does it? Which DTE objects to use?</p>
<p>(This is not quite what you're asking for, but almost:)</p> <p>You can put a breakpoint on <strong>every member function of a class</strong> in Visual Studio by bringing up the <em>New Breakpoint</em> dialog and entering:</p> <pre><code>CMyClass::* </code></pre> <p>See <a href="http://blogs.msdn.com/b/habibh/archive/2009/09/10/class-breakpoint-how-to-set-a-breakpoint-on-a-c-class-in-the-visual-studio-debugger.aspx">http://blogs.msdn.com/b/habibh/archive/2009/09/10/class-breakpoint-how-to-set-a-breakpoint-on-a-c-class-in-the-visual-studio-debugger.aspx</a> for more details.</p>
Finding the time taken to send messages with WCF net.tcp <p>I’m writing a prototype WCF enabled distributed app, to try and find out any issues I’ll have upgrading my existing “sending xml over tcp to communicate” apps I’ve got. I’m using Callback Contracts to register clients with a server (Singleton in ServiceHost) and so far all the communications between client and server work. I can connect multiple clients to the server and send a broadcast from the server that is received by all clients. I can block a particular client and the other clients still receive the calls. This is good.</p> <p>To continue my learning and evaluation of performance I would like the client to record what time the server sends each message, as well as what time the client receives that same message. How should I best go about this?</p> <p>Is there something similar to SOAP extensions, where I can add to the outgoing from the server and incoming to the client? Or would I need to add a “timeSent” parameter to every method that the server calls on the client and record the time received on the client (yuck!)? Is there a better way to accomplish this?</p> <p>I am using net.tcp rather than wsDualHttpBinding (which also works but is less performant).</p>
<p>Hmmm... that's a difficult one. The problem here is you can't even make sure both the client and the server timers are in sync.</p> <p>If what you want to do is send some out-of-band data, so that you don't need to modify your methods, you can use the method suggested <a href="http://microsoft.apress.com/asptodayarchive/73677/using-aspnet-soap-headers-in-web-services-for-orthogonal-interception-services-part-1" rel="nofollow">here</a>. I think it should be enough.</p>
Flex: Modify an embedded icon and use it in a button? <p>Just that, if you embed an icon:</p> <pre><code>[Embed(source='icons/checkmark.png')] private static var CheckMark:Class; </code></pre> <p>You end up with a dynamic class. You can pretty easily assign the icon to a button at runtime by calling the setStyle method:</p> <pre><code>var btn:Button = new Button(); btn.setStyle("icon", CheckMark); </code></pre> <p>But what if you wanted to alter the icon at runtime, like changing it's alpha value or even redrawing pixels, before assigning it to the button?</p> <p>So far I can't find a satisfactory answer...</p>
<p>This is the only answer I could find that seemed close: <a href="http://blog.xsive.co.nz/archives/234" rel="nofollow">Dynamic Icons</a> <a href="http://blog.xsive.co.nz/flex_source/button_icon_drawing/ButtonTest.html" rel="nofollow">(example with View Source)</a></p> <p>His solution involves a custom "DynamicIcon" class which is used in the button's icon setting, and a custom Button class which adds one method to the Button class to draw dynamic icons.</p> <p>The end result is that you are able to send BitmapData to the DynamicIcon class, which will show up in the button. So, embed your image, instantiate your asset class, get the bitmapasset and modify it however you need to and send the bitmapData to the icon.</p> <p>It's an interesting problem and it seems like there should be an easier solution, but this works without a lot of hassle.</p>
should I free pointer returned by getpwuid() in Linux? <p>After I call getpwuid(uid), I have a reference to a pointer. Should I free that when I don't use it anymore? Reading the man pages, it says that it makes reference to some static area, that may be overwritten by subsequent calls to the same functions, so I'm sure sure if I should touch that memory area.</p> <p>Thanks.</p>
<p>No. You do not need to free the result. You can only call free(3) on pointers allocated on the heap with malloc(3), calloc(3) or realloc(3).</p> <p>Static data is part of a program's data or bss segments and will persist until the process exits (or is overwritten by exec(2)).</p>
What svn command would list all the files modified on a branch? <p>In svn, I have a branch which was created, say at revision 22334. Commits were then made on the branch.</p> <p>How do I get a list of all files that were changed on the branch compared to what's on the trunk? I do not want to see files that were changed on the trunk between when the branch was created and "now".</p>
<p>This will do it I think:</p> <pre><code>svn diff -r 22334:HEAD --summarize &lt;url of the branch&gt; </code></pre>
ZIP Code (US Postal Code) validation <p>I thought people would be working on little code projects together, but I don't see them, so here's an easy one:</p> <p>Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so you might want to use weak validation.</p> <p>I wrote a little bit about zip codes in a side project on my wiki/blog:</p> <p>https://benc.fogbugz.com/default.asp?W24</p> <p>There is also a new, weird type of zip code. </p> <p>https://benc.fogbugz.com/default.asp?W42</p> <p>I can do the javascript code, but it would be interesting to see how many languages we can get here.</p>
<p><strong>Javascript Regex Literal</strong>:</p> <p>US Zip Codes: <code>/(^\d{5}$)|(^\d{5}-\d{4}$)/</code></p> <pre><code>var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210"); </code></pre> <p>Some countries use <a href="http://en.wikipedia.org/wiki/Postal_code">Postal Codes</a>, which would fail this pattern.</p>
Run custom Javascript whenever a client-side ASP.NET validator is triggered? <p>Is there a way to run some custom Javascript whenever a client-side ASP.NET validator (RequiredFieldValidator, RangeValidator, etc) is triggered? </p> <p>Basically, I have a complicated layout that requires I run a custom script whenever a DOM element is shown or hidden. I'm looking for a way to automatically run this script when a validator is displayed. (I'm using validators with Display="dynamic")</p>
<p>See <a href="http://stackoverflow.com/questions/124682/can-you-have-custom-client-side-javascript-validation-for-standard-aspnet-web-f#125158">this comment</a> for how I managed to extend the ASP.Net client side validation. <a href="http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=362" rel="nofollow">Others</a> have managed to extend it using server side techniques.</p>
Run Sparc binaries without Sparc hardware <p>I've been curious in the past few months in trying my hand at doing some assembly for the SPARC processor (either V8 or V9). My question is this, I have no access to a SPARC machine, is there a way I can run SPARC binaries on my x86 machine? I've looked at QEMU but I am not too sure how to set it up.</p>
<p><A HREF="https://www.simics.net/" rel="nofollow">SimICS</A> emulates a Sparc platform. Academic and personal licenses are free.</p> <p><B>Edit:</B> I didn't do SimICS justice in my initial response, it is a very useful tool for Sparc-based development. You can instrument, profile, and explore the behavior or code in both user space and kernel space. I first became aware of it about 10 years ago, when it was released by the Swedish Institute of Computer Science (SICS). They later spun it out as a commercial product.</p>
Generating random numbers in Objective-C <p>I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:</p> <pre><code>Random.nextInt(74) </code></pre> <p>I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.</p>
<p>You should use the arc4random_uniform() function. It uses a superior algorithm to rand. You don't even need to set a seed.</p> <pre><code>#include &lt;stdlib.h&gt; // ... // ... int r = arc4random_uniform(74); </code></pre> <p>The arc4random man page:</p> <blockquote> <pre><code>NAME arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include &lt;stdlib.h&gt; u_int32_t arc4random(void); void arc4random_stir(void); void arc4random_addrandom(unsigned char *dat, int datlen); DESCRIPTION The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and random(3). The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via arc4random_addrandom(). There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically initializes itself. EXAMPLES The following produces a drop-in replacement for the traditional rand() and random() functions using arc4random(): #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1)) </code></pre> </blockquote>
How do I check if an integer is even or odd? <p>How can I check if a given number is even or odd in C?</p>
<p>Use the modulo (%) operator to check if there's a remainder when dividing by 2:</p> <pre><code>if (x % 2) { /* x is odd */ } </code></pre> <p>A few people have criticized my answer above stating that using x &amp; 1 is "faster" or "more efficient". I do not believe this to be the case. </p> <p>Out of curiosity, I created two trivial test case programs:</p> <pre><code>/* modulo.c */ #include &lt;stdio.h&gt; int main(void) { int x; for (x = 0; x &lt; 10; x++) if (x % 2) printf("%d is odd\n", x); return 0; } /* and.c */ #include &lt;stdio.h&gt; int main(void) { int x; for (x = 0; x &lt; 10; x++) if (x &amp; 1) printf("%d is odd\n", x); return 0; } </code></pre> <p>I then compiled these with gcc 4.1.3 on one of my machines 5 different times:</p> <ul> <li>With no optimization flags.</li> <li>With -O</li> <li>With -Os</li> <li>With -O2</li> <li>With -O3</li> </ul> <p>I examined the assembly output of each compile (using gcc -S) and found that in each case, the output for and.c and modulo.c were identical (they both used the andl $1, %eax instruction). I doubt this is a "new" feature, and I suspect it dates back to ancient versions. I also doubt any modern (made in the past 20 years) non-arcane compiler, commercial or open source, lacks such optimization. I would test on other compilers, but I don't have any available at the moment.</p> <p>If anyone else would care to test other compilers and/or platform targets, and gets a different result, I'd be very interested to know.</p> <p>Finally, the modulo version is <strong>guaranteed</strong> by the standard to work whether the integer is positive, negative or zero, regardless of the implementation's representation of signed integers. The bitwise-and version is not. Yes, I realise two's complement is somewhat ubiquitous, so this is not really an issue.</p>
Error: initializer element is not computable at load time <p>I have in a function that takes a struct, and I'm trying to store its variables in an array, but I get this when I run gcc -Wall -ansi -pedantic-errors -Werror</p> <pre><code>int detect_prm(Param prm) { int prm_arr[] = {prm.field1, prm.field2, prm.field3}; return 0; } </code></pre> <p>I get Error: initializer element is not computable at load time when I try to compile the above. It looks fine to me, whats wrong?</p>
<p>Mike's answer is absolutely right.</p> <p>However, if you're able to use the GNU C extensions, or to use the newer and better C99 standard instead (use the <code>--std=c99</code> option), then initializers such as this are perfectly legal. The C99 standard has been out for, well, 9 years, and most C compilers support it quite well... especially this feature.</p>
How do I invoke a Java method when given the method name as a string? <p>If I have two variables:</p> <pre><code>Object obj; String methodName = "getName"; </code></pre> <p>Without knowing the class of <code>obj</code>, how can I call the method identified by <code>methodName</code> on it?</p> <p>The method being called has no parameters, and a <code>String</code> return value. It's <em>a getter for a Java bean</em>.</p>
<p>Coding from the hip, it would be something like:</p> <pre><code>java.lang.reflect.Method method; try { method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..); } catch (SecurityException e) { ... } catch (NoSuchMethodException e) { ... } </code></pre> <p>The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give <code>methodName</code>).</p> <p>Then you invoke that method by calling</p> <pre><code>try { method.invoke(obj, arg1, arg2,...); } catch (IllegalArgumentException e) { ... } catch (IllegalAccessException e) { ... } catch (InvocationTargetException e) { ... } </code></pre> <p>Again, leave out the arguments in <code>.invoke</code>, if you don't have any. But yeah. Read about <a href="http://java.sun.com/docs/books/tutorial/reflect/index.html">Java Reflection</a></p>
In .NET is there a way to enable Assembly.Load tracing? <p>In .NET is there a way to enable Assembly.Load tracing? I know while running under the debugger it gives you a nice message like "Loaded 'assembly X'" but I want to get a log of the assembly loads of my running application outside the debugger, preferably intermingled with my Debug/Trace log messages. </p> <p>I'm tracing out various things in my application and I basically want to know what action triggered a particular assembly to be loaded.</p>
<p>Get the AppDomain for your application and attach to the AssemblyLoad event.</p> <p>Example (C#): </p> <pre><code>AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(OnAssemblyLoad); </code></pre>
How do I force a tomcat web application reload the trust store after I update it <p>I have the following problem. My tomcat 5.5 based web application is using a trust store to verify SSL connections. The application allows the user to add or remove CA certificates to be used in the verification process. However, adding or removing certificates from the trust store doesn't change a thing. The application 'recognizes' only the certificates that were in the trust store when tomcat started. For it to recognize the new set of certificates, I need to restart tomcat.</p> <p>This is not a valid solution, however. What I do need is a code based solution. Please advice.</p>
<p>how about writing a Custom Classloader that loads in the trust store ONLY for this webapp. You could unload the classloader when you need to refresh the contents and reload it ?</p>
How do I determine the file and line # of a C# method from a symbols (.pdb) file? <p>pdb files contain symbol information for .NET assemblies. I'd like to read a pdb file in order to correlate methods with their file location. The data is contained within it but I can't seem to find a good description of how to get it out.</p> <p>I know about <a href="http://blogs.msdn.com/jmstall/archive/2005/08/25/pdb2xml.aspx" rel="nofollow">mdbg</a>, but that is very heavy (I think/hope) for what I want.</p>
<p>You should look:</p> <ul> <li><a href="http://www.mono-project.com/Cecil" rel="nofollow">Mono.Cecil</a> and especially the Mono.Cecil.Pdb module. It should do what you want and more.</li> </ul>
FTP File Upload with HTTP Proxy <p>Is there a way to upload a file to a FTP server when behind an HTTP proxy ?</p> <p>It seems that uploading a file is not supported behind an HTTP Proxy using .Net Webclient. (<a href="http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.proxy.aspx">http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.proxy.aspx</a>).</p> <p>If there is no workaround ? If not, do you know a good and free FTP library I can use ?</p> <p><strong>Edit</strong>: Unfortunately, I don't have any FTP proxy to connect to.</p>
<p>In active FTP mode, the server initiates a data connection to the client. If the client is behind an HTTP proxy, this obviously won't work. In passive FTP mode it is the client who initiates both the initial and the data connections. Since HTTP proxies can tunnel arbitrary outgoing TCP connections (using the CONNECT method), it should be possible to access an FTP server in passive mode via an HTTP proxy.</p> <p>The <code>FtpWebRequest</code> seems to support passive mode. However, I don't understand why file download and directory listings are supported, whereas file upload, which also uses the same data connection, is not.</p> <p>Have you confirmed that <code>FtpWebRequest</code> configured for passive mode does not work via an HTTP proxy through which directory listings/file download work just fine?</p>
Access to remote computer's MSMQ gives "Remote computer is not available" <p>We have a windows application that runs on a server and accesses 4 other servers (all of them are members in the domain) to get the messages in each of their private queues. We've just installed a new server, and for some reason when the application tries to access that computer, it gets a "Remote computer is not available" message.<br /> The application accesses the other servers with a user who is an admin domain user.<br /> Has anyone encountered such a problem, or have a clue as to what could be causing it?</p>
<p>Probably way too late for this thread, but I found the answer to this here: <a href="http://blogs.msdn.com/johnbreakwell/archive/2008/07/10/getting-msmq-messages-out-of-windows-server-2008.aspx" rel="nofollow">http://blogs.msdn.com/johnbreakwell/archive/2008/07/10/getting-msmq-messages-out-of-windows-server-2008.aspx</a></p>
Unit Testing: Maven or Eclipse? <p>I am not really familiar with Maven program but I've been using Eclipse for quite a while for Unit testing, code coverage, javadoc generation, code style checking, etc. Probably, the only main thing that I didn't really like about Eclipse is the "compilation errors" that it generates when you are running Eclipse and Ant simultaneously. So I am wondering if Maven 2 does the same thing if you are running Ant task.</p> <p>Lee23 </p>
<p>The company I currently work for has a lot of JUnit tests which are run using Maven (1.x). We've never really had any problem and any tests that fail in maven can be debugged using the remote debugger or in Eclipse on their own.</p> <p>The most important thing is that you take the time and effort to set up the environment properly so that when your tests run they are using the correct directories, variables, etc. This way you shouldn't get the 'compilation errors' that you would get when running Eclipse and Ant.</p> <p>Maven has the ability to run all your tests for you during the testing cycle of compilation, this should stop the need for any Ant tasks to run the tests. However, if you still need to have scripts for other tasks (generation of code, etc) then be weary of Maven's ability to generate code and not include it in the compiled binaries (jar, war), though this may well be fixed for newer versions of Maven.</p> <p>At the end of the day it would be best to evaluate Maven 2 and see if it's right for you. It sounds like you're having (sarcasm)a lot of fun (/sarcasm) with Ant and Eclipse already though. :)</p>
Referenced structure not 'sticking' <p>I am currently porting a lot of code from an MFC-based application to a DLL for client branding purposes.</p> <p>I've come across an unusual problem. This bit of code is the same in both systems:</p> <pre><code>// ... CCommsProperties props; pController-&gt;GetProperties( props ); if (props.handshake != HANDSHAKE_RTS_CTS) { props.handshake = HANDSHAKE_RTS_CTS; pController-&gt;RefreshCommProperties( props ); } // ... in another file: void CControllerSI::RefreshCommProperties ( const CCommsProperties&amp; props ) { // ... code ... } </code></pre> <p>CommProperties is a wrapper for the comm settings, serialization of etc. and pController is of type ControllerSI which itself is a layer between the actual Comms and the Application.</p> <p>On the original MFC version the setting of handshake to RTS-CTS sticks but when running as the DLL version it resets itself to 0 as soon as the function is entered. The code is contained entirely in the DLL section of the code, so there are no boundaries.</p> <p>The main differences between the original and the new modules is the variables that call the various dialogs have been removed and the removed #includes</p> <p>I've lost an afternoon to this and I don't really want to lose any more...</p>
<p>It is difficult to see what is wrong from the given code alone. Some general pointers:</p> <ol> <li><p>The object is initialized and processed in different binary modules with incompatible linking (such as C-run times)</p></li> <li><p>If the class/structure is shared it is not exported/imported correctly.</p></li> <li><p>The class(s) are defined in more than one place, and you are not including the correct definitions.</p></li> </ol> <p>The above three are the most likely causes, especially, if all fields are reset to their default initialized values.</p> <p>if this is only happening with only one or two fields, the structure may be poorly aligned and you may need to rearrange the fields to correct these (check that in release too).</p> <p>In general, I am tempted to hypothesize that the object you have intialized is not the one <code>RefreshCommProperties()</code> sees, for some reason, may be one of the three above.</p>
'pass parameter by reference' in Ruby? <p>In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)? I'm looking for something similar to C#'s '<strong>ref</strong>' keyword.</p> <p>Example:</p> <pre><code>def func(x) x += 1 end a = 5 func(a) #this should be something like func(ref a) puts a #should read '6' </code></pre> <p>Btw. I know I could just use:</p> <pre><code>a = func(a) </code></pre>
<p>You can accomplish this by explicitly passing in the current binding:</p> <pre><code>def func(x, bdg) eval "#{x} += 1", bdg end a = 5 func(:a, binding) puts a # =&gt; 6 </code></pre>
Where is GDB documentation specific to the Cell Linux environment? <p>Where can documentation be found for the features of GDB, and the debugging process, specific to debugging of Cell Linux programs mixing PPU and SPU code?</p>
<p>Documents at the IBM developerWorks site for Cell can be found here: <a href="http://www.ibm.com/developerworks/power/cell/documents.html?S_TACT=105AGX16&amp;S_CMP=LP" rel="nofollow">Cell @developerWorks</a></p> <p>You sound like you'd want the <a href="http://www.ibm.com/chips/techlib/techlib.nsf/techdocs/1DAAA0A3B6404763002573530066008C?Open&amp;S_TACT=105AGX16&amp;S_CMP=LP" rel="nofollow">Programmer's Guide</a>, which goes through debugging Cell applications.</p> <p>Edit to add sample topics:</p> <ul> <li>Chapter 3. Debugging Cell BE applications <ul> <li>...</li> <li>Debugging PPE code </li> <li>Debugging SPE code </li> <li>...</li> <li>Debugging in the Cell BE environment</li> <li>Debugging multithreaded code </li> <li>Debugging architecture</li> <li>Switching architectures within a single thread </li> <li>...</li> <li>Using the combined debugger</li> <li>...</li> </ul></li> </ul>
How do I launch a standalone SWF from within an Adobe AIR application? <p>I'm completely new to AIR but what I'm trying to do feels like it should be quite easy.</p> <p>I want my AIR app to execute (launch) an SWF in the standalone Flash Player (just like if I were to double click it). </p> <p>Please note that I don't want the AIR app to embed the SWF. Just run it.</p> <p>Can this be done?</p>
<p>Using Adobe AIR, you could launch / load the SWF into a separate native window. It would run in the same process as the AIR app loading / launching it, but the experience would be the similar if not the same for the end user.</p> <p>mike chambers</p> <p>mesh@adobe.com</p>
initialize a const array in a class initializer in C++ <p>I have the following class in C++:</p> <pre><code>class a { const int b[2]; // other stuff follows // and here's the constructor a(void); } </code></pre> <p>The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is <code>const</code>?</p> <p>This doesn't work:</p> <pre><code>a::a(void) : b([2,3]) { // other initialization stuff } </code></pre> <p>Edit: The case in point is when I can have different values for <code>b</code> for different instances, but the values are known to be constant for the lifetime of the instance.</p>
<p>With C++11 the answer to this question has now changed and you can in fact do:</p> <pre><code>struct a { const int b[2]; // other bits follow // and here's the constructor a(); }; a::a() : b{2,3} { // other constructor work } int main() { a a; } </code></pre>
How do you track the time of replicated rows for Subscribers in SQL Server 2005? <p>The basic problem is like this:<br /> A subscriber has successfully replicated a row from the publisher, using transactional replication. Now, how do we keep track the time of this row being last successfully replicated? </p> <p>A friend has suggested the following solution, which he used for his SQL Server 2000:<br /> 1) Add a datetime column.<br /> 2) Change the replication stored procedure to update the datetime column (!).</p> <p>The step #2 sets off all sorts of warning bells within me, so I'm asking if there are better solutions for SQL Server 2005 in this situation, before I even go into detail with his solution. </p>
<p>I had this exact problem a few weeks ago trying to find records that have changed recently.</p> <p>Create a new column and set the data type to TIMESTAMP. SS2005 automatically updates this type when the row is updated. The only problem is that this 'timestamp' has nothing at all to do with a date or time, it is just a number that reflects the last successful update of that row (any update, not just via replication). If that is all you need, then you should be fine. </p> <p>If you need the last <em>replication</em> update, things might get a bit tricky, and you need get your hands dirty with triggers and stored procs.</p> <p><a href="http://www.sqlteam.com/article/timestamps-vs-datetime-data-types" rel="nofollow">http://www.sqlteam.com/article/timestamps-vs-datetime-data-types</a></p> <p>Hope that helps~ </p>
If I stop a long running query, does it rollback? <p>A query that is used to loop through <b>17 millions records to remove duplicates</b> has been running now for about <b>16 hours</b> and I wanted to know if the query is stopped right now if it will finalize the delete statements or if it has been deleting while running this query? Indeed, if I do stop it, does it finalize the deletes or rolls back?</p> <p>I have found that when I do a </p> <pre><code> select count(*) from myTable </code></pre> <p>That the rows that it returns (while doing this query) is about 5 less than what the starting row count was. Obviously the server resources are extremely poor, so does that mean that this process has taken 16 hours to find 5 duplicates (when there are actually thousands), and this could be running for days?</p> <p>This query took 6 seconds on 2000 rows of test data, and it works great on that set of data, so I figured it would take 15 hours for the complete set.</p> <p>Any ideas?</p> <p>Below is the query:</p> <pre><code>--Declare the looping variable DECLARE @LoopVar char(10) DECLARE --Set private variables that will be used throughout @long DECIMAL, @lat DECIMAL, @phoneNumber char(10), @businessname varchar(64), @winner char(10) SET @LoopVar = (SELECT MIN(RecordID) FROM MyTable) WHILE @LoopVar is not null BEGIN --initialize the private variables (essentially this is a .ctor) SELECT @long = null, @lat = null, @businessname = null, @phoneNumber = null, @winner = null -- load data from the row declared when setting @LoopVar SELECT @long = longitude, @lat = latitude, @businessname = BusinessName, @phoneNumber = Phone FROM MyTable WHERE RecordID = @LoopVar --find the winning row with that data. The winning row means SELECT top 1 @Winner = RecordID FROM MyTable WHERE @long = longitude AND @lat = latitude AND @businessname = BusinessName AND @phoneNumber = Phone ORDER BY CASE WHEN webAddress is not null THEN 1 ELSE 2 END, CASE WHEN caption1 is not null THEN 1 ELSE 2 END, CASE WHEN caption2 is not null THEN 1 ELSE 2 END, RecordID --delete any losers. DELETE FROM MyTable WHERE @long = longitude AND @lat = latitude AND @businessname = BusinessName AND @phoneNumber = Phone AND @winner != RecordID -- prep the next loop value to go ahead and perform the next duplicate query. SET @LoopVar = (SELECT MIN(RecordID) FROM MyTable WHERE @LoopVar &lt; RecordID) END </code></pre>
<p>no, sql server will not roll back the deletes it has already performed if you stop query execution. oracle requires an explicit committal of action queries or the data gets rolled back, but not mssql.</p> <p>with sql server it will not roll back unless you are specifically running in the context of a transaction and you rollback that transaction, or the connection closes without the transaction having been committed. but i don't see a transaction context in your above query.</p> <p>you could also try re-structuring your query to make the deletes a little more efficient, but essentially if the specs of your box are not up to snuff then you might be stuck waiting it out.</p> <p>going forward, you should create a unique index on the table to keep yourself from having to go through this again. </p>
Fire Async method on page load with AJAX <p>I am using ASP.NET 2.0 with AJAX Extensions (1.0?) and am wondering if it is possible to call a method asynchronously and have the results populate on the page after it has been loaded.</p> <p>I have a gridview that is populated by a fairly long-running SQL query. I would prefer to have the page come up and the results trickle back in as they are returned from the server instead of forcing the user to stare at a blank page until everything is processed.</p>
<p>You can use an asp:UpdatePanel and insert the gridview in there. They just call the AJAX call during load. You use the Sys.Application.load event. Check it out here for more information: <a href="http://www.asp.net/ajax/documentation/live/overview/AJAXClientEvents.aspx" rel="nofollow">http://www.asp.net/ajax/documentation/live/overview/AJAXClientEvents.aspx</a></p>
What is the role of Spring in Struts + Spring + Hibernate? <p>What role is Spring taking in Struts + Spring + Hibernate?</p>
<p>Spring provides many different "modules" and different programmers will use different parts of Spring.</p> <p>However, commonly in this sort of stack, you will see Spring being used as a provider of</p> <ul> <li>An inversion of control container for dependency injection</li> <li>An abstraction to Hibernate called "HibernateTemplate"</li> <li>Framework classes for simplifying Aspect Oriented Programming</li> <li>Transaction support, often "declaratively" via the IoC container and AOP.</li> </ul>
const int vs. int const as function parameter in C++ and C <p>Quick question: </p> <pre><code>int testfunc1 (const int a) { return a; } int testfunc2 (int const a) { return a; } </code></pre> <p>Are these two functions the same in every aspect or is there a difference? I'm interested in an answer for the C-language, but if there is something interested in the C++ case I'd like to know as well. </p>
<p>The trick is to read the declaration backwards (right-to-left):</p> <pre><code>const int a = 1; // read as "a is an integer which is constant" int const a = 1; // read as "a is a constant integer" </code></pre> <p>Both are the same thing. Therefore:</p> <pre><code>a = 2; // Can't do because a is constant </code></pre> <p>The reading backwards trick especially comes in handy when you're dealing with more complex declarations such as:</p> <pre><code>const char *s; // read as "s is a pointer to a char that is constant" char c; char *const t = &amp;c; // read as "t is a constant pointer to a char" *s = 'A'; // Can't do because the char is constant s++; // Can do because the pointer isn't constant *t = 'A'; // Can do because the char isn't constant t++; // Can't do because the pointer is constant </code></pre>
Is there a way to script diagrams in SQL 2000 (or save them another way)? <p>It's possible to create digrams in SQL Server 2000 that can be useful to show the relationships between tables. The problem we run into is that when somebody refreshes our development database, the diagrams get lost. We can load tables, stored procedures, views, etc. with SQL scripts, but we have to create the diagrams by hand.</p> <p>Is there a way to script out the diagrams? Or can they be saved outside of the database some other way?</p>
<p>It can be done for SQL Server 2005 - see <a href="http://www.codeproject.com/KB/database/ScriptDiagram2005.aspx" rel="nofollow">here</a>.</p> <p>And info. on SQL Server 2000 - <a href="http://bytes.com/forum/thread81534.html" rel="nofollow">here</a>.</p>
How do I detect "Easter Egg" mode in my Palm OS application? <p>Since the early days, Palm OS has had a special "easter egg" mode that's enabled by making the right gesture in one of the Preference panels. On current Palm Treo and Centro devices, this is turned on by doing a clockwise swirl above the "Tips" button in the Power panel.</p> <p>Some applications, like the Blazer web browser, enable special features when easter eggs are active. How can I detect this in my own program?</p>
<p>The standard system preference for this is prefAllowEasterEggs (see Preference.h). This setting can be accessed using the PrefGetPreference API:</p> <pre><code>UInt32 enableEasterEggs = PrefGetPreference(prefAllowEasterEggs); </code></pre> <p>The value will be non-zero when the user has requested that Easter eggs be available.</p>
The value of hobby game development <p>Does attempting to develop some sort of game, even just as a hobby during leisure time provide useful (professional) experience or is it a childish waste of time?</p> <p>I have pursued small personal game projects on and off throughout my programming career. I've found the (often) strict performance requirements and escalating design complexity have taught me some of my most useful programming lessons. </p> <p>In these projects to name just a few, I very quickly came face to face with: "Everything is fast for small N". I also discovered the hard way about using basic object oriented design principles to manage complexity.</p> <p>In a field where many technologies and topics can be quite dry/dull, I think hobby game development is important in motivating new (and not so new) developers to brush up on essential skills while having fun at the same time. </p> <p><a href="http://stackoverflow.com/questions/157319/do-you-have-a-hobby-development-project">This question</a> talks about hobby projects in general, however here I am more interested in game projects specially and how valuable they are to professional programmers.</p>
<p>You can learn a lot from game development. Game development requires a discipline that you can't find in other programming projects.</p> <p>Here are just a small set of things game development has taught me:</p> <ul> <li>Optimization for speed</li> <li>Sacrificing computational depth for speed</li> <li>Developing under small constraints of memory</li> <li>Building a system that works like an operating system but is geared toward speed.</li> <li>Keeping hundreds to thousands of objects in a tree, each with their own unique characteristics</li> <li>Some areas of game development have great academic value (like Artificial Intelligence, Procedural Algorithms, etc)</li> <li>It doesn't matter how much of a hack the code is, as long as the gameplay is there. Translating this to other disciplines, the objective of programming is to make the customers happy, regardless of how clever or ugly your code is.</li> </ul> <p>Because game programmers are forced to use less resources, they become better programmers.</p>
Rendered pIxel width data for each character in a browser's font <p>I have a table column that needs to be limited to a certain width - say 100 pixels. At times the text in that column is wider than this and contains no spaces. For example:</p> <pre><code>a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_table_unhappy </code></pre> <p>I would like to calculate the width of text server-side and add an ellipsis after the correct number of characters. The problem is that I don't have data about the rendered size of the text.</p> <p>For example, assuming the browser was Firefox 3 and the font was 12px Arial. What would be the width of the letter "a", the width of the letter "b", etc.?</p> <p>Do you have data showing the pixel width of each character? Or a program to generate it?</p> <p>I think a clever one-time javascript script could do the trick. But I don't want to spend time re-inventing the wheel if someone else has already done this. I am surely not the first person to come up against this problem.</p>
<p>How about overflow: scroll?</p>
How do you log the machine name via log4net? <p>I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database.</p> <p>I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated.</p> <p>But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender.</p> <p>Is there a way to log the machine name via log4net in this manner?</p>
<p>You can use the pre-populated property <code>log4net:HostName</code>, for example:</p> <pre><code>&lt;conversionPattern value="%property{log4net:HostName}" /&gt; </code></pre> <p>This way you don't need to populate the MDC.</p>
Would it be possible to use web services from a Cobol program? <p>We have some COBOL programs in our financial applications which need to interact with some of our backend systems. One of the available interfaces is through a web service. Can a program written in Cobol make requests to a web service?</p>
<p><a href="http://www.microfocus.com/" rel="nofollow">Microfocus</a> provide a tool called Enterprise Server which allows COBOL to interact with web services.</p> <p>If you have a COBOL program A and another COBOL program B and A calls B via the interface section, the tool allows you to expose B's interface section as a web service.</p> <p>For program A, you then generate a client proxy and A can now call B via a web service.</p> <p>Of course, because B now has a web service any other type of program (command line, Windows application, Java, ASP etc.) can now also call it.</p>
Is there a source-control system that allows tracking of file name changes? <p>So, I've been living with my cvs repositories for some time. Though there is a thing I miss - if i rename a file that is already in repository, I need to delete the one with old name from there and add the new one. Hence, I loose all my change-history. And sometimes there's a need to rename a file in alredy existing project.</p> <p>From what I saw, cvs/svn can't handle something like this, or am I wrong? If not, what other source control system would you recommend, that allows the renaming of files? </p>
<p>Subversion can do this, but you have to do it with </p> <pre><code>svn move &lt;oldfile&gt; &lt;newfile&gt; </code></pre> <p>Edit: And in this decade, we do <code>git mv &lt;oldfile&gt; &lt;newfile&gt;</code>, or just use <code>mv</code> and git usually figures it out on its own.</p>