input
stringlengths
51
42.3k
output
stringlengths
18
55k
What's the best HTML WYSISYG editor available to web developers and why? <p>There are many different flavored HTML WYSIWYG editors from javascript to ASP.Net web controls, but all too often the features are the same. Does anyone have a favorite HTML editor they like to use in projects? Why?</p>
<p>I'm partial to TinyMCE WYSIWYG editor due to the following reasons:</p> <ol> <li><p>Javascript - so it is broadly usable regardless of the platform I'm working in.</p></li> <li><p>Easy to use - just a couple lines of code and a textarea and the control is up and running.</p></li> <li><p>Easily themed - so I can quickly make it look like the site in which it is being used</p></li> <li><p>Most importantly - easily customized to show/hide particular buttons depending on my application needs</p></li> </ol>
Unit Testing C Code <p>I worked on an embedded system this summer written in straight C. It was an existing project that the company I work for had taken over. I have become quite accustomed to writing unit tests in Java using JUnit but was at a loss as to the best way to write unit tests for existing code (which needed refactoring) as well as new code added to the system.</p> <p>Are there any projects out there that make unit testing plain C code as easy as unit testing Java code with JUnit? Any insight that would apply specifically to embedded development (cross-compiling to arm-linux platform) would be greatly appreciated.</p>
<p>One unit testing framework in C is <a href="http://check.sourceforge.net/">Check</a>; a (<strong>LAST UPDATED ON 2008</strong>) list of unit testing frameworks in C can be found <a href="http://check.sourceforge.net/doc/check_html/check_2.html#SEC3">here</a> and is reproduced below. Depending on how many standard library functions your runtime has, you may or not be able to use one of those.</p> <blockquote> <h3>AceUnit</h3> <p>AceUnit (Advanced C and Embedded Unit) bills itself as a comfortable C code unit test framework. It tries to mimick JUnit 4.x and includes reflection-like capabilities. AceUnit can be used in resource constraint environments, e.g. embedded software development, and importantly it runs fine in environments where you cannot include a single standard header file and cannot invoke a single standard C function from the ANSI / ISO C libraries. It also has a Windows port. It does not use forks to trap signals, although the authors have expressed interest in adding such a feature. See the <a href="http://aceunit.sourceforge.net/">AceUnit homepage</a>.</p> <h3>GNU Autounit</h3> <p>Much along the same lines as Check, including forking to run unit tests in a separate address space (in fact, the original author of Check borrowed the idea from GNU Autounit). GNU Autounit uses GLib extensively, which means that linking and such need special options, but this may not be a big problem to you, especially if you are already using GTK or GLib. See the <a href="http://autounit.tigris.org/">GNU Autounit homepage</a>.</p> <h3>cUnit</h3> <p>Also uses GLib, but does not fork to protect the address space of unit tests.</p> <h3>CUnit</h3> <p>Standard C, with plans for a Win32 GUI implementation. Does not currently fork or otherwise protect the address space of unit tests. In early development. See the <a href="http://cunit.sourceforge.net/">CUnit homepage</a>.</p> <h3>CuTest</h3> <p>A simple framework with just one .c and one .h file that you drop into your source tree. See the <a href="http://cutest.sourceforge.net/">CuTest homepage</a>.</p> <h3>CppUnit</h3> <p>The premier unit testing framework for C++; you can also use it to test C code. It is stable, actively developed, and has a GUI interface. The primary reasons not to use CppUnit for C are first that it is quite big, and second you have to write your tests in C++, which means you need a C++ compiler. If these don’t sound like concerns, it is definitely worth considering, along with other C++ unit testing frameworks. See the <a href="http://sourceforge.net/apps/mediawiki/cppunit/index.php?title=Main_Page">CppUnit homepage</a>.</p> <h3>embUnit</h3> <p>embUnit (Embedded Unit) is another unit test framework for embedded systems. This one appears to be superseded by AceUnit. <a href="http://sourceforge.net/projects/embunit/">Embedded Unit homepage</a>.</p> <h3>MinUnit</h3> <p>A minimal set of macros and that’s it! The point is to show how easy it is to unit test your code. See the <a href="http://www.jera.com/techinfo/jtns/jtn002.html">MinUnit homepage</a>.</p> <h3>CUnit for Mr. Ando</h3> <p>A CUnit implementation that is fairly new, and apparently still in early development. See the <a href="http://park.ruru.ne.jp/ando/work/CUnitForAndo/html/">CUnit for Mr. Ando homepage</a>.</p> <p>This list was last updated in March 2008.</p> </blockquote> <p>Others:</p> <h3>CMocka</h3> <p>CMocka is a test framework for C with support for mock objects. It's easy to use and setup. <a href="https://cmocka.org/">CMocka</a> official homepage.</p> <h3>Criterion</h3> <p>Criterion is a cross-platform C unit testing framework supporting automatic test registration, parameterized tests, theories, and that can output to multiple formats, including TAP and JUnit XML. Each test is run in its own process, so signals and crashes can be reported or tested if needed. See the <a href="https://github.com/Snaipe/Criterion">Criterion homepage</a> for more information.</p> <h3>HWUT</h3> <p>HWUT is a general Unit Test tool with great support for C. It can help to create Makefiles, generate massive test cases coded in minimal 'iteration tables', walk along state machines, generate C-stubs and more. The general approach is pretty unique: Verdicts are based on 'good stdout/bad stdout'. The comparison function, though, is flexible. Thus, any type of script may be used for checking. It may be applied to any language that can produce standard output. See <a href="http://hwut.sourceforge.net/">HWUT</a> homepage.</p>
Debugging VBO Vertex buffers crashes <p>I'm using the VBO extension for storing Vertex, normal and color buffers (glBindBufferARB) For some reason when changing buffers or doing some operation the application crashes with an access violation. When attaching The debugger I see that the crash is in some thread that is not my main thread which performs the opengl call with the execution in some dll which is related to the nvidia graphics driver.</p> <p>What probably happened is that I gave some buffer call a bad buffer or with a wrong size. So my question is, how do I debug this situation? The crash seem to happen some time after the actual call and in a different thread.</p>
<p>Assuming this is about Windows, NVIDIA has a <a href="http://developer.nvidia.com/object/glexpert_home.html" rel="nofollow">GLExpert</a> tool. It can print various OpenGL warnings/errors.</p> <p>In some other cases, using <a href="http://glintercept.nutty.org/" rel="nofollow">GLIntercept</a> OpenGL call interceptor with error checking turned on can be useful.</p> <p>If the tools do not help, well, then it's good old debugging. Try to narrow down the problem and locate what exactly causes a crash. If it's a NVIDIA specific problem, try installing different drivers and/or asking on NVIDIA developer forums.</p>
Importing Access data into SQL Server using ColdFusion <p>This should be simple. I'm trying to import data from Access into SQL Server. I don't have direct access to the SQL Server database - it's on GoDaddy and they only allow web access. So I can't use the Management Studio tools, or other third-party Access upsizing programs that require remote access to the database.</p> <p>I wrote a query on the Access database and I'm trying to loop through and insert each record into the corresponding SQL Server table. But it keeps erroring out. I'm fairly certain it's because of the HTML and God knows what other weird characters are in one of the Access text fields. I tried using CFQUERYPARAM but that doesn't seem to help either.</p> <p>Any ideas would be helpful. Thanks.</p>
<p>Try using the <a href="http://blog.godaddyhosting.com/2007/07/20/presentingdrum-roll-please-the-ms-sql-backuprestore-feature.aspx" rel="nofollow">GoDaddy SQL backup/restore tool</a> to get a local copy of the database. At that point, use the <a href="http://www.microsoft.com/technet/prodtechnol/sql/2000/deploy/dtssql2k.mspx" rel="nofollow">SQL Server DTS tool</a> to import the data. It's an easy to use, drag-and-drop graphical interface.</p>
What is the best way to randomize an array's order in PHP without using the shuffle() function? <p>I was asked this question in a job interview. The interviewer and I disagreed on what the correct answer was. I'm wondering if anyone has any data on this.</p> <p>Update: I should have mentioned that the use of shuffle() was strictly forbidden... sorry.</p>
<p>shuffle($arr); :)</p> <p>edit: I should clarify... my definition of best involves not just algorithm efficiency but code readability and maintainability as well. Using standard library functions means maintaining less code and reading much less too. Beyond that, you can get into year-long debates with PhD professors about the best "true random" function, so somebody will always disagree with you on randomization questions.</p>
Anyone know of a list of delegates already built into the framework? <p>I find myself writing delegates occasionally for really simple functions (take no arguments and return void for example) and am wondering if anyone knows someplace that has compiled a list of all the predefined delegates already available in the .NET framework so I can reuse them?</p> <p>To be clear I am looking for something like this:</p> <ul> <li>void System.AsyncCallback(System.IAsyncResult)</li> <li>int System.Comparison(T x, T y)</li> <li>void System.IO.ErrorEventHandler(object, System.Io.ErrorEventArgs)</li> </ul> <p>and so on</p> <p>If not, sounds like a good idea for a blog article.</p>
<p>Just look in the msdn database for (T) delegate.</p> <p>Here you got a direct link: <a href="http://social.msdn.microsoft.com/Search/en-us/?Query=(T)%20delegate">List of delegates</a></p> <p>That should get you started.</p>
Application Level Replication Technologies <p>I am building out a solution that will be deployed in multiple data centers in multiple regions around the world, with each data center having a replicated copy of data actively updated in each region. I will have a combination of multiple databases and file systems in each data center, the state of which must be kept consistent (within a data center). These multiple repositories will be fronted by a SOA service tier. </p> <p>I can tolerate some latency in the replication, and need to allow for regions to be off-line, and then catch up later.</p> <p>Given the multiple back end repositories of data, I can't easily rely on independent replication solutions for each one to maintain a consistent state. I am thus lead to implementing replication at the application layer -- by replicating the SOA requests in some manner. I'll need to make sure that replication loops don't occur, and that last writer conditions are sorted out correctly.</p> <p>In your experience, what is the best pattern for solving this problem, and are there good products (free or otherwise) that should be investigated?</p>
<p>Lotus/ Domino is your answer. I've been working with it for ten years and its exactly what you need. It may not be trendy (a perception that I would challenge) but its powerful, adaptable and very secure, The latest version R8 is the best yet.</p>
Perl aids for regression testing <p>Is there a Perl module that allows me to view diffs between actual and reference output of programs (or functions)? The test fails if there are differences.</p> <p>Also, in case there are differences but the output is OK (because the functionality has changed) I want to be able to commit the actual output as future reference output.</p>
<p>Perl has excellent utilities for doing testing. The most commonly used module is probably Test::More, which provides all the infrastructure you're likely to need for writing regression tests. The prove utility provides an easy interface for running test suites and summarizing the results. The Test::Differences module (which can be used with Test::More) might be useful to you as well. It formats differences as side-by-side comparisons. As for committing the actual output as the new reference material, that will depend on how your code under test provides output and how you capture it. It should be easy if you write to files and then compare them. If that's the case you might want to use the Text::Diff module within your test suite.</p>
How do you launch the JavaScript debugger in Google Chrome? <p>When using Google Chrome, I want to debug some JavaScript code. How can I do that?</p>
<p>Try adding this to your source:</p> <pre><code>debugger; </code></pre> <p>It works in most, if not all browsers. Just place it somewhere in your code, and it will act like a breakpoint.</p>
When does System.gc() do anything <p>I know that garbage collection is automated in Java. But I understood that if you write <code>System.gc()</code> in your code the Java VM may or may not decide at runtime to do a garbage collection at that point. How does this work precisely? On what basis/parameters exactly does the VM decide to do (or not do) a GC when it sees a <code>System.gc()</code>? Are there maybe examples in which case it <strong>is</strong> a good idea to put this in your code?</p>
<p>In practice, it <em>usually</em> decides to do a garbage collection. The answer varies depending on lots of factors, like which JVM you're running on, which mode it's in, and which garbage collection algorithm it's using. </p> <p>I wouldn't depend on it in your code. If the JVM is about to throw an OutOfMemoryError, calling System.gc() won't stop it, because the garbage collector will attempt to free as much as it can before it goes to that extreme. The only time I've seen it used in practice is in IDEs where it's attached to a button that a user can click, but even there it's not terribly useful.</p>
How can I create a site in php and have it generate a static version? <p>For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client?</p> <p>Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I was on a PC, so I grabbed the windows version from here: <a href="http://gnuwin32.sourceforge.net/packages/wget.htm">http://gnuwin32.sourceforge.net/packages/wget.htm</a>.</p>
<p>If you have a Linux system available to you use <a href="http://www.gnu.org/software/wget/">wget</a>:</p> <pre><code>wget -k -K -E -r -l 10 -p -N -F -nH http://website.com/ </code></pre> <p>Options</p> <ul> <li>-k : convert links to relative</li> <li>-K : keep an original versions of files without the conversions made by wget</li> <li>-E : rename html files to .html (if they don’t already have an htm(l) extension)</li> <li>-r : recursive… of course we want to make a recursive copy</li> <li>-l 10 : the maximum level of recursion. if you have a really big website you may need to put a higher number, but 10 levels should be enough.</li> <li>-p : download all necessary files for each page (css, js, images)</li> <li>-N : Turn on time-stamping.</li> <li>-F : When input is read from a file, force it to be treated as an HTML file.</li> <li>-nH : By default, wget put files in a directory named after the site’s hostname. This will disabled creating of those hostname directories and put everything in the current directory.</li> </ul> <p>Source: <a href="http://blog.jphoude.qc.ca/2007/10/16/creating-static-copy-of-a-dynamic-website/">Jean-Pascal Houde's weblog</a></p>
Are there any tools to visualize a RDF graph? (please include a screenshot) <p>I'm looking for a tool that will render a RDF graph in a reasonably useful graphic format. The primary purpose of the graphic format being inclusion into a PowerPoint slide or printing on a large plotter for management review.</p> <p>I am currently using TopBraid Composer which does a reasonably well at visualizing a single entity but doesn't seem to have a clear way of visualizing the entire graph (as a whole).</p> <p>Anyone know of any good solutions to this problem?</p> <p><img src="http://i37.tinypic.com/2gufbz9.jpg" alt="TopBraid Composer Graph view screenshot" /></p>
<p><a href="http://semweb.salzburgresearch.at/apps/rdf-gravity/index.html">RDF Gravity</a> is an RDF visualisation tool.</p> <p>Here's a screenshot: <img src="http://semweb.salzburgresearch.at/apps/rdf-gravity/html/owl_ontology_1.jpg" alt="RDF Gravity Screenshot" /></p>
How do I create a new signal in pygtk <p>I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.</p>
<p>You can also define signals inside the class definition:</p> <pre><code>class MyGObjectClass(gobject.GObject): __gsignals__ = { "some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), } </code></pre> <p>The contents of the tuple are the the same as the three last arguments to <code>gobject.signal_new</code>.</p>
How to control the capitalization of month and day names returned by DateFormat? <p>Here is a quick test program:</p> <pre><code> public static void main( String[] args ) { Date date = Calendar.getInstance().getTime(); System.out.println("Months:"); printDate( "MMMM", "en", date ); printDate( "MMMM", "es", date ); printDate( "MMMM", "fr", date ); printDate( "MMMM", "de", date ); System.out.println("Days:"); printDate( "EEEE", "en", date ); printDate( "EEEE", "es", date ); printDate( "EEEE", "fr", date ); printDate( "EEEE", "de", date ); } public static void printDate( String format, String locale, Date date ) { System.out.println( locale + ": " + (new SimpleDateFormat( format, new Locale( locale ) )).format( date ) ); } </code></pre> <p>The output is:</p> <p><code> Months: en: September es: septiembre fr: septembre de: September Days: en: Monday es: lunes fr: lundi de: Montag</code></p> <p>How can I control the capitalization of the names. For some reason the Spanish and French always seem to return names that start with a lowercase letter.</p>
<p>Not all languages share english capitalization rules. I guess you'd need to alter the data used by the API, but your non-english clients might not appreciate it...</p> <p><a href="http://french.about.com/library/writing/bl-capitalization.htm">about.com on french capitalization</a></p>
Why is RSpec so slow under Rails? <p>Whenever I run rspec tests for my Rails application it takes forever and a day of overhead before it actually starts running tests. Why is rspec so slow? Is there a way to speed up Rails' initial load or single out the part of my Rails app I need (e.g. ActiveRecord stuff only) so it doesn't load absolutely everything to run a few tests?</p>
<p>I definitely suggest checking out spork.</p> <p><a href="http://spork.rubyforge.org/">http://spork.rubyforge.org/</a></p> <p>The railstutorial specifically addresses this, and gives a workaround to get spork running nicely in rails 3.0 (as of this moment, spork is not rails 3 ready out of the box). Of course, if you're not on rails 3.0, then you should be good to go.</p> <p>The part of the tutorial showing how to get spork running in rails 3.0</p> <p><a href="http://railstutorial.org/chapters/static-pages#sec:spork">http://railstutorial.org/chapters/static-pages#sec:spork</a></p> <p>Checking when spork is rails 3.0 ready</p> <p><a href="http://www.railsplugins.org/plugins/440-spork">http://www.railsplugins.org/plugins/440-spork</a></p>
Promising alternatives to make? <p>I've been using make and makefiles for many many years, and although the concept is sound, the implementation has something to be desired.</p> <p>Has anyone found any good alternatives to make that don't overcomplicate the problem?</p>
<p>check out <a href="http://www.scons.org/">SCons</a>. For example Doom 3 and Blender make uses of it.</p>
Custom style with Qt <p>Has anybody experience in building a custom style in Qt? What I have in my mind is a complete new style that affects all kind of widgets. I have seen some examples in the web for a custom combo box. But I have no idea how much time and code it takes to build a "complete" new custom style ... maybe someone can give me a hint.</p> <p>We think of using Qt 4.3 (or even newer) ...</p>
<p>Check out the <a href="http://doc.qt.io/qt-4.8/stylesheet.html" rel="nofollow">Stylesheets</a> facility in Qt 4. While it's still a hassle, it's way easier than doing a full-on custom style. You can just adjust one visual facet at a time and try it out.</p> <p>It pays attention to inheritance. So if you style the font in QWidget, then every visual widget will also use that font. And so on.</p>
Integration of JavaScript and JMS <p>Where can I find a guide for integrating JavaScript and JMS (Java Messaging Service)?</p> <p>I would like a best practice or established technology that allows me to directly or indirectly receive messages from a topic and update a site based on the message. I was thinking of creating two components, a servlet for the Web module, and an MDB (Message-Driven Bean) for the EJB module. The web client will comsume messages from the JMS topic, and the MDB will handle the onMessage.</p> <p>Does this sound correct? Have you seen any examples?</p> <p>Edit: I am using ActiveMQ for the JMS.</p>
<p>I think <a href="http://activemq.apache.org/ajax.html" rel="nofollow">this</a> is your answer. Looks like it is baked in to ActieMQ. I tried the examples and they seem to work.</p> <p><a href="http://activemq.apache.org/ajax.html" rel="nofollow">http://activemq.apache.org/ajax.html</a></p>
How do I run a program as nobody? <p>I want a user-privileged (not root) process to launch new processes as user <code>nobody</code>. I've tried a straight call to <code>setuid</code> that fails with -1 <code>EPERM</code> on <code>Ubuntu 8.04</code>:</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; int main() { setuid(65534); while (1); return 0; } </code></pre> <p>How should I do this instead?</p>
<p>You <em>will</em> require assistance and a lot of trust from your system administrator. Ordinary users are not able to run the executable of their choice on behalf on other users, period.</p> <p>She may add your application to <code>/etc/sudoers</code> with proper settings and you'll be able to run it as with <code>sudo -u nobody</code>. This will work for both scripts and binary executables.</p> <p>Another option is that she will do <code>chown nobody</code> and <code>chmod +s</code> on your binary executable and you'll be able to execute it directly. This task must be repeated each time your executable changes. </p> <p>This could also work for scripts if you'll create a tiny helper executable which simply does <code>exec("/home/you/bin/your-application")</code>. This executable can be made suid-nobody (see above) and you may freely modify <code>your-application</code>.</p> <p>Hope it helps,</p>
How to test credit card interactions? <p>After reading <a href="http://stackoverflow.com/questions/63668/confessions-of-your-worst-wtf-moment-what-not-to-do#63730">this answer</a>, I wonder if there's a way to get a "testing" credit card number. One that you can experiment with but that doesn't actually charge anything.</p>
<pre><code>MasterCard: 5431111111111111 Amex: 341111111111111 Discover: 6011601160116611 American Express (15 digits) 378282246310005 American Express (15 digits) 371449635398431 American Express Corporate (15 digits) 378734493671000 Diners Club (14 digits) 30569309025904 Diners Club (14 digits) 38520000023237 Discover (16 digits) 6011111111111117 Discover (16 digits) 6011000990139424 JCB (16 digits) 3530111333300000 JCB (16 digits) 3566002020360505 MasterCard (16 digits) 5555555555554444 MasterCard (16 digits) 5105105105105100 Visa (16 digits) 4111111111111111 Visa (16 digits) 4012888888881881 Visa (13 digits) 4222222222222 </code></pre> <p><strong>Credit Card Prefix Numbers:</strong> </p> <pre><code>Visa: 13 or 16 numbers starting with 4 MasterCard: 16 numbers starting with 5 Discover: 16 numbers starting with 6011 AMEX: 15 numbers starting with 34 or 37 </code></pre>
Fast, Pixel Precision 2D Drawing API for Graphics App? <p>I woud like to create a cross-platform drawing program. The one requirement for writing my app is that I have pixel level precision over the canvas. For instance, I want to write my own line drawing algorithm rather than rely on someone elses. I do not want any form of anti-aliasing (again, pixel level control is required.) I would like the users interactions on the screen to be quick and responsive (pending my ability to write fast algorithms.)</p> <p>Ideally, I would like to write this in Python, or perhaps Java as a second choice. The ability to easily make the final app cross-platform is a must. I will submit to different API's on different OS'es if necessary as long as I can write an abstraction layer around them. Any ideas?</p> <p>addendum: I need the ability to draw <em>on-screen</em>. Drawing out to a file I've got figured out.</p>
<p>The <a href="http://www.pyglet.org/" rel="nofollow">Pyglet</a> library for Python might suit your needs. It lets you use OpenGL, a cross-platform graphics API. You can disable anti-aliasing and capture regions of the screen to a buffer or a file. In addition, you can use its event handling, resource loading, and image manipulation systems. You can probably also tie it into PIL (Python Image Library), and definitely Cairo, a popular cross-platform vector graphics library.</p> <p>I mention Pyglet instead of pure PyOpenGL because Pyglet handles a lot of ugly OpenGL stuff transparently with no effort on your part.</p> <p>A friend and I are currently working on a drawing program using Pyglet. There are a few quirks - for example, OpenGL is always double buffered on OS X, so we have to draw everything twice, once for the current frame and again for the other frame, since they are flipped whenever the display refreshes. You can look at our current progress <a href="http://cwru-hackers.googlecode.com/svn/splatterboard/" rel="nofollow">in this subversion repository</a>. (Splatterboard.py in trunk is the file you'll want to run.) If you're not up on using svn, I would be happy to email you a .zip of the latest source. Feel free to steal code if you look into it.</p>
mod_python/MySQL error on INSERT with a lot of data: "OperationalError: (2006, 'MySQL server has gone away')" <p>When doing an INSERT with a lot of data, ie:</p> <pre><code>INSERT INTO table (mediumtext_field) VALUES ('...lots of text here: about 2MB worth...') </code></pre> <p>MySQL returns </p> <blockquote> <p>"OperationalError: (2006, 'MySQL server has gone away')"</p> </blockquote> <p>This is happening within a minute of starting the script, so it is not a timeout issue. Also, <code>mediumtext_field</code> should be able to hold ~16MB of data, so that shouldn't be a problem.</p> <p>Any ideas what is causing the error or how to work around it?</p> <p>Some relevant libraries being used: <code>mod_python 3.3.1</code>, <code>MySQL 5.0.51</code> (on Windows XP SP3, via xampp, details below)</p> <p><strong>ApacheFriends XAMPP (basic package) version 1.6.5</strong></p> <ul> <li>Apache 2.2.6</li> <li>MySQL 5.0.51</li> <li>phpMyAdmin 2.11.3</li> </ul>
<p>check the max_packet setting in your my.cnf file. this determines the largest amount of data you can send to your mysql server in a single statement. exceeding this values results in that error.</p>
Tool recommendation for converting VB to C# <p>We have a project with over 500,000 lines of VB.NET that we need to convert to C#. Any recommendations, based on experience, for tools to use? We are using Visual Studio 2008 and we're targeting 3.5 .</p>
<p>I would concur with the comment. You have 500,000 of tried and true VB.Net code. Why on earth would you waste any time changing that? No one says that you can't write all new components in C#. </p> <p>I would consider not worrying about a tool and instead ask yourself, truly, why you are doing this.</p>
Why doesn't BackColor work for TabControls in .NET? <p>If you use the standard tab control in .NET for your tab pages and you try to change the look and feel a little bit then you are able to change the back color of the tab pages but not for the tab control. The property is available, you could set it but it has no effect. If you change the back color of the pages and not of the tab control it looks... uhm quite ugly.</p> <p>I know Microsoft doesn't want it to be set. <a href="http://msdn.microsoft.com/en/library/w4sc610z(VS.80).aspx" rel="nofollow">MSDN</a>: '<i>This property supports the .NET Framework infrastructure and is not intended to be used directly from your code. This member is not meaningful for this control.</i>' A control property just for color which supports the .NET infrastructure? ...hard to believe.</p> <p>I hoped over the years Microsoft would change it but they did not. I created my own TabControl class which overrides the paint method to fix this. But is this really the best solution?</p> <p>What is the reason for not supporting BackColor for this control? What is your solution to fix this? Is there a better solution than overriding the paint method?</p>
<p>The solution in Rajesh's blog is really useful, but it colours the tab part of the control only. In my case I had a tabcontrol on a different coloured background. The tabs themselves were grey which wasn't a problem, but the area to the right of the tabs was displaying as a grey strip. </p> <p>To change this colour to the colour of your background you need to add the following code to the DrawItem method (as described in Rajesh's solution). I'm using VB.Net:</p> <pre><code>... Dim r As Rectangle = tabControl1.GetTabRect(tabControl1.TabPages.Count-1) Dim rf As RectangleF = New RectangleF(r.X + r.Width, r.Y - 5, tabControl1.Width - (r.X + r.Width), r.Height + 5) Dim b As Brush = New SolidBrush(Color.White) e.Graphics.FillRectangle(b, rf) ... </code></pre> <p>Basically you need to get the rectangle made of the right hand side of the last tab to the right hand side of the tab control and then fill it to your desired colour.</p>
Dynamically Create a generic type for template <p>I'm programming WCF using the ChannelFactory which expects a type in order to call the CreateChannel method. For example: </p> <pre><code>IProxy proxy = ChannelFactory&lt;IProxy&gt;.CreateChannel(...); </code></pre> <p>In my case I'm doing routing so I don't know what type my channel factory will be using. I can parse a message header to determine the type but I hit a brick wall there because even if I have an instance of Type I can't pass that where ChannelFactory expects a generic type. </p> <p>Another way of restating this problem in very simple terms would be that I'm attempting to do something like this:</p> <pre><code>string listtype = Console.ReadLine(); // say "System.Int32" Type t = Type.GetType( listtype); List&lt;t&gt; myIntegers = new List&lt;&gt;(); // does not compile, expects a "type" List&lt;typeof(t)&gt; myIntegers = new List&lt;typeof(t)&gt;(); // interesting - type must resolve at compile time? </code></pre> <p>Is there an approach to this I can leverage within C#?</p>
<p>What you are looking for is MakeGenericType</p> <pre><code>string elementTypeName = Console.ReadLine(); Type elementType = Type.GetType(elementTypeName); Type[] types = new Type[] { elementType }; Type listType = typeof(List&lt;&gt;); Type genericType = listType.MakeGenericType(types); IProxy proxy = (IProxy)Activator.CreateInstance(genericType); </code></pre> <p>So what you are doing is getting the type-definition of the generic "template" class, then building a specialization of the type using your runtime-driving types.</p>
Why does sed fail with International characters and how to fix? <p>GNU sed version 4.1.5 seems to fail with International chars. Here is my input file:</p> <p>Gras Och Stenar Trad - From Moja to Minneapolis DVD [G2007DVD] 7812 | X <br> Gras Och Stenar Trad - From Möja to Minneapolis DVD [G2007DVD] 7812 | Y</p> <p>(Note the umlaut in second line.)</p> <p>And when I do</p> <p>sed 's/.*| //' &lt; in</p> <p>I would expect to see only the X and Y, as I've asked to remove ALL chars up to the '|' and space beyond it. Instead, I get:</p> <p>X<br> Gras Och Stenar Trad - From M? Y</p> <p>I know I can use tr to remove the International chars. first, but is there a way to just use sed?</p>
<p>I think the error occurs if the input encoding of the file is different from the preferred encoding of your environment. </p> <p>Example: <code>in</code> is UTF-8</p> <pre><code>$ LANG=de_DE.UTF-8 sed 's/.*| //' &lt; in X Y $ LANG=de_DE.iso88591 sed 's/.*| //' &lt; in X Y </code></pre> <p>UTF-8 can safely be interpreted as ISO-8859-1, you'll get strange characters but apart from that everything is fine.</p> <p>Example: <code>in</code> is ISO-8859-1</p> <pre><code>$ LANG=de_DE.UTF-8 sed 's/.*| //' &lt; in X Gras Och Stenar Trad - From MöY $ LANG=de_DE.iso88591 sed 's/.*| //' &lt; in X Y </code></pre> <p>ISO-8859-1 cannot be interpreted as UTF-8, decoding the input file fails. The strange match is probably due to the fact that sed tries to recover rather than fail completely.</p> <p>The answer is based on Debian Lenny/Sid and sed 4.1.5.</p>
Other than Xcode, are there any full functioned IDEs for Objective-C? <p>I know and have Xcode, but I was wondering if there were any other complete development environments that support Objective-C? I'm not looking for solutions with vim or emacs, nor editors like BBEdit that support syntax highlighting, but a full fledged IDE with:</p> <ul> <li>code completion</li> <li>compilation</li> <li>debugging</li> <li>refactoring</li> </ul> <p>Extra points for being cross platform, supporting vi key bindings and supporting other languages.</p> <h3>Note:</h3> <p>I've updated and accepted my answer below as Jetbrains has released Early Access for <em>AppCode</em>, their new Objective-C IDE. Since this has been a fairly popular question, I thought it worthwhile to update the information.</p>
<p>I recently learned that <a href="http://www.jetbrains.com/">Jetbrains</a> the make of my favorite IDE (Idea) may support Objective-C (though it is unclear how much it will work for iPhone/iPad development). See the thread <a href="http://www.jetbrains.net/devnet/thread/282271?tstart=0">here</a> for early discussion on this.</p> <p>In the last year or two, they have started adding additional language support both in their flagship IDE as well as specialized IDEs (for Ruby, Python, PHP). I guess this is just another step in the process. I for one would love to have another option other than XCode and I couldn't think of one that I'd love more.</p> <p>This is obviously vaporware at the moment, but I think it is something to keep an eye on.</p> <p>This is now a real product, albeit still in Early Access. See <a href="http://blog.jetbrains.com/objc/">here</a> for a the blog on this new product, which will give you pointers to check out the EAP.</p> <p>UPDATE: <a href="http://www.jetbrains.com/objc/">AppCode</a> has now been released and offers a true alternative to using Xcode for Objective-C and iPhone/iPad/Mac development. It does still rely on Interface Builder for layout and wiring of GUI components and uses the iOS simulator, but all coding, including a slew of refactorings, smart templating and static analysis, is available through App Code.</p>
Perl Sys::Syslog on Solaris <p>Has anyone got <a href="http://perldoc.perl.org/Sys/Syslog.html" rel="nofollow">Sys::Syslog</a> to work on Solaris? (I'm running Sys::Syslog 0.05 on Perl v5.8.4 on SunOS 5.10 on SPARC). Here's what doesn't work for me:</p> <pre><code>openlog "myprog", "pid", "user" or die; syslog "crit", "%s", "Test from $0" or die; closelog() or warn "Can't close: $!"; system "tail /var/adm/messages"; </code></pre> <p>Whatever I do, the closelog returns an error and nothing ever gets logged anywhere.</p>
<p>By default, Sys::Syslog is going to try to connect with one of the following socket types:</p> <pre><code>[ 'tcp', 'udp', 'unix', 'stream' ] </code></pre> <p>On Solaris, though, you'll need to use an inet socket. Call:</p> <pre><code>setlogsock('inet', $hostname); </code></pre> <p>and things should start working.</p>
Where can I find an example burn-down / planning game template? <p>I'd like to experiment with burn-down and planning game with the team I'm on. People on my team are interested in making it happen, however I'm sure someone has done this before and has learned some lessons we hopefully don't have to repeat. Does anyone know of an example Excel (or other tool) template available for burn-down or planning game activities?</p>
<p><a href="http://blogs.msdn.com/progressive_development/archive/2008/02/19/motley-says-what-are-we-burning-down-your-house-scrum-part-v.aspx" rel="nofollow">This MSDN Blog article</a> Has quite a good review of using burndowns in combination with Cumulative Flow Diagrams which fleshes out the diagrams even more. In the resources links at the bottom of the article there is a <a href="http://go.microsoft.com/fwlink/?LinkId=98602&amp;clcid=0x409" rel="nofollow">link to the Microsoft Scrum kit</a> which has a pre-built excel file.</p>
Is there any way to pass a structure type to a c function <p>I have some code with multiple functions very similar to each other to look up an item in a list based on the contents of one field in a structure. The only difference between the functions is the type of the structure that the look up is occurring in. If I could pass in the type, I could remove all the code duplication.</p> <p>I also noticed that there is some mutex locking happening in these functions as well, so I think I might leave them alone...</p>
<p>If you ensure that the field is placed in the same place in each such structure, you can simply cast a pointer to get at the field. This technique is used in lots of low level system libraries e.g. BSD sockets.</p> <pre><code>struct person { int index; }; struct clown { int index; char *hat; }; /* we're not going to define a firetruck here */ struct firetruck; struct fireman { int index; struct firetruck *truck; }; int getindexof(struct person *who) { return who-&gt;index; } int main(int argc, char *argv[]) { struct fireman sam; /* somehow sam gets initialised */ sam.index = 5; int index = getindexof((struct person *) &amp;sam); printf("Sam's index is %d\n", index); return 0; } </code></pre> <p>You lose type safety by doing this, but it's a valuable technique.</p> <p>[ I have now actually tested the above code and fixed the various minor errors. It's much easier when you have a compiler. ]</p>
How to debug a JSP tomcat service using eclipse? <p>I would like to debug my separately running JSP/Struts/Tomcat/Hibernate application stack using the Eclipse IDE debugger. How do I setup the java JVM and eclipse so that I can set breakpoints, monitor variable values, and see the code that is currently executing?</p>
<p>I just Googled it. :)</p> <p><a href="http://bugs.sakaiproject.org/confluence/display/BOOT/Setting+Up+Tomcat+For+Remote+Debugging">http://bugs.sakaiproject.org/confluence/display/BOOT/Setting+Up+Tomcat+For+Remote+Debugging</a></p> <p>Many more on google.</p> <p>Effectively, set your JPDA settings: set JPDA_ADDRESS=8000 set JPDA_TRANSPORT=dt_socket bin/catalina.bat jpda start</p> <p>Then, in Eclipse, Run->Debug Configurations...->Remote Applications.</p>
What's the best way to hash a url in ruby? <p>I'm writing a web app that points to external links. I'm looking to create a non-sequential, non-guessable id for each document that I can use in the URL. I did the obvious thing: treating the url as a string and str#crypt on it, but that seems to choke on any non-alphanumberic characters, like the slashes, dots and underscores.</p> <p>Any suggestions on the best way to solve this problem?</p> <p>Thanks!</p>
<p>Depending on how long a string you would like you can use a few alternatives:</p> <pre><code>require 'digest' Digest.hexencode('http://foo-bar.com/yay/?foo=bar&amp;a=22') # "687474703a2f2f666f6f2d6261722e636f6d2f7961792f3f666f6f3d62617226613d3232" require 'digest/md5' Digest::MD5.hexdigest('http://foo-bar.com/yay/?foo=bar&amp;a=22') # "43facc5eb5ce09fd41a6b55dba3fe2fe" require 'digest/sha1' Digest::SHA1.hexdigest('http://foo-bar.com/yay/?foo=bar&amp;a=22') # "2aba83b05dc9c2d9db7e5d34e69787d0a5e28fc5" require 'digest/sha2' Digest::SHA2.hexdigest('http://foo-bar.com/yay/?foo=bar&amp;a=22') # "e78f3d17c1c0f8d8c4f6bd91f175287516ecf78a4027d627ebcacfca822574b2" </code></pre> <p>Note that this won't be unguessable, you may have to combine it with some other (secret but static) data to salt the string:</p> <pre><code>salt = 'foobar' Digest::SHA1.hexdigest(salt + 'http://foo-bar.com/yay/?foo=bar&amp;a=22') # "dbf43aff5e808ae471aa1893c6ec992088219bbb" </code></pre> <p>Now it becomes much harder to generate this hash for someone who doesn't know the original content and has no access to your source.</p>
How do I register a custom type converter in Spring? <p>I need to pass a UUID instance via http request parameter. Spring needs a custom type converter (from String) to be registered. How do I register one?</p>
<p>Please see chapter 5 of the spring reference manual here: <a href="http://static.springframework.org/spring/docs/2.5.x/reference/validation.html#beans-beans-conversion-customeditor-registration" rel="nofollow">5.4.2.1. Registering additional custom PropertyEditors</a></p>
Wildcards for resources in a Tomcat Servlet's context.xml <p>I'm not overly familiar with Tomcat, but my team has inherited a complex project that revolves around a Java Servlet being hosted in Tomcat across many servers. Custom configuration management software is used to write out the server.xml, and various resources (connection pools, beans, server variables, etc) written into server.xml configure the servlet. This is all well and good.</p> <p>However, the names of some of the resources aren't known in advance. For example, the Servlet may need access to any number of "Anonymizers" as configured by the operator. Each anonymizer has a unique name associated with it. We create and configure each anonymizer using java beans similar to the following:</p> <pre><code>&lt;Resource name="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="50" /&gt; &lt;Resource name="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="54" /&gt; </code></pre> <p>However, this appears to require us to have explicit entries in the Servlet's context.xml file for each an every possible resource name in advance. I'd like to replace the explicit context.xml entries with wildcards, or know if there is a better solution to this type of problem.</p> <p>Currently:</p> <pre><code> &lt;ResourceLink name="bean/Anonymizer_default" global="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean"/&gt; &lt;ResourceLink name="bean/Anonymizer_toon" global="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean"/&gt; </code></pre> <p>Replaced with something like:</p> <pre><code> &lt;ResourceLink name="bean/Anonymizer_*" global="bean/Anonymizer_*" type="com.company.tomcatutil.AnonymizerBean"/&gt; </code></pre> <p>However, I haven't been able to figure out if this is possible or what the correct syntax might be. Can anyone make any suggestions about better ways to handle this?</p>
<p>I don't know if it's what you require, but perhaps you may want to investigate creating your own custom resource factory for Tomcat. Here is the general documentation for all things resources via Tomcat: <a href="http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html" rel="nofollow">Tomcat Resources</a></p>
How Long Do You Keep Your Code? <p>I took a data structures class in C++ last year, and consequently implemented all the major data structures in templated code. I saved it all on a flash drive because I have a feeling that at some point in my life, I'll use it again. I imagine <em>something</em> I end up programming will need a B-Tree, or is that just delusional? How long do you typically save the code you write for possible reuse? </p>
<p>Forever (or as close as I can get). That's the whole point of a source control system.</p>
Is it possible to get a core dump of a running process and its symbol table? <p>Is it possible to get gdb or use some other tools to create a core dump of a running process and it's symbol table? It would be great if there's a way to do this without terminating the process. </p> <p>If this is possible, what commands would you use? (I'm trying to do this on a Linux box)</p>
<pre> $ gdb --pid=26426 (gdb) gcore Saved corefile core.26426 (gdb) detach </pre>
What level of complexity requires a framework? <p>At what level of complexity is it mandatory to switch to an existing framework for web development?</p> <p>What measurement of complexity is practical for web development? Code length? Feature list? Database Size?</p>
<p>If you work on several different sites then by using a common framework across all of them you can spend time working on the code rather than trying to remember what is located where and why.</p> <p>I'd always use a framework of some sort, even if it's your own, as the uniformity will help you structure your project. Unless it's a one page static HTML project.</p> <p>There is no mandatory limit however.</p>
How to start/plan a software project for data collection on a PDA/handheld device <p>A friend is having mysterious health problems that we're trying to track down. One thing that would help would be to improve his record keeping by giving him a handheld device with which he could keep track of various details of his day including diet and environmental factors.</p> <p>We will be getting him a device but haven't decided on Palm vs. Windows Mobile vs. other. I'd like to find some existing software but so far haven't been able to find something that is general enough or customizable to fit our needs. Ideally I'd like to find an open source project that I can join and contribute while customizing the software to do what I need it to, which I haven't even totally defined yet.</p> <p>I'm a C++ developer (way too) familiar with MSVS6 but would be happy to have an excuse to get into .NET or other modern frameworks. But if the easiest and quickest option is to work with something in C for the Palm I'd be happy to do that as well. (I've found a good but somewhat dated reference for <a href="http://answers.google.com/answers/threadview/id/123584.html" rel="nofollow">C++ programming for the Palm</a>) Similar and more recent info like this is what I'm looking for.</p> <p>Thanks for any advice or suggestions about how to get started with this. </p>
<p>DataViz offers a program for PalmOS called <a href="http://www.dataviz.com/products/smartlisttogo/index.html" rel="nofollow">SmartListToGo</a>. It hasn't been updated in a while, but if you're basically collecting data, you can design forms/tables with minimal programming knowledge. I've used it to keep track of mileage/car repairs. I've also used it to keep track of health insurance invoices.</p> <p>It's not open source, and it actually hasn't had an update of significance in a while. You can even write plugins for it if you are unable to get what you need out of the basic functionality.</p>
Text Centering Using CSS not working in IE <p>I am having problems getting text within a table to appear centered in IE. </p> <p>In Firefox 2, 3 and Safari everything work fine, but for some reason, the text doesn't appear centered in IE 6 or 7. </p> <p>I'm using:</p> <pre class="lang-css prettyprint-override"><code>h2 { font: 300 12px "Helvetica", serif; text-align: center; text-transform: uppercase; } </code></pre> <p>I've also tried adding <code>margin-left:auto;</code>, <code>margin-right:auto</code> and <code>position:relative;</code> </p> <p>to no avail. </p>
<p>Can we see more code? My first hunch is the table cell needs the text-align: center.</p>
Are tuples more efficient than lists in Python? <p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
<p>In general, you might expect tuples to be slightly faster. However you should definitely test your specific case (if the difference might impact the performance of your program -- remember "premature optimization is the root of all evil").</p> <p>Python makes this very easy: <a href="https://docs.python.org/2/library/timeit.html">timeit</a> is your friend.</p> <pre><code>$ python -m timeit "x=(1,2,3,4,5,6,7,8)" 10000000 loops, best of 3: 0.0388 usec per loop $ python -m timeit "x=[1,2,3,4,5,6,7,8]" 1000000 loops, best of 3: 0.363 usec per loop </code></pre> <p>and...</p> <pre><code>$ python -m timeit -s "x=(1,2,3,4,5,6,7,8)" "y=x[3]" 10000000 loops, best of 3: 0.0938 usec per loop $ python -m timeit -s "x=[1,2,3,4,5,6,7,8]" "y=x[3]" 10000000 loops, best of 3: 0.0649 usec per loop </code></pre> <p>So in this case, instantiation is almost an order of magnitude faster for the tuple, but item access is actually somewhat faster for the list! So if you're creating a few tuples and accessing them many many times, it may actually be faster to use lists instead.</p> <p>Of course if you want to <em>change</em> an item, the list will definitely be faster since you'd need to create an entire new tuple to change one item of it (since tuples are immutable).</p>
Can you have a class in a struct? <p>Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both?</p>
<p>Yes, you can. The pointer to the class member variable is stored <strike>on the stack</strike> with the rest of the struct's values, and the class instance's data is stored on the heap.</p> <p>Structs can also contain class definitions as members (inner classes).</p> <p>Here's some really useless code that at least compiles and runs to show that it's possible:</p> <pre><code>using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MyStr m = new MyStr(); m.Foo(); MyStr.MyStrInner mi = new MyStr.MyStrInner(); mi.Bar(); Console.ReadLine(); } } public class Myclass { public int a; } struct MyStr { Myclass mc; public void Foo() { mc = new Myclass(); mc.a = 1; } public class MyStrInner { string x = "abc"; public string Bar() { return x; } } } } </code></pre>
How do you write a C# Extension Method for a Generically Typed Class <p>This should hopefully be a simple one.</p> <p>I would like to add an extension method to the System.Web.Mvc.ViewPage&lt; T > class.</p> <p>How should this extension method look?</p> <p>My first intuitive thought is something like this:</p> <pre><code>namespace System.Web.Mvc { public static class ViewPageExtensions { public static string GetDefaultPageTitle(this ViewPage&lt;Type&gt; v) { return ""; } } } </code></pre> <p><strong>Solution</strong></p> <p>The general solution is <a href="http://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772">this answer</a>.</p> <p>The specific solution to extending the System.Web.Mvc.ViewPage class is <a href="http://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68802">my answer</a> below, which started from the <a href="http://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772">general solution</a>.</p> <p>The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type.</p>
<p>I don't have VS installed on my current machine, but I think the syntax would be:</p> <pre><code>namespace System.Web.Mvc { public static class ViewPageExtensions { public static string GetDefaultPageTitle&lt;T&gt;(this ViewPage&lt;T&gt; v) { return ""; } } } </code></pre>
Visual Studio basicHttpBinding and endpoint problems <p>I have a WPF application in VS 2008 with some web service references. For varying reasons (max message size, authentication methods) I need to manually define a number of settings in the WPF client's app.config for the service bindings.</p> <p>Unfortunately, this means that when I update the service references in the project we end up with a mess - multiple bindings and endpoints. Visual Studio creates new bindings and endpoints with a numeric suffix (ie "Service1" as a duplicate of "Service"), resulting in an invalid configuration as there may only be a single binding per service reference in a project.</p> <p>This is easy to duplicate - just create a simple "Hello World" ASP.Net web service and WPF application in a solution, change the maxBufferSize and maxReceivedMessageSize in the app.config binding and then update the service reference.</p> <p>At the moment we are working around this by simply undoing checkout on the app.config after updating the references but I can't help but think there must be a better way!</p> <p>Also, the settings we need to manually change are:</p> <pre><code>&lt;security mode="TransportCredentialOnly"&gt; &lt;transport clientCredentialType="Ntlm" /&gt; &lt;/security&gt; </code></pre> <p>and:</p> <pre><code>&lt;binding maxBufferSize="655360" maxReceivedMessageSize="655360" /&gt; </code></pre> <p>We use a service factory class so if these settings are somehow able to be set programmatically that would work, although the properties don't seem to be exposed.</p>
<p>Create a .Bat file which uses svcutil, for proxygeneration, that has the settings that is right for your project. It's fairly easy. Clicking on the batfile, to generate new proxyfiles whenever the interface have been changed is easy.</p> <p>The batch can then later be used in automated builds. Then you only need to set up the app.config (or web.config) once. We generally separate the different configs for different environments, such as dev, test prod.</p> <p>Example (watch out for linebreaks):</p> <pre><code>REM generate meta data call "SVCUTIL.EXE" /t:metadata "MyProject.dll" /reference:"MyReference.dll" REM making sure the file is writable attrib -r "MyServiceProxy.cs" REM create new proxy file call "SVCUTIL.EXE" /t:code *.wsdl *.xsd /serializable /serializer:Auto /collectionType:System.Collections.Generic.List`1 /out:"MyServiceProxy.cs" /namespace:*,MY.Name.Space /reference:"MyReference.dll" </code></pre> <p>:)</p> <p>//W</p>
In Applescript, how can I find out if a menu item is selected/focused? <p>I have a script for OS X 10.5 that focuses the Search box in the Help menu of any application. I have it on a key combination and, much like Spotlight, I want it to toggle when I run the script. So, I want to detect if the search box is already focused for typing, and if so, type Esc instead of clicking the Help menu.</p> <p>Here is the script as it stands now:</p> <pre><code>tell application "System Events" tell (first process whose frontmost is true) set helpMenuItem to menu bar item "Help" of menu bar 1 click helpMenuItem end tell end tell </code></pre> <p>And I'm thinking of something like this:</p> <pre><code>tell application "System Events" tell (first process whose frontmost is true) set helpMenuItem to menu bar item "Help" of menu bar 1 set searchBox to menu item 1 of menu of helpMenuItem if (searchBox's focused) = true then key code 53 -- type esc else click helpMenuItem end if end tell end tell </code></pre> <p>... but I get this error:</p> <blockquote> <p>Can’t get focused of {menu item 1 of menu "Help" of menu bar item "Help" of menu bar 1 of application process "Script Editor" of application "System Events"}.</p> </blockquote> <p>So is there a way I can get my script to detect whether the search box is already focused?</p> <p><hr /></p> <p>I solved my problem by <a href="http://stackoverflow.com/questions/69391/">working around it</a>. I still don't know how to check if a menu item is selected though, so I will leave this topic open.</p>
<p>The built in key shortcut cmd-? already behaves like this. It moves key focus to the help menu's search field if it is not already focused, and otherwise dismisses the menu.</p>
Agile project and amount of Documentation <p>What kind of documentation you'd recommend to support for Agile project? What are the core metrics you use to detect amount of documentation needed? Do you think you can store all of project info as TFS work items?</p>
<p><strong>Create documentation that speeds up communication and helps you move faster.</strong> Let the principle of "Mutual Benefit" guide you.</p> <ul> <li>Adoption documents: "NewPerson handbook". Getting started with any "framework" or niche tools you are using. <em>The best way might be to get the first bunch of newbies to collaborate on refining the content... listen to the Voice of the people.</em> </li> <li>Instructions for Setting up a development machine is another good one. Source Control server settings, Installation paths for tools used.</li> <li>Also document team conventions if any. </li> <li>Product Maps: You would need product design roadmaps - block diagrams of various top-level components and the like. Tests can serve as the always updated specs - ground zero documentation.. but you need a simple word doc ... bulleted list of high level product needs / features.</li> <li>"Here the dragons lie" - any known minefields with products (esp. legacy), 'Don't tread here' areas that you need to be careful while changing.. e.g. If you change something here, make sure you have it reviewed by Y and Z before checking in.</li> <li><em>Update from <strong>Dimarzionist</strong>:</em> Stash away decisions taken during development, reasons and supporting evidence (mail chains) if needed in a 'well-known place'</li> </ul> <p>Core Metric: <strong>If you find no one on the team complaining "WTH? Why didnt anyone document this? I'm stuck.. How am I supposed to proceed on this?" - you're good.</strong></p> <ul> <li>If the team finds that they have been drawing a class diagram or sequence diagram over and over, that's proof that it is a useful artifact. Soon someone will make a sticky copy and save it somewhere to save time. Over time , the more useful artifacts would build up. </li> <li>Don't pester the team to churn out documents no one else will read...(No "This is mandated by the process")</li> <li>Don't create documents that are 40-50 pages long. No one will read them.. "Take more time and write a shorter letter" 5-6 pages max.</li> </ul> <p>Finally as for TFS, once again let the team tell you. If it seems to be working well.. continue if not find alternatives &amp; switch.</p>
A snippet to monitor the last INSERT/UPDATE in an Oracle DB from C#? <p>I'm looking for a simple, sample snippet of C# code to monitor an Oracle database and basically check for its last update. It could be either command line (great for future integration with Nagios) or GUI. I've did some prototypes but the code tend to get lengthy as I'm still kind of learning the language.</p> <p>Any suggestion/comment would be much appreciated.</p>
<p>One possible solution is:</p> <ol> <li><p>Add a DATE field that represents the last update time to MY_TABLE table.</p> <p><code>ALTER TABLE my_table ADD (last_update_time DATE);</code></p></li> <li><p>Create an index on that field.</p> <p><code>CREATE INDEX i_my_table_upd_time ON my_table (last_update_time);</code></p></li> <li><p>Create a database trigger on that table that fires ON UPDATE and ON INSERT and stores SYSDATE into the new field.</p> <pre><code>CREATE OR REPLACE TRIGGER my_table_insert_trg BEFORE INSERT OR UPDATE ON my_table FOR EACH ROW BEGIN :new.last_update_time := SYSDATE; END; </code></pre></li> </ol> <p>Now you can issue the following query every 5 minutes</p> <pre><code>SELECT max(last_update_time) FROM my_table; </code></pre> <p>and it will give you the time when your table was last updated.</p> <p>There is no easy way to get a notification from Oracle, sorry.</p>
Why does a C/C++ program often have optimization turned off in debug mode? <p>In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.<br /> Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.<br /> In "release" mode, you usually have all sorts of optimizations turned on.<br /> Why the difference?</p>
<p>Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.<br> For example:</p> <pre><code> void foo() { 1: int i; 2: for(i = 0; i &lt 2; ) 3: i++; 4: return; </code></pre> <p>In this example, without optimization, you could single step through the code and hit lines 1, 2, 3, 2, 3, 2, 4</p> <p>With optimization on, you might get an execution path that looks like: 2, 3, 3, 4 or even just 4! (The function does nothing after all...)</p> <p>Bottom line, debugging code with optimization enabled can be a royal pain! Especially if you have large functions.</p> <p>Note that turning on optimization changes the code! In certain environment (safety critical systems), this is unacceptable and the code being debugged has to be the code shipped. Gotta debug with optimization on in that case.</p> <p>While the optimized and non-optimized code should be "functionally" equivalent, under certain circumstances, the behavior will change.<br> Here is a simplistic example:<br> <code><pre> int* ptr = 0xdeadbeef; // some address to memory-mapped I/O device *ptr = 0; // setup hardware device while(*ptr == 1) { // loop until hardware device is done // do something } </pre></code></p> <p>With optimization off, this is straightforward, and you kinda know what to expect. However, if you turn optimization on, a couple of things might happen:</p> <ul> <li>The compiler might optimize the while block away (we init to 0, it'll never be 1)</li> <li>Instead of accessing memory, pointer access might be moved to a register->No I/O Update</li> <li>memory access might be cached (not necessarily compiler optimization related)</li> </ul> <p>In all these cases, the behavior would be drastically different and most likely wrong.</p>
Zend PHP debugger: How can I start debugging a page using a get argument? <p>I am trying out the debugger built into <code>Zend studio</code>. It seems great! One thing though, when I start a page using the debugger does anyone know how I can set a request get argument within the page?</p> <p>For example, I don't want to debug runtests.php</p> <p>I want to debug <code>runtests.php?test=10</code></p> <p>I assume its a simple configuration and I just can't find it.</p>
<p>I recommend getting the <a href="http://www.zend.com/en/products/studio/downloads" rel="nofollow">Zend Studio Toolbar</a>. The extension allows you to control which pages are debugged from within the browser instead of from Zend Studio. The options for debugging let you debug the next page, the next form post or all pages. When you debug like this it runs the PHP just like it will from your server instead of from within Zend Studio. It's an essential tool when using Zend Studio. </p>
Is there a way to make text unselectable on an HTML page? <p>I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.</p> <p>I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers.</p>
<p>In most browsers, this can be achieved using CSS:</p> <pre class="lang-css prettyprint-override"><code>*.unselectable { -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; /* Introduced in IE 10. See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/ */ -ms-user-select: none; user-select: none; } </code></pre> <p>For IE &lt; 10 and Opera, you will need to use the <code>unselectable</code> attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:</p> <pre><code>&lt;div id="foo" unselectable="on" class="unselectable"&gt;...&lt;/div&gt; </code></pre> <p>Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <code>&lt;div&gt;</code>. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:</p> <pre><code>function makeUnselectable(node) { if (node.nodeType == 1) { node.setAttribute("unselectable", "on"); } var child = node.firstChild; while (child) { makeUnselectable(child); child = child.nextSibling; } } makeUnselectable(document.getElementById("foo")); </code></pre>
What Safari-specific pure CSS hacks are out there? <p>I'm wondering if there's any way to write CSS specifically for Safari using only CSS. I know there has to be something out there, but I haven't found it yet.</p>
<p>I think the question is valid. I agree with the other responses, but it doesn't mean it's a terrible question. I've only ever had to use a Safari CSS hack once as a temporary solution and later got rid of it. I agree that you shouldn't have to target just Safari, but no harm in knowing how to do it.</p> <p>FYI, this hack only targets Safari 3, and also targets Opera 9.</p> <pre><code>@media screen and (-webkit-min-device-pixel-ratio:0) { /* Safari 3.0 and Opera 9 rules here */ } </code></pre>
Getting The XML Data Inside Custom XPath function <p>Is there a way to get the current xml data when we make our own custom XPath function (see here).</p> <p>I know you have access to an <code>XPathContext</code> but is this enough?</p> <p><strong>Example:</strong></p> <p>Our XML:</p> <pre><code>&lt;foo&gt; &lt;bar&gt;smang&lt;/bar&gt; &lt;fizz&gt;buzz&lt;/fizz&gt; &lt;/foo&gt; </code></pre> <p>Our XSL:</p> <pre><code>&lt;xsl:template match="/"&gt; &lt;xsl:value-of select="ourFunction()" /&gt; &lt;/xsl:template&gt; </code></pre> <p>How do we get the entire XML tree?</p> <p><strong>Edit:</strong> To clarify: I'm creating a custom function that ends up executing static Java code (it's a Saxon feature). So, in this Java code, I wish to be able to get elements from the XML tree, such as bar and fizz, and their CDATA, such as smang and buzz.</p>
<p>What about <strike>select the current node</strike> selecting the relevant data from the current node into an XSL parameter, and passing that parameter to the function? Like:</p> <pre><code>&lt;xsl:value-of select="ourFunction($data)" /&gt; </code></pre>
How do I change the background color in gnuplot? <p>I have a script that renders graphs in gnuplot. The graphs all end up with an ugly white background. How do I change this? (Ideally, with a command that goes into a gnuplot script, as opposed to a command-line option or something in a settings file)</p>
<p>You can change the background color by command <code>set object 1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb"green" behind</code> to set the background color to the the color you specified (here is green).</p> <p>To get more knowledge about setting the background in gnuplot, you can visit this <a href="http://gnuplot-surprising.blogspot.com/">blog</a>. There are even provided methods to set a gradient color background and background pictures. Good luck!</p>
What is a good regression testing framework for software applications? <p>Am looking for a regression test framework where I can add tests to.. Tests could be any sort of binaries that poke an application..</p>
<p>This really depends on what you're trying to do, but one of the features of the new <a href="http://search.cpan.org/dist/Test-Harness/" rel="nofollow">Test::Harness</a> (disclaimer: I'm the original author and still a core developer) is that if your tests output TAP (the Test Anything Protocol), you can use Test::Harness to run test suites written in multiple languages. As a result, you don't have to worry about getting "locked in" to a particular language because that's all your testing software supports. In one of my talks on the subject, I even give an example of a test suite written in Perl, C, Ruby, and HTML (yes, HTML -- you'd have to see it).</p>
Are there any noted differences in appearance rendering of html and xhtml in Google Chrome from other browsers? <p>Are there any noted differences in appearance rendering of html and xhtml in Google Chrome from Firefox? From IE? From other browsers/what browser does it render the code the most similar to?</p>
<p>Since it's based on WebKit, its rendering will most closely resemble Safari and Konqueror.</p>
Hidden Markov Models <p>I want to get started on HMM's, but don't know how to go about it. Can people here, give me some basic pointers, where to look?</p> <p>More than just the theory, I like to do a lot of hands-on. So, would prefer resources, where I can write small code snippets to check my learning, rather than just dry text.</p>
<p>Have you tried: Russel and Norvig's Artificial Intelligence: A Modern Approach. </p> <p>I realise that this is heavy on theory, but it also contains useful code samples that can be used to help your learning.</p> <p>You can also check out: <a href="http://www.kanungo.com/software/software.html" rel="nofollow">http://www.kanungo.com/software/software.html</a> for a c-implementation of a HMM</p>
visually customize autocomplete in Wicket <p>How can I visually customize autocomplete fields in Wicket (change colors, fonts, etc.)?</p>
<p>You can use CSS to modify the look of this component. For the Ajax auto-complete component in 1.3 the element you want to override is div.wicket-aa, so for example you might do:</p> <pre><code>div.wicket-aa { background-color:white; border:1px solid #CCCCCC; color:black; } div.wicket-aa ul { list-style-image:none; list-style-position:outside; list-style-type:none; margin:0pt; padding:5px; } div.wicket-aa ul li.selected { background-color:#CCCCCC; } </code></pre>
What do the flags in a Maildir message filename mean? <p>I'm cleaning up some old Maildir folders, and finding messages with names like:</p> <p>1095812260.M625118P61205V0300FF04I002DC537_0.redoak.cise.ufl.edu,S=2576:2,ST</p> <p>They don't show up in my IMAP client, so I presume there's some semaphore indicating the message already got moved somewhere else. Is that the case, and can the files be deleted without remorse?</p>
<p>The 'M' is just part of the unique filename and has nothing to do with the fact that the mail doesn't show up in mail clients. </p> <p>The 'T' at the end of the filename, after the ':' sign, however tells the IMAP server that this message is Trashed.</p> <p>See <a href="http://cr.yp.to/proto/maildir.html" rel="nofollow">http://cr.yp.to/proto/maildir.html</a></p>
What attributes help runtime .Net performance? <p>I am looking for attributes I can use to ensure the best runtime performance for my .Net application by giving hints to the loader, JIT compiler or ngen.</p> <p>For example we have <a href="http://msdn.microsoft.com/en-us/library/k2wxda47.aspx">DebuggableAttribute</a> which should be set to not debug and not disable optimization for optimal performance.</p> <pre><code>[Debuggable(false, false)] </code></pre> <p>Are there any others I should know about?</p>
<p>Ecma-335 specifies some more CompilationRelaxations for relaxed exception handling (so-called e-relaxed calls) in Annex F "Imprecise faults", but they have not been exposed by Microsoft.</p> <p>Specifically CompilationRelaxations.RelaxedArrayExceptions and CompilationRelaxations.RelaxedNullReferenceException are mentioned there.</p> <p>It'd be intersting what happens when you just try some integers in the CompilationRelaxationsAttribute's ctor ;)</p>
In a client-server application: How to send to the DB the user's application password? <p>I have an Java desktop application wich connects directly with the DB (an Oracle). The application has multiple user accounts. What is the correct method to send the user's password (not DB password) over the network? I don't want to send it in plain text</p>
<p>You could connect over a secure socket connection, or hash the password locally before sending it to the database (or better, both) - Ideally, the only time the password should exist in plain text form is prior to hashing. If you can do all of that on the client side, more the better.</p>
Is it worth encrypting email addresses in the database? <p>I'm already using <a href="http://www.matasano.com/log/958/enough-with-the-rainbow-tables-what-you-need-to-know-about-secure-password-schemes/">salted hashing</a> to store passwords in my database, which means that I should be immune to <a href="http://en.wikipedia.org/wiki/Rainbow_table">rainbow table</a> attacks.</p> <p>I had a thought, though: what if someone does get hold of my database? It contains the users' email addresses. I can't really hash these, because I'll be using them to send notification emails, etc..</p> <p>Should I encrypt them?</p>
<p>Bruce Schneier has a good response to this kind of problem.</p> <blockquote> <p>Cryptography is not the solution to your security problems. It might be part of the solution, or it might be part of the problem. In many situations, cryptography starts out by making the problem worse, and it isn't at all clear that using cryptography is an improvement.</p> </blockquote> <p>Essentially encrypting your emails in the database 'just in case' is not really making the database more secure. Where are the keys stored for the database? What file permissions are used for these keys? Is the database accesable publically? Why? What kind of account restrictions are in place for these accounts? Where is the machine stored, who has physical access to this box? What about remote login/ssh access etc. etc. etc.</p> <p>So I guess you can encrypt the emails if you want, but if that is the extent of the security of the system then it really isn't doing much, and would actually make the job of maintaining the database harder.</p> <p>Of course this could be part of an extensive security policy for your system - if so then great!</p> <p>I'm not saying that it is a bad idea - But why have a lock on the door from Deadlocks'R'us which cost $5000 when they can cut through the plywood around the door? Or come in through the window which you left open? Or even worse they find the key which was left under the doormat. Security of a system is only as good as the weakest link. If they have root access then they can pretty much do what they want.</p> <p><a href="http://stackoverflow.com/questions/70450/is-it-worth-encrypting-email-addresses-in-the-database#70484">Steve Morgan</a> makes a good point that even if they cannot understand the email addresses, they can still do a lot of harm (which could be mitigated if they only had SELECT access)</p> <p>Its also important to know what your reasons are for storing the email address at all. I might have gone a bit overboard with <a href="http://stackoverflow.com/questions/767276/what-is-the-best-and-safest-way-to-store-user-email-addresses-in-the-database">this answer</a>, but my point is do you really need to store an email address for an account? The most secure data is data that doesn't exist.</p>
Can we achieve 100% decoupling? <p>Can we achieve 100% decoupling between components of a system or different systems that communicate with each other? I don't think its possible. If two systems communicate with each other then there should be some degree of coupling between them. Am I right?</p>
<p>If components are 100% decoupled, it means that they don't communicate with each other.</p> <p>Actually there are <a href="http://en.wikipedia.org/wiki/Coupling_%28computer_science%29" rel="nofollow">different types of coupling</a>. But the general idea is that objects are not coupled if they don't depend on each other.</p>
How do I compare phrases for similarity? <p>When entering a question, stackoverflow presents you with a list of questions that it thinks likely to cover the same topic. I have seen similar features on other sites or in other programs, too (Help file systems, for example), but I've never programmed something like this myself. Now I'm curious to know what sort of algorithm one would use for that.</p> <p>The first approach that comes to my mind is splitting the phrase into words and look for phrases containing these words. Before you do that, you probably want to throw away insignificant words (like 'the', 'a', 'does' etc), and then you will want to rank the results.</p> <p>Hey, wait - let's do that for web pages, and then we can have a ... watchamacallit ... - a "search engine", and then we can sell ads, and then ...</p> <p>No, seriously, what are the common ways to solve this problem?</p>
<p>One approach is the so called bag-of-words model.</p> <p>As you guessed, first you count how many times words appear in the text (usually called document in the NLP-lingo). Then you throw out the so called stop words, such as "the", "a", "or" and so on.</p> <p>You're left with words and word counts. Do this for a while and you get a comprehensive set of words that appear in your documents. You can then create an index for these words: "aardvark" is 1, "apple" is 2, ..., "z-index" is 70092. </p> <p>Now you can take your word bags and turn them into vectors. For example, if your document contains two references for aardvarks and nothing else, it would look like this:</p> <pre><code>[2 0 0 ... 70k zeroes ... 0]. </code></pre> <p>After this you can count the "angle" between the two vectors with <a href="http://en.wikipedia.org/wiki/Dot_product">a dot product</a>. The smaller the angle, the closer the documents are.</p> <p>This is a simple version and there other more advanced techniques. May the <a href="http://en.wikipedia.org/wiki/Document_classification">Wikipedia be with you</a>.</p>
Logging image downloads <p>I'm trying to find a way of finding out who is downloading what image from an image gallery. Users can download using a button beside the thumbnail or right click and use the "save link as" Is it possible to relate a user session or ID to a "save link as" action from all browsers using either PHP or JavaScript.</p>
<p>Yes, my preferred way of doing this would be via PHP. You'd have to set up a script which would load up the file and send it to the user browser. This script would also be able to log the download somewhere (e.g. your database).</p> <p>For example - in very rough pseudo-code:</p> <p>download.php</p> <pre><code>$file = $_GET['file']; updateFileCount($file); header('Content-Type: image/jpeg'); sendFile($file); </code></pre> <p>Then, you just have your download link point to download.php instead of the actual file. (Note that updateFileCount and sendFile are functions that you would have to provide, of course - <a href="http://elouai.com/force-download.php" rel="nofollow">this script</a> is an example of a download script which you could use)</p> <p>Note: I highly recommend avoiding the use of $_GET['file'] to get the whole filename - malicious users could use it to retrieve sensitive files from your web server. But the safe use of PHP downloads is a topic for another question.</p>
What is this strange C code format? <p>What advantage, if any, is provided by formatting C code as follows:</p> <pre><code>while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3); } if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1); } unlock_file(lockdir); </code></pre> <p>versus something more typical such as</p> <pre><code>while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3); } if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1); } unlock_file(lockdir); </code></pre> <p>I just find the top version difficult to read and to get the indenting level correct for statements outside of a long block, especially for longs blocks containing several nested blocks.</p> <p>Only advantage I can see is just to be different and leave your fingerprints on code that you've written.</p> <p>I notice vim formatting would have to be hand-rolled to handle the top case.</p>
<p>The top example is know as "Whitesmiths style". <a href="http://en.wikipedia.org/wiki/Indent_style">Wikipedia's entry on Indent Styles</a> explains several styles along with their advantages and disadvantages.</p>
deleting a buffer through a different type of pointer? <p>Say I have the following C++:</p> <pre><code>char *p = new char[cb]; SOME_STRUCT *pSS = (SOME_STRUCT *) p; delete pSS; </code></pre> <p>Is this safe according to the C++ standard? Do I need to cast back to a <code>char*</code> and then use <code>delete[]</code>? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?</p>
<p>It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite:</p> <p>[16.13] Can I drop the <code>[]</code> when deleting array of some built-in type (<code>char</code>, <code>int</code>, etc.)?</p> <p><a href="https://isocpp.org/wiki/faq/freestore-mgmt#delete-array" rel="nofollow">http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13</a></p>
Extracting text from a PDF using JBoss Richfaces <p>I am trying to write a web-app to manage references for my PhD thesis.</p> <p>I used to manage this information inside a personal Confluence (fantastic tool! - <a href="http://www.atlassian.com/software/confluence/" rel="nofollow">http://www.atlassian.com/software/confluence/</a>) instance however I'm fed-up with the opening of PDF's and cutting and pasting values into fields that I wish to record.</p> <p>I have exposed a webservice that will return me images based on a PDF filename and a page number. The same webservice also exposes a method that will return the text inside of a provided rectangle (top left x-y coord, bottom right x-y coord).</p> <p>I would like to be able to drag a rectangle over part of the PDF image and then call the webservice to give me the text (which I will then store on a EntityBean). I am looking at using the JBoss application stack (Application Server, Hibernate, Seam and Richfaces). Does anybody know how I could go about achieving this? I have seen the ability to draw custom images in other RIA toolkits (e.g. dojo), but I can't see a way of doing this inside of Richfaces.</p> <p>Hopefully somebody out there could prove me wrong, or provide some idea about what I can do (as I am not a web developer - I'm mainly building this tool because the RIA frameworks available now have got me interested!)</p> <p>I already have the code to extract the text, my problem is purely how can I get the user to draw a "selection rectangle" inside the web browser over the top of the image?</p> <p>Many Thanks,</p> <p>Aidos</p>
<p>Try using the <a href="http://livedemo.exadel.com/richfaces-demo/richfaces/paint2D.jsf?c=paint2d&amp;tab=usage" rel="nofollow">RichFaces Paint 2D</a> tag</p> <p>It exposes the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics2D.html" rel="nofollow">Graphics2D</a> package to the user interface.</p> <p>Track user drag events on the image using javascript, then post the co-ordrdinates to the backing bean to re-render the image with a drawn on selection box.</p>
Help in creating Zip files from .Net and reading them from Java <p>I'm trying to create a Zip file from .Net that can be read from Java code.</p> <p>I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncompress it using the Java.Utils.Zip class in Java.</p> <p>Problem seems to be in the wrong header written by SharpZipLib, I've also posted a question on the SharpDevelop forum but with no results (see <a href="http://community.sharpdevelop.net/forums/t/8272.aspx" rel="nofollow">http://community.sharpdevelop.net/forums/t/8272.aspx</a> for info) but with no result.</p> <p>Has someone a code sample of compressing a Zip file with .Net and de-compressing it with the Java.Utils.Zip class?</p> <p>Regards Massimo</p>
<p>I have used <a href="http://www.codeplex.com/DotNetZip" rel="nofollow">DotNetZip library</a> and it seems to work properly. Typical code:</p> <pre><code>using (ZipFile zipFile = new ZipFile()) { zipFile.AddDirectory(sourceFolderPath); zipFile.Save(archiveFolderName); } </code></pre>
Can I add maven repositories in the command line? <p>I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like:</p> <pre><code>mvn install -Dmaven.repository=http://example.com/maven2 </code></pre> <p>The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle.</p>
<p>You can do this but you're probably better off doing it in the POM as others have said.</p> <p>On the command line you can specify a property for the local repository, and another repository for the remote repositories. The remote repository will have all default settings though</p> <p>The example below specifies two remote repositories and a custom local repository.</p> <pre><code>mvn package -Dmaven.repo.remote=http://www.ibiblio.org/maven/,http://myrepo -Dmaven.repo.local="c:\test\repo" </code></pre>
Tool to test Website accessibility <p>Can you suggest a tool for testing accessibility and section 508/ADA compliance of a Website with MS Share Point and .Net 2.0 as the underlying platform?</p>
<p>In my experience, testing Sharepoint for accessibility is not worth it. Even if you've used the Accessibility Toolkit for Sharepoint (AKS) with Sharepoint 2007, the end result is far from accessible.</p> <p>The trouble is that accessibility was not, and still is not a big consideration for MS when they made Sharepoint. Everything depends on table layout, and screenreaders are given a nightmare to deal with.</p> <p>There are a few online tools - some will help validate your output, others pretend to test you for accessibility (<a href="http://www.tawdis.net" rel="nofollow">TAW</a>). </p> <p>The problem is that many of the guidelines under WCAG are just too arbitrary, and will never be testable by an automated tool. This may change with WCAG 2.</p> <p>Anyway, wish you the best trying to make Sharepoint accessible.</p> <p><strong>EDIT:</strong> As a side not, I can highly recommend the following tools/resources for anyone interested in accessible development:</p> <ul> <li>Chris Pederick's <a href="http://chrispederick.com/work/web-developer/" rel="nofollow">Web Accessibility Toolbar</a></li> <li><a href="http://www.accessit.nda.ie/" rel="nofollow">NDA's Web Accessibility IT Guidelines</a></li> </ul>
How can I find last row that contains data in the Excel sheet with a macro? <p>How can I find the last row that contains data in a specific column and on a specific sheet?</p>
<p>How about:</p> <pre><code> Sub GetLastRow(strSheet, strColum) Dim MyRange As Range Dim lngLastRow As Long Set MyRange = Worksheets(strSheet).Range(strColum &amp; "1") lngLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row End Sub </code></pre> <p>Re Comment</p> <p>This</p> <pre><code> Cells.Find("*",SearchOrder:=xlByRows,SearchDirection:=xlPrevious).Row </code></pre> <p>Will return the row number of the last cell even when only a single cell in the last row has data. </p>
Set a UserControl Property to Not Show Up in VS Properties Window <p>I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up?</p> <pre><code>class MyControl : System.Web.UI.UserControl { // Attribute to prevent property from showing in VS Property Window? public bool SampleProperty { get; set; } // other stuff } </code></pre>
<p>Use the following attribute ...</p> <pre><code>using System.ComponentModel; [Browsable(false)] public bool SampleProperty { get; set; } </code></pre> <p>In VB.net, this <a href="http://stackoverflow.com/questions/71440/set-a-usercontrol-property-to-not-show-up-in-vs-properties-window#71481">will be</a>:</p> <pre><code>&lt;System.ComponentModel.Browsable(False)&gt; </code></pre>
How to display the progress of a server script in jQuery? <p>With this code I can show an animated gif while the server script is running:</p> <pre><code>function calculateTotals() { $('#results').load('getResults.php', null, showStatusFinished); showLoadStatus(); } function showLoadStatus() { $('#status').html(''); } function showStatusFinished() { $('#status').html('Finished.'); } </code></pre> <p>However, I would like to display a status of how far along the script is, e.g. "Processing line 342 of 20000..." and have it count up until it is finished.</p> <p>How can I do that? I can make a server-script which constantly contains the updated information but where do I put the command to read this, say, every second?</p>
<p>After reading your comments to Andrew's answer.</p> <p>You would read the status like this:</p> <pre><code>function getStatus() { $.getJSON("/status.php",{"session":0, "requestID":12345}, function(data) { //data is the returned JSON object from the server {name:"value"} setStatus(data.status); window.setTimeout("getStatus()",intervalInMS) }); } </code></pre> <p>Using this method you can open several simultaneous XHR request on the server.</p> <p>all your status.php as to output is :</p> <pre><code>{"status":"We are done row 1040/45983459"} </code></pre> <p>You can however output as many information you want in the response and to process it accordingly (feeding a progress bar for example or performing an animation..)</p> <p>For more information on $.getJSON see <a href="http://docs.jquery.com/Ajax/jQuery.getJSON" rel="nofollow">http://docs.jquery.com/Ajax/jQuery.getJSON</a></p>
How do I make the lights stay fixed in the world with Direct3D <p>I've been using OpenGL for years, but after trying to use D3D for the first time, I wasted a significant amount of time trying figure out how to make my scene lights stay fixed in the world rather than fixed on my objects.</p> <p>In OpenGL light positions get transformed just like everything else with the MODELVIEW matrix, so to get lights fixed in space, you set up your MODELVIEW the way you want for the lights, and call glLightPosition then set it up for your geometry and make geometry calls. In D3D that doesn't help.</p> <p>(Comment -- I eventually figured out the answer to this one, but I couldn't find anything helpful on the web or in the MSDN. It would have saved me a few hours of head scratching if I could have found this answer then.)</p>
<p>The answer I discovered eventually was that while OpenGL only has its one amalgamated <code>MODELVIEW</code> matrix, in D3D the "world" and "view" transforms are kept separate, and placing lights seems to be the major reason for this. So the answer is you use <code>D3DTS_VIEW</code> to set up matrices that should apply to your lights, and <code>D3DTS_WORLD</code> to set up matrices that apply to the placement of your geometry in the world.</p> <p>So actually the D3D system kinda makes more sense than the OpenGL way. It allows you to specify your light positions whenever and wherever the heck you feel like it once and for all, without having to constantly reposition them so that they get transformed by your current "view" transform. OpenGL has to work that way because it simply doesn't know what you think your "view" is vs your "model". It's all just a modelview to GL.</p> <p>(Comment - apologies if I'm not supposed to answer my own questions here, but this was a real question that I had a few weeks ago and thought it was worth posting here to help others making the shift from OpenGL to D3D. Basic overviews of the D3D lighting and rendering pipeline seem hard to come by.)</p>
Java Applet crashes .NET Webbrowsercontrol <p>in our application we have a Java applet running inside a .NET browser control. It is a know issue from Sun that running an applet this way may crash the control.</p> <p>Has anyone come across the same problem and solved it?</p> <p>Atm we are running the applet in a Webbrowser but we need to run it in a browser control.</p> <p>Thx for any help.</p>
<p>After some time the problem solved itself. It was indeed a bug in the java runtime which is now fixed by sun. Just make sure your JRE is > 1.6.10.</p>
Determine the size of a pipe without calling read() <p>I need a function called SizeOfPipe() which should return the size of a pipe- I only want to know how much data is in the pipe and not actually read data off the pipe itself. </p> <p>I thought the following code would work</p> <pre><code>fseek (pPipe, 0 , SEEK_END); *pBytes = ftell (pPipe); rewind (pPipe); </code></pre> <p>but fseek dosent work on file descriptors. Another option would be to read the pipe then write the data back but would like to avoid this if possibe, any suggestions ?</p>
<p>Depending on your unix implementation ioctl/FIONREAD might do the trick</p> <pre> err = ioctl(pipedesc, FIONREAD, &bytesAvailable); </pre> <p>Unless this returns the error code for "invalid argument" (or any other error) bytesAvailable contains the amount of data available for unblocking read operations at that time.</p>
How to implement a Digg-like algorithm? <p>How to implement a website with a recommendation system similar to stackoverflow/digg/reddit? I.e., users submit content and the website needs to calculate some sort of "hotness" according to how popular the item is. The flow is as follows:</p> <ul> <li>Users submit content</li> <li>Other users view and vote on the content (assume 90% of the users only views content and 10% actively votes up or down on content)</li> <li>New content is continuously submitted</li> </ul> <p>How do I implement an algorithm that calculates the "hotness" of a submitted item, preferably in real-time? Are there any best-practices or design patterns?</p> <p>I would assume that the algorithm takes the following into consideration:</p> <ul> <li>When an item was submitted</li> <li>When each vote was cast</li> <li>When the item was viewed</li> </ul> <p>E.g. an item that gets a constant trickle of votes would stay somewhat "hot" constantly while an item that receives a burst of votes when it is first submitted will jump to the top of the "hotness"-list but then fall down as the votes stop coming in.</p> <p>(I am using a MySQL+PHP but I am interested in general design patterns).</p>
<p>You could use something similar to the <a href="http://redflavor.com/reddit.cf.algorithm.png">Reddit algorithm</a> - the basic principle of which is you compute a value for a post based on the time it was posted and the score. What's neat about the Reddit algorithm is that you only need recompute the value when the score of a post changes. When you want to display your front page, you just get the top n posts from your database based on that score. As time goes on the scores will naturally increase, so you don't have to do any special processing to remove items from the front page.</p>
How do you efficiently copy BSTR to wchar_t[]? <p>I have a BSTR object that I would like to convert to copy to a wchar__t object. The tricky thing is the length of the BSTR object could be anywhere from a few kilobytes to a few hundred kilobytes. Is there an efficient way of copying the data across? I know I could just declare a wchar_t array and alway allocate the maximum possible data it would ever need to hold. However, this would mean allocating hundreds of kilobytes of data for something that potentially might only require a few kilobytes. Any suggestions?</p>
<p>First, you might not actually have to do anything at all, if all you need to do is read the contents. A BSTR type is a pointer to a null-terminated wchar_t array already. In fact, if you check the headers, you will find that BSTR is essentially defined as:</p> <pre><code>typedef BSTR wchar_t*; </code></pre> <p>So, the compiler can't distinguish between them, even though they have different semantics.</p> <p>There is are two important caveat.</p> <ol> <li><p><s>BSTRs are supposed to be immutable. You should never change the contents of a BSTR after it has been initialized. If you "change it", you have to create a new one assign the new pointer and release the old one (if you own it).</s><br /> <i>[<strong>UPDATE</strong>: this is not true; sorry! You can modify BSTRs in place; I very rarely have had the need.]</i></p></li> <li><p>BSTRs are allowed to contain embedded null characters, whereas traditional C/C++ strings are not.</p></li> </ol> <p>If you have a fair amount of control of the source of the BSTR, and can guarantee that the BSTR does not have embedded NULLs, you can read from the BSTR as if it was a wchar_t and use conventional string methods (wcscpy, etc) to access it. If not, your life gets harder. You will have to always manipulate your data as either more BSTRs, or as a dynamically-allocated array of wchar_t. Most string-related functions will not work correctly.</p> <p>Let's assume you control your data, or don't worry about NULLs. Let's assume also that you really need to make a copy and can't just read the existing BSTR directly. In that case, you can do something like this:</p> <pre><code>UINT length = SysStringLen(myBstr); // Ask COM for the size of the BSTR wchar_t *myString = new wchar_t[lenght+1]; // Note: SysStringLen doesn't // include the space needed for the NULL wcscpy(myString, myBstr); // Or your favorite safer string function // ... delete myString; // Done </code></pre> <p>If you are using class wrappers for your BSTR, the wrapper should have a way to call SysStringLen() for you. For example:</p> <pre><code>CComBString use .Length(); _bstr_t use .length(); </code></pre> <p><strong>UPDATE</strong>: This is a good article on the subject by someone far more knowledgeable than me:<br /> <a href="http://blogs.msdn.com/ericlippert/archive/2003/09/12/52976.aspx">"Eric [Lippert]'s Complete Guide To BSTR Semantics"</a> <strong>UPDATE</strong>: Replaced strcpy() with wcscpy() in example</p>
C++ overload resolution <p>Given the following example, why do I have to explicitly use the statement <code>b-&gt;A::DoSomething()</code> rather than just <code>b-&gt;DoSomething()</code>?</p> <p>Shouldn't the compiler's overload resolution figure out which method I'm talking about?</p> <p>I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)</p> <pre><code>class A { public: int DoSomething() {return 0;}; }; class B : public A { public: int DoSomething(int x) {return 1;}; }; int main() { B* b = new B(); b-&gt;A::DoSomething(); //Why this? //b-&gt;DoSomething(); //Why not this? (Gives compiler error.) delete b; return 0; } </code></pre>
<p>The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done <em>afterwards</em>. In your case this means that the compiler sees <code>B::DoSomething</code>. It then tries to match the argument list, which fails.</p> <p>One solution would be to pull down the overload from <code>A</code> into <code>B</code>'s scope:</p> <pre><code>class B : public A { public: using A::DoSomething; // … } </code></pre>
Problem with SET FMTONLY ON <p>I'm executing stored procedures using SET FMTONLY ON, in order to emulate what our code generator does. However, it seems that the results are cached when executed like this, as I'm still getting a <em>Conversion failed</em> error from a proc that I have just dropped! This happens even when I execute the proc without SET FMTONLY ON.</p> <p>Can anyone please tell me what's going on here?</p>
<p>Some statements will still be executed, even with <strong><code>SET FMTONLY ON</code></strong>. You "Conversion failed" error could be from something as simple as a <code>set variable</code> statement in the stored proc. For example, this returns the metadata for the first query, but throws an exception when it runs the last statement:</p> <pre><code>SET FMTONLY on select 1 as a declare @a int set @a = 'a' </code></pre> <p>As for running a dropped procedure, that's a new one to me. SQL Server uses the system tables to determine the object to execute, so it doesn't matter if the execution plan is cached for that object. If you drop it, it is deleted from the system tables, and should never be executable. Could you please query sysobjects (or sys.objects) just before you execute the procedure? I expect you'll find that you haven't dropped it.</p>
How to implement "DOM Ready" event in a GreaseMonkey script? <p>I'm trying to modify my GreaseMonkey script from firing on window.onload to window.DOMContentLoaded, but this event never fires.</p> <p>I'm using FireFox 2.0.0.16 / GreaseMonkey 0.8.20080609</p> <p><a href="http://stackoverflow.com/questions/59205/enhancing-stackoverflow-user-experience">This</a> is the full script that I'm trying to modify, changing:</p> <pre><code>window.addEventListener ("load", doStuff, false); </code></pre> <p>to</p> <pre><code>window.addEventListener ("DOMContentLoaded", doStuff, false); </code></pre>
<p>So I googled <a href="http://www.google.com/search?q=greasemonkey%20dom%20ready">greasemonkey dom ready</a> and the <a href="http://www.sitepoint.com/article/beat-website-greasemonkey/">first result</a> seemed to say that the greasemonkey script is actually running at "DOM ready" so you just need to remove the onload call and run the script straight away.</p> <p>I removed the <em><code>window.addEventListener ("load", function() {</code></em> and <em><code>}, false);</code></em> wrapping and it worked perfectly. It's <strong>much</strong> more responsive this way, the page appears straight away with your script applied to it and all the unseen questions highlighted, no flicker at all. And there was much rejoicing.... yea.</p>
Mocking constructors in Ruby <p>I'm a Java-developer toying with Ruby, and loving it. I have understood that because of Ruby's metaprogramming facilities my unit-tests become much cleaner and I don't need nasty mocking frameworks. I have a class which needs the <code>File</code> class's services and in my test I don't want to touch my real filesystem. In Java I would use some virtual file system for easier "seams" to pass fake-objects in but in Ruby that's obviously overkill. What I come up seems already really nice compared to the Java-world. In my class under test I have an optional constructor parameter: </p> <pre><code>def initialize(file_class=File) </code></pre> <p>When I need to open files within my class, I can then do this:</p> <pre><code>@file_class.open(filename) </code></pre> <p>And the call goes to either the real File-class, or in case of my unit-test, it goes to a fake-class which doesn't touch the filesystem. I know there must be a better way to do this with metaprogramming?</p>
<p>Mocha (<a href="http://mocha.rubyforge.org/">http://mocha.rubyforge.org/</a>) is a very good mocking library for ruby. Depending on what you're actually wanting to test (i.e. if you want to just fake out the File.new call to avoid the file system dependency or if you want to verify that the correct arguments are passed into File.new) you could do something like this:</p> <pre> <code> require 'mocha' mock_file_obj = mock("My Mock File") do stubs(:some_instance_method).returns("foo") end File.stubs(:new).with(is_a(String)).returns(mock_file_obj) </code> </pre>
How to Call BizTalk Orchestration Dynamically <p>How can I call a BizTalk Orchestration dynamically knowing the Orchestration name? The call Orchestration shapes need to know the name and parameters of Orchestrations at design time. I've tried using 'call' XLang keyword but it also required Orchestration name as Design Time like in expression shape, we can write as </p> <p>call BizTalkApplication1.Orchestration1(param1,param2);</p> <p>I'm looking for some way to specify calling orchestration name, coming from the incoming message or from SSO config store.</p> <p>EDIT: I'musing BizTalk 2006 R1 (ESB Guidance is for R2 and I didn't get how it could solve my problem) </p>
<p>The way I've accomplished something similar in the past is by using direct binding ports in the orchestrations and letting the MsgBox do the dirty work for me. Basically, it goes something like this:</p> <ol> <li>Make the callable orchestrations use a direct-bound port attached to your activating receive shape.</li> <li>Set up a filter expression on your activating receive shape with a custom context-based property and set it equal to a value that uniquely identifies the orchestration (such as the orchestration name or whatever)</li> <li>In the calling orchestration, create the message you'll want to use to fire the new orchestration. In that message, set your custom context property to the value that matches the filter used in the specific orchestration you want to fire.</li> <li>Send the message through a direct-bound send port so that it gets sent to the MsgBox directly and the Pub/Sub mechanisms in BizTalk will take care of the rest.</li> </ol> <p>One thing to watch out in step 4: To have this work correctly, you will need to create a new Correlation Set type that includes your custom context property, and then make sure that the direct-bound send port "follows" the correlation set on the send. Otherwise, the custom property will only be written (and not promoted) to the msg context and the routing will fail.</p> <p>Hope this helps!</p>
How to use the "is" operator in System.Type variables? <p>here is what a I'm doing: </p> <pre><code>object ReturnMatch(System.Type type) { foreach(object obj in myObjects) { if (obj == type) { return obj; } } } </code></pre> <p>However, if obj is a subclass of <code>type</code>, it will not match. But I would like the function to return the same way as if I was using the operator <code>is</code>.</p> <p>I tried the following, but it won't compile:</p> <pre><code>if (obj is type) // won't compile in C# 2.0 </code></pre> <p>The best solution I came up with was:</p> <pre><code>if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type)) </code></pre> <p>Isn't there a way to use operator <code>is</code> to make the code cleaner?</p>
<p>I've used the IsAssignableFrom method when faced with this problem.</p> <pre><code>Type theTypeWeWant; // From argument or whatever foreach (object o in myCollection) { if (theTypeWeWant.IsAssignableFrom(o.GetType)) return o; } </code></pre> <p>Another approach that may or may not work with your problem is to use a generic method:</p> <pre><code>private T FindObjectOfType&lt;T&gt;() where T: class { foreach(object o in myCollection) { if (o is T) return (T) o; } return null; } </code></pre> <p>(Code written from memory and is not tested)</p>
Speech Recognition for Searching Files <p>Here is the problem I have:</p> <p>I have a lot (tens of thousands) of mp3 files that my users would like to be able to search. Is there is software out there that you've used or heard good things about that would allow me to index that content and put it in a database so I can search on it later?</p>
<p>There's an open source library <a href="http://cmusphinx.sourceforge.net/html/cmusphinx.php" rel="nofollow">Sphinx</a></p>
Storing content in multiple languages? E.g. English, French, German <p>How should I store (and present) the text on a website intended for worldwide use, with several languages? The content is mostly in the form of 500+ word articles, although I will need to translate tiny snippets of text on each page too (such as "print this article" or "back to menu").</p> <p>I know there are several CMS packages that handle multiple languages, but I have to integrate with our existing ASP systems too, so I am ignoring such solutions.</p> <p>One concern I have is that Google should be able to find the pages, even for foreign users. I am less concerned about issues with processing dates and currencies.</p> <p>I worry that, left to my own devices, I will invent a way of doing this which work, but eventually lead to disaster! I want to know what professional solutions you have actually used on real projects, not untried ideas! Thanks very much.</p> <hr> <p>I looked at RESX files, but felt they were unsuitable for all but the most trivial translation solutions (I will elaborate if anyone wants to know).</p> <p>Google will help me with translating the text, but not storing/presenting it.</p> <p>Has anyone worked on a multi-language project that relied on their own code for presentation?</p> <hr> <p>Any thoughts on serving up content in the following ways, and which is best?</p> <ul> <li><a href="http://www.website.com/text/view.asp?id=12345&amp;lang=fr" rel="nofollow">http://www.website.com/text/view.asp?id=12345&amp;lang=fr</a></li> <li><a href="http://www.website.com/text/12345/bonjour_mes_amis.htm" rel="nofollow">http://www.website.com/text/12345/bonjour_mes_amis.htm</a></li> <li><a href="http://fr.website.com/text/12345" rel="nofollow">http://fr.website.com/text/12345</a></li> </ul> <p>(these are not real URLs, i was just showing examples)</p>
<p>Firstly put all code for all languages under one domain - it will help your google-rank.</p> <p>We have a fully multi-lingual system, with localisations stored in a database but cached with the web application.</p> <p>Wherever we want a localisation to appear we use:</p> <pre><code>&lt;%$ Resources: LanguageProvider, Path/To/Localisation %&gt; </code></pre> <p>Then in our web.config:</p> <pre><code>&lt;globalization resourceProviderFactoryType="FactoryClassName, AssemblyName"/&gt; </code></pre> <p><code>FactoryClassName</code> then implements <code>ResourceProviderFactory</code> to provide the actual dynamic functionality. Localisations are stored in the DB with a string key "Path/To/Localisation"</p> <p>It is important to cache the localised values - you don't want to have lots of DB lookups on each page, and we cache thousands of localised strings with no performance issues.</p> <p>Use the user's current browser localisation to choose what language to serve up.</p>
Is a software token a valid second factor in multi-factor security? <p>We are changing our remote log-in security process at my workplace, and we are concerned that the new system does not use <a href="http://en.wikipedia.org/wiki/Two-factor_authentication" rel="nofollow">multi-factor authentication</a> as the old one did. (We had been using RSA key-fobs, but they are being replaced due to cost.) The new system is an anti-phishing image system which has been misunderstood to be a two-factor authentication system. We are now exploring ways to continue providing multi-factor security without issuing hardware devices to the users.</p> <p>Is it possible to write a software-based token system to be installed on the user's PCs that would constitute a true second factor in a multi-factor authentication system? Would this be considered "something the user has", or would it simply be another form of "something the user knows"?</p> <p>Edit: <em>phreakre</em> makes a good point about cookies. For the sake of this question, assume that cookies have been ruled out as they are not secure enough.</p>
<p>I would say "no". I don't think you can really get the "something you have" part of multi-factor authentication without issuing something the end user can carry with them. If you "have" something, it implies it can be lost - not many users lose their entire desktop machines. The security of "something you have", after all, comes from the following:</p> <ul> <li>you would notice when you don't have it - a clear indication security has been compromised</li> <li>only 1 person can have it. So if you do, someone else doesn't</li> </ul> <p>Software tokens do not offer the same guarantees, and I would not in good conscience class it as something the user "has". </p>
Making a C#/Winform application cross-platform - should I use AIR, Mono, or something else? <p>I have an app that I've written in C#/WinForms (<a href="http://www.thekbase.com" rel="nofollow" title="TheKBase">my little app</a>). To make it cross-platform, I'm thinking of redoing it in Adobe AIR. Are there any arguments in favor of WinForms as a cross-platform app? Is there a cross-platform future for Winforms (e.g., Mono, etc.)? Suggestions for cross-platform UI development?</p> <p>By cross-platform I mean, currently, Mac OSX, Windows and Linux.</p> <p>This question was <a href="http://stackoverflow.com/questions/116468/winforms-for-mono-on-mac-linux-and-pc-redux">asked again and answered with better success</a>.</p>
<p>As far as my experience in Flex/AIR/Flash actionscripting goes, Adobe AIR development environment and coding/debugging toolsets are far inferior to the Visual Studio and .NET SDK as of the moment. The UI toolsets are superior though.</p> <p>But as <em>you already have a working C# code</em>, porting it to ActionScript might requires a redesign due to ActionScript having a different way of thinking/programming, they use different primitive data types, for example, they use just a <code>Number</code> instead of <code>int float double</code> etc. and the debugging tools are quiet lacking compared to VS IMO.</p> <p>And I heard that <a href="http://www.mono-project.com/GtkSharp" rel="nofollow">Mono's GtkSharp</a> is quiet a decent platform.</p> <p>But if you don't mind the coding/debugging tooling problems, then AIR is a great platform. I like how Adobe integrates the Flash experience into it e.g. you can start an installation of AIR application via a button click in a flash movieclip, that kind of integration.</p>
Modal dialogs in IE gets hidden behind IE if user clicks on IE pane <p>I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds <strong>all</strong> IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they <em>see</em> dialog on top of IE but it looks like it has hanged since it is not refreshe). </p> <p>So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice. </p> <p>Here's the code:</p> <pre><code> PassDialog dialog = new PassDialog(parent); /* do some non gui related initialization */ dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setAlwaysOnTop(true); dialog.setVisible(true); </code></pre> <p>Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was: </p> <pre><code>parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet); </code></pre>
<p>Make a background Thread that calls toFront on the Dialog every 2 seconds. Code that we use (I hope I got everything):</p> <pre><code>class TestClass { protected void toFrontTimer(JFrame frame) { try { bringToFrontTimer = new java.util.Timer(); bringToFrontTask = new BringToFrontTask(frame); bringToFrontTimer.schedule( bringToFrontTask, 300, 300); } catch (Throwable t) { t.printStackTrace(); } } class BringToFrontTask extends TimerTask { private Frame frame; public BringToFrontTask(Frame frame) { this.frame = frame; } public void run() { if(count &lt; 2) { frame.toFront(); } else { cancel(); } count ++; } private int count = 0; } public void cleanup() { if(bringToFrontTask != null) { bringToFrontTask.cancel(); bringToFrontTask = null; } if(bringToFrontTimer != null) { bringToFrontTimer = null; } } java.util.Timer bringToFrontTimer = null; java.util.TimerTask bringToFrontTask = null; } </code></pre>
How can I show scrollbars on a System.Windows.Forms.TextBox only when the text doesn't fit? <p>For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.</p> <p>This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?)</p> <p><hr/></p> <p>Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.</p> <p><hr/></p> <p>@<a href="#89428">nobugz</a>, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.</p> <p><hr/></p> <p>@André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness.</p>
<p>I came across this question when I wanted to solve the same problem. </p> <p>The easiest way to do it is to change to System.Windows.Forms.RichTextBox. The ScrollBars property in this case can be left to the default value of RichTextBoxScrollBars.Both, which indicates "Display both a horizontal and a vertical scroll bar when needed." It would be nice if this functionality were provided on TextBox.</p>
Firefox, saved passwords, and the change password dialogue <p>If a user saves the password on the login form, ff3 is putting the saved password in the change password dialoge on the profile page, even though its <strong>not the same input name</strong> as the login. how can I prevent this?</p>
<p>Try using autocomplete="off" as an attribute of the text box. I've used it in the past to stop credit card details being stored by the browser but i dont know if it works with passwords. e.g. <code>print("&lt;input type="text" name="cc" autocomplete="off" /&gt;");</code></p>
What is your choice for a Time Managment Solution? <p>I've come across a few different applications that monitor my usage while on the computer, but what have you used, and like? whether it be writing down your activities in a composition notbook or install an app that reports silently to a server? what do you like?</p>
<p>For explicit time tracking for projects I use <a href="http://slimtimer.com" rel="nofollow">SlimTimer</a>. I also run <a href="http://www.rescuetime.com/" rel="nofollow">RescueTime</a> to track my time implicitly, but I end up not looking at that data very often.</p>
How to set the header sort glyph in a .NET ListView? <p>How do I set the column which has the header sort glyph, and its direction, in a .NET 2.0 WinForms ListView?</p> <h2>Bump</h2> <p>The listview is .net is not a managed control, it is a very thin wrapper around the Win32 ListView common control. It's not even a very good wrapper - it doesn't expose all the features of the real listview.</p> <p>The Win32 listview common control supports drawing itself with themes. One of the themed elements is the header sort arrow. Windows Explorer's listview common control knows how to draw one of its columns with that theme element.</p> <ul> <li>does the Win32 listview support specifying which column has what sort order? </li> <li>does the Win32 header control that the listview internally uses support specifying which column has what sort order? </li> <li>does the win32 header control support custom drawing, so I can draw the header sort glyph myself?</li> <li>does the win32 listview control support custom header drawing, so I can draw the header sort glyph myself?</li> <li>does the .NET ListView control support custom header drawing, so I can draw the header sort glyph myself?</li> </ul>
<p>In case someone needs a quick solution (it draws up/down arrow at the beginning of column header text):</p> <p><strong>ListViewExtensions.cs:</strong></p> <pre><code>public static class ListViewExtensions { public static void DrawSortArrow(this ListView listView, SortOrder sortOrder, int colIndex) { string upArrow = "▲ "; string downArrow = "▼ "; foreach (ColumnHeader ch in listView.Columns) { if (ch.Text.Contains(upArrow)) ch.Text = ch.Text.Replace(upArrow, string.Empty); else if (ch.Text.Contains(downArrow)) ch.Text = ch.Text.Replace(downArrow, string.Empty); } if (sortOrder == SortOrder.Ascending) listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, downArrow); else listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, upArrow); } } </code></pre> <p><strong>Usage:</strong></p> <pre><code>private void lstOffers_ColumnClick(object sender, ColumnClickEventArgs e) { lstOffers.DrawSortArrow(SortOrder.Descending, e.Column); } </code></pre>
How to gracefully deal with ViewState errors? <p>I'm running some c# .net pages with various gridviews. If I ever leave any of them alone in a web browser for an extended period of time (usually overnight), I get the following error when I click any element on the page.</p> <p>I'm not really sure where to start dealing with the problem. I don't mind resetting the page if it's viewstate has expired, but throwing an error is unacceptable!</p> <pre><code> Error: The state information is invalid for this page and might be corrupted. Target: Void ThrowError(System.Exception, System.String, System.String, Boolean) Data: System.Collections.ListDictionaryInternal Inner: System.Web.UI.ViewStateException: Invalid viewstate. Client IP: 66.35.180.246 Port: 1799 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008052906 Firefox/3.0 ViewState: (**Very long Gibberish Omitted!**) Offending URL: (**Omitted**) Source: System.Web Message: The state information is invalid for this page and might be corrupted. Stack trace: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) at System.Web.UI.WebControls.DropDownList.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) </code></pre>
<p>That is odd as the ViewState is stored as a string in the webpage itself. So I do not see how an extended period of time would cause that error. Perhaps one or more objects on the page have been garbage collected or the application reset, so the viewstate is referencing old controls instead of the controls created when the application restarted. </p> <p>Whatever the case, I feel your pain, these errors are never pleasant to debug, and I have no easy answer as to how to find the problem other than perhaps studying <a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx" rel="nofollow">how ViewState works</a></p>
How do I send an SMTP Message from Java? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail">How do you send email from a Java app using Gmail?</a> </p> </blockquote> <p>How do I send an SMTP Message from Java?</p>
<p>Here's an example for Gmail smtp:</p> <pre><code>/* * */ import java.io.*; import java.net.InetAddress; import java.util.Properties; import java.util.Date; import javax.mail.*; import javax.mail.internet.*; import com.sun.mail.smtp.*; public class Distribution { public static void main(String args[]) throws Exception { Properties props = System.getProperties(); props.put("mail.smtps.host","smtp.gmail.com"); props.put("mail.smtps.auth","true"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("[email protected]"));; msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]", false)); msg.setSubject("Heisann "+System.currentTimeMillis()); msg.setText("Med vennlig hilsennTov Are Jacobsen"); msg.setHeader("X-Mailer", "Tov Are's program"); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); t.connect("smtp.gmail.com", "[email protected]", "&lt;insert password here&gt;"); t.sendMessage(msg, msg.getAllRecipients()); System.out.println("Response: " + t.getLastServerResponse()); t.close(); } } </code></pre> <p>Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache</p> <p><a href="http://commons.apache.org/email/" rel="nofollow">http://commons.apache.org/email/</a> </p> <p>Regards</p> <p>Tov Are Jacobsen</p>
Is there a console for Windows Mobile devices? <p>I would like to write small console based applications on Windows Mobile. What console applications might I use?</p>
<p>See this article: <a href="http://www.walkingrandomly.com/?p=22" rel="nofollow">Pocket Console on Windows Mobile 6</a></p>
Linux desktop shortcut and icon from install <p>What do I need to add to my <code>.spec</code> file to create the desktop shortcut and assign an icon to the shortcut during install of my <code>.rpm</code>? If a script is required, an example would be very helpful.</p>
<p>You use a .desktop file for icons under linux. Where to put the icon depends on what distribution and what desktop environment you are using. Since I'm currently running Gnome on Fedora 9, I will answer it in those terms.</p> <p>An example foo.desktop file would be:</p> <pre><code>[Desktop Entry] Encoding=UTF-8 GenericName=Generic Piece Of Software Name=FooBar Exec=/usr/bin/foo.sh Icon=foo.png Terminal=false Type=Application Categories=Qt;Gnome;Applications; </code></pre> <p>The .desktop file should under Fedora 9 Gnome be located in /usr/share/applications/ , you can run a locate on .desktop to figure out where you should put in on your distro. Gnome will generally look in the KDE icon directory to see if there are other icons there also....</p> <blockquote> <p>Encoding, Name and Exec should speak for themselves.</p> <ul> <li>Generic name == Brief Description of application.</li> <li>Icon == The image to display for the icon</li> <li>Terminal == Is this a terminal application, should I start it as one?</li> <li>Type == Type of program this is, can be used in placing the icon in a menu.</li> <li>Categories == This information is what is mainly used to place the icon in a given menu if an XML file to specify such is not present. The setup for menus is handled a little differently by everyone.</li> </ul> </blockquote> <p>There are more attributes you can set, but they aren't strictly necessary.</p> <p>The image file used sits somewhere in the bowels of the /usr/share/icons/ directory. You can parse through that to find all the wonders of how such things work, but the basics are that you pick the directory for the icon type (in my case gnome) and place the image within the appropriate directory (there is a scalable directory for .svg images, and specific sizes such as 48x48 for raster images. Under Gnome all images are generally .png).</p>
Combine PDFs c# <p>How can I combine multiple PDFs into one PDF without a 3rd party component?</p>
<p>I don't think you can. Opensource component PDFSharp has that functionality, and a nice <a href="http://www.pdfsharp.com/PDFsharp/index.php?option=com_content&amp;task=view&amp;id=24&amp;Itemid=35" title="source sample">source code sample on file combining</a></p>
Dropdownlist width in IE <p>In IE, the dropdown-list takes the same width as the dropbox (I hope I am making sense) whereas in Firefox the dropdown-list's width varies according to the content. </p> <p>This basically means that I have to make sure that the dropbox is wide enough to display the longest selection possible. This makes my page look very ugly :(</p> <p>Is there any workaround for this problem? How can I use CSS to set different widths for dropbox and the dropdownlist?</p>
<p>Here's another <a href="http://jquery.com">jQuery</a> based example. In contrary to all the other answers posted here, it takes all keyboard and mouse events into account, especially clicks:</p> <pre><code>if (!$.support.leadingWhitespace) { // if IE6/7/8 $('select.wide') .bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); }) .bind('click', function() { $(this).toggleClass('clicked'); }) .bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }}) .bind('blur', function() { $(this).removeClass('expand clicked'); }); } </code></pre> <p>Use it in combination with this piece of CSS:</p> <pre><code>select { width: 150px; /* Or whatever width you want. */ } select.expand { width: auto; } </code></pre> <p>All you need to do is to add the class <code>wide</code> to the dropdown element(s) in question.</p> <pre><code>&lt;select class="wide"&gt; ... &lt;/select&gt; </code></pre> <p><a href="http://jsfiddle.net/HnV9Q/">Here is a jsfiddle example</a>. Hope this helps.</p>
What is the difference between explicit and implicit cursors in Oracle? <p>I am a bit rusty on my cursor lingo in PL/SQL. Anyone know this?</p>
<p>An implicit cursor is one created "automatically" for you by Oracle when you execute a query. It is simpler to code, but suffers from </p> <ul> <li>inefficiency (the ANSI standard specifies that it must fetch twice to check if there is more than one record)</li> <li>vulnerability to data errors (if you ever get two rows, it raises a TOO_MANY_ROWS exception)</li> </ul> <p>Example</p> <pre><code>SELECT col INTO var FROM table WHERE something; </code></pre> <p>An explicit cursor is one you create yourself. It takes more code, but gives more control - for example, you can just open-fetch-close if you only want the first record and don't care if there are others. </p> <p>Example</p> <pre><code>DECLARE CURSOR cur IS SELECT col FROM table WHERE something; BEGIN OPEN cur; FETCH cur INTO var; CLOSE cur; END; </code></pre>
Generate thumbnail with white border <p>I need to generate thumbnails from a set of jpg's that need to have a small white border so that they appear to be "photos" when displayed on a map. Getting the thumbnails themselves is easy but I can't figure out how to get the border.</p>
<p>Here's a quick hack:</p> <pre><code>public Image AppendBorder(Image original, int borderWidth) { var borderColor = Color.White; var newSize = new Size( original.Width + borderWidth * 2, original.Height + borderWidth * 2); var img = new Bitmap(newSize.Width, newSize.Height); var g = Graphics.FromImage(img); g.Clear(borderColor); g.DrawImage(original, new Point(borderWidth, borderWidth)); g.Dispose(); return img; } </code></pre> <p>It creates a new <code>Bitmap</code> object which has the size of the original plus 2 times border width and then paint the original image in the middle and then return the finished image.</p> <p>You can do a lot of drawing/painting with the <code>Graphics</code> object above too.</p>