instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm writing a simple IDictionary abstraction in C# that wraps a Dictionary&lt;K, ICollection&lt;V&gt;&gt;. Basically, it maps multiple values to one key. I can't decide whether to remove a key and its empty list when the last item in a values list is removed, or leave it (to avoid instantiating a new collection if the key is reused) and do checks on a key's values' Count when determining whether a key exists.</p>
<p>I would remove the collections so that your MultiMap has consistent behavior. If I used your MultiMap I would be very surprised (and unhappy) to find that a missing key behaves differently depending on whether a key was previously in the MultiMap or not.</p> <p>Does Clear() remove the the Collections?</p> <p>You may also create an unintended memory leak if you do not remove the collections. A developer may add many items, then remove them. Memory usage (after GC) should return to the same amount as before those items were added.</p> <p>I would not worry about the cost of creating Collections. I would worry about the contract you create for your MultiMap. If after profiling your application you find that to be a concerned, you could modify or create a special MultiMap for that behavior. Don't fall into the trap of premature optimization.</p>
<p>Why not treat the key as present even if all the values are removed, and provide explicit API for removing the key?</p>
40,214
<p>My employer uses subversion for version-control, and this is unlikely to change. I'm interested in learning more about git, and using git-svn to interface with my employer's subversion repositories. My question is: if I were to begin using git-svn, would I need to do some or all of my version control work from the command-line? Or is there a (linux) GUI client that can perform all the git-svn-related tasks that I will need?</p> <p>Update: Based on the answers so far, there doesn't appear to be a GUI client for git-svn. However, I would like to call attention to <a href="http://bugzilla.gnome.org/show_bug.cgi?id=566293" rel="noreferrer">this feature request</a> for the Giggle GUI client as proof that there is some interest in a feature like this. Hopefully a positive answer to this question can be added sometime in the coming months. (In fact, I think that in the near future, the best way to interact with subversion might be to use a GUI client for git!)</p> <p>Update 2: The recently released 2.1 version of SmartGit does fully support Git/SVN integration. This proves that there is at least one GUI client allowing Git and SVN to be used together. There may be more.</p>
<p><a href="http://www.syntevo.com/git-svn/index.html" rel="nofollow noreferrer">This page</a> seems to indicate that <a href="http://www.syntevo.com/smartgit/index.html" rel="nofollow noreferrer">SmartGit</a> can do what you want. As far as I can tell, you have to do the initial init/clone from cmd/bash though.</p>
<p>I wonder if it would be possible to somehow intercept the Push command in git-gui and make it run git-svn dcommit instead? I have already added an git alias to run !git-svn dcommit.</p>
48,580
<p>I used <code>git pull</code> and had a merge conflict:</p> <pre><code>unmerged: some_file.txt You are in the middle of a conflicted merge. </code></pre> <p>How do I abandon my changes to the file and keep only the pulled changes?</p>
<p>Since your <code>pull</code> was unsuccessful then <code>HEAD</code> (not <code>HEAD^</code>) is the last "valid" commit on your branch:</p> <pre><code>git reset --hard HEAD </code></pre> <p>The other piece you want is to let their changes over-ride your changes. </p> <p>Older versions of git allowed you to use the "theirs" merge strategy:</p> <pre><code>git pull --strategy=theirs remote_branch </code></pre> <p>But this has since been removed, as explained in <a href="http://marc.info/?l=git&amp;m=121637513604413&amp;w=2" rel="noreferrer">this message by Junio Hamano</a> (the Git maintainer). As noted in <a href="http://marc.info/?l=git&amp;m=121637513604413&amp;w=2" rel="noreferrer">the link</a>, instead you would do this:</p> <pre><code>git fetch origin git reset --hard origin </code></pre>
<p>I found the following worked for me (revert a single file to pre-merge state):</p> <pre><code>git reset *currentBranchIntoWhichYouMerged* -- *fileToBeReset* </code></pre>
12,722
<p>Does SQL Server's (2000) <strong>Soundex function work on Asian character sets</strong>? I used it in a query and it appears to have not worked properly but I realize that it could be because I don't know how to read Chinese...</p> <p>Furthermore, are there any other languages where the function might have trouble working on? (Russian for example)</p> <p>Thank you,<br>Frank</p>
<p>Soundex is fairly specific to English - it may or may not work well on other languages. One example that happened in New Zealand was an attempt at patient name matching using Soundex. Unfortunately pacific island names did not work well with Soundex, in many cases hashing to the same small set of values. A different algorithm had to be used.</p> <p>Your mileage may vary. On more recent versions of SQL Server you could write a CLR function to do some other computation.</p>
<p>You may use an algorithm like Levenshtein distance. There are various implementations of the algorithm as user-defined functions which you may use within a <code>SELECT</code> statement.</p>
38,443
<p>Essentially the only thing I can deploy to my deployment machine is a JAR file. I can't install JRuby, nor can I install Glassfish or Tomcat.</p> <p>Is it possible to package up a Rails application (including Rails, vendored, of course) to a JAR file such that I can do</p> <pre><code>c:\my_server&gt; java rails_app.jar </code></pre> <p>and have it run WEBRick or Mongrel within the JVM?</p>
<p>I'd recommend that you checkout Jetty. The process for <a href="http://docs.codehaus.org/display/JETTY/Embedding+Jetty" rel="noreferrer">Embedding Jetty</a> is surprisingly easy, and it should be possible to give it your servlets from your current jar file. I haven't used Ruby/Rails, though, so I'm not sure if there are any complications there.</p> <p>Is it normally possible to embed all of your rails templates/models into a jar inside of a war file for deployment on Tomcat? If so, then you should be able to get embedded Jetty to pull it from your single jar as well.</p>
<p>I just ran across this blog today, and I intend on giving it a try, if anyone else has let me know</p> <p><a href="http://matthewkwilliams.com/index.php/2010/03/02/rails-jruby-in-a-jar/" rel="nofollow">http://matthewkwilliams.com/index.php/2010/03/02/rails-jruby-in-a-jar/</a></p>
15,695
<p>SQL:</p> <pre><code>SELECT u.id, u.name, isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault FROM universe u LEFT JOIN history h ON u.id=h.id AND h.dateCol&lt;GETDATE()-1 GROUP BY u.Id, u.name </code></pre>
<p>A solution, albeit one that defers handling of the null value to the code, could be:</p> <blockquote> <p>DateTime yesterday = DateTime.Now.Date.AddDays(-1);</p> </blockquote> <pre><code>var collection= from u in db.Universe select new { u.id, u.name, MaxDate =(DateTime?) ( from h in db.History where u.Id == h.Id &amp;&amp; h.dateCol &lt; yesterday select h.dateCol ).Max() }; </code></pre> <p>This does not produce exactly the same SQL, but does provide the same logical result. Translating "complex" SQL queries to LINQ is not always straightforward.</p>
<p>This isn't a full answer for you, but on the left join piece you can use the DefaultIfEmpty operator like so:</p> <pre><code>var collection = from u in db.Universe join history in db.History on u.id = history.id into temp from h in temp.DefaultIfEmpty() where h.dateCol &lt; DateTime.Now.Date.AddDays(-1) select u.id, u.name, h.dateCol ?? '1900-01-01' </code></pre> <p>I haven't had the need to do any <code>groupby</code> commands yet, so I left that out as to not send you down the wrong path. Two other quick things to note. I have been unable to actually join on two parameters although as above there are ways to get around it. Also, the ?? operator works really well in place of the <code>isnull</code> in SQL. </p>
2,325
<p>I know the file needs to be where the getClass().getResource(filename) can find it, but I don't know where that is.</p> <p>I'm interested both in where to put the files on the filesystem itself, and how to go about using Eclipse's functionality to set up the resources.</p>
<p>For Eclipse, typically all you need to do is set up a folder somewhere within your source code directory. For instance, if the directory containing your source is <code>/src</code> then you can create a <code>/src/resources</code> folder to place your images/files in. Then, within your class you do a <code>getResource("/resources/image.png")</code> to retrieve it. </p> <p>You can also place the image/file within the same folder/package as the class trying to access it if you wish (example: place the image.png in the <code>com.mycompany</code> package with the <code>com.mycompany.Foo</code> class that needs to access it and call <code>getResource("image.png")</code>), but I've found it's easier to keep resources like images and other files in their own special directory outside of the class folders -- they're just easier to manage that way.</p> <p>In Eclipse, whenever you do a build, the files within this resource directory will be copied over into your build directory along with your compiled classes. </p> <p>It's important to note that if you have "Build Automatically" turned on in Eclipse (as most people do) any resources in this directory that get changed outside of Eclipse (i.e. you edit an image using an image editing tool) that the IDE may not always detect this change. Usually doing a refresh on the project folder will ensure that the file gets updated in the build in these situations.</p>
<p>You can either put them in the src folder alongside your classes, or you can create a new source folder for the purpose (usually called <em>resources</em>), although you'll locate them identically from code.</p> <p>Then you get at them using <code>getResource("/com/x/y/foo.png")</code>.</p>
33,954
<p>I'm going to try out turbogears however I'm on windows vista. however due to firewall proxy problems, it seems i can't download .egg files which is required for setup turbogears to get installed in my windows environment. I do have a bootable, or I can make a bootable Linux USB, I can try cygwin but I am not sure where to start with cygwin, so I was wondering what would solve my firewall / proxy problem of installing something like turbogears.</p> <p>if it's possible, is there some non-online version of turbogears that i could just download from visiting a site and then somehow importing that non-online version into my python environment?</p> <p>thanks so much!:)</p>
<p>You can run TG <a href="http://docs.turbogears.org/1.0/InstallWindows" rel="nofollow noreferrer">locally from windows</a>. The <code>tgsetup.py</code> method of installation uses <a href="http://pypi.python.org/pypi/setuptools/0.6c9" rel="nofollow noreferrer">setuptools</a> which depends on being able to bring in <code>.egg</code> files from the internet. The best approach would be to open the firewall to eggs, as others suggested. TG has a <a href="http://www.turbogears.org/download/filelist.html" rel="nofollow noreferrer">list of egg files</a> that you can try to bring manually (maybe from an open internet connection). Installing an egg manually is possible, but <a href="http://www.turbogears.org/download/filelist.html" rel="nofollow noreferrer">not recommended</a>.</p> <p>If changing the firewall rules is not possible, you can use a Linux (bootable or virtual) installation that has a pre-configured TG package. For example, <a href="http://mirror.isoc.org.il/pub/fedora/releases/9/Everything/i386/os/Packages/TurboGears-1.0.4.4-2.fc9.noarch.rpm" rel="nofollow noreferrer">Fedora has one</a>. This way, the TG package crosses (hopefully) the firewall as an <code>.rpm</code> file.</p>
<p>This might not be what you are looking for, but you can <a href="http://www.mtu.net/~engstrom/ssh-proxy.php" rel="nofollow noreferrer">bypass the proxy tunneling SSH</a>. Another possibility is using <a href="http://tor.eff.org" rel="nofollow noreferrer">Tor</a>.</p>
35,845
<p>I have an internal enterprise application I've developed for my company built on .Net 3.5 / SQL 2008. </p> <p>I have two types of databases. The main system database which contains all of our global data, such as user names, and customers, etc. And project databases, which contain the actual data pertaining to our clients project.</p> <p>When the system creates a new project for a customer, it needs to provision a new SQL database using a custom schema providing the tables, views, sps, etc. The name of the project database corresponds to the Project ID of the project stored in the system database. So a new project will create a new project database with the name: Project_XXX where XXX is the project id.</p> <p>My question is what is the best way to provision a custom database programatically? Right now the only way I can think to do it is have a class which reads a SQL script from the file system and does a parse to replace the project ID for the name of the database. This is easy, but seems rather inelegant. </p> <p>Any approaches some veterans out there prefer over this?</p>
<p>Generally if there is only ever one (or a handful) of databases, and you have direct control over them (typicall corporate environment), I'd recommend not auto upgrading the databases as it is more hassle than it's worth. Just pass the script on to the people doing the install.</p> <p>For more widespread releases in the past I have used a script as you suggest along with the <a href="http://msdn.microsoft.com/en-us/library/ms162169.aspx" rel="nofollow noreferrer">SQL Server SMO</a> library (Server.CurrentContext.ExecuteNonQuery()). I don't find it inelegant is it is simple and it works.</p> <p>For the first release we would include a full DB build script, then add an upgrade script for each subsquent release. So if someone installs v1.2 over v1.1 we would only run the v1.2 script. However if they did a fresh install we would run v1.0, v1.1 and v1.2.</p>
<p>Since you are using .NET 3.5 you may want to consider using LINQ. LINQ has the ability to dynamically create a database (<a href="http://msdn.microsoft.com/en-us/library/bb399420.aspx" rel="nofollow noreferrer">link to howto</a>) using a mapping file or the strongly typed DBML file you've created. I believe that it can create the appropriate tables in multiple places. This probably works ok for simple databases.</p> <p>I can't see how it would work, however, if you had functions or stored procedures and/or indexes on non-primary keys. The mapping file may be able to track these, but I've never used one so I'm skeptical. Probably @doofledorfer's idea on using SQL scripts to recreate the database structure in a new database is the way to go. I typically keep these scripts in my source code control anyway.</p> <p>If you haven't already done so you may want to look into tools for managing updates. Presumably you'll need to roll any db changes across existing projects as your code/db changes. We've had good results with <a href="http://www.red-gate.com" rel="nofollow noreferrer">Red Gate</a> SQL tools.</p>
38,092
<p>I'm trying to have a new layer appear above existing content on my site when a link/button is clicked. I am using jquery - but the code I have doesn't seem to work as expected.</p> <p>Here is what I have:</p> <pre><code> $(document).ready(function(){ $("#button").click(function () { $("#showme").insertAfter("#bodytag") $("#showme").fadeIn(2000); }); </code></pre> <p>});</p> <p>The effect I'm after is to have <code>&lt;div id="showme"&gt;...&lt;/div&gt;</code> appear directly after the #bodytag. <code>&lt;div id="showme"&gt;...&lt;/div&gt;</code> has a z-index higher than anything else on the site, so it should just appear above the content directly after the #bodytag.</p> <p>Thanks for the assistance.</p>
<p>It would appear to me that to get the desired effect, the div you are inserting #showme into needs to be position: relative, and #showme should be position: absolute. Absolute positioning will take the element out of the document flow, allowing it to sit above the content.</p> <p>Also, two tips - $() is a shortcut for $(document), and you can chain jQuery commands:</p> <pre><code>$().ready(function(){ $("#button").click(function () { $("#showme").insertAfter("#bodytag").fadeIn(2000); }); }); </code></pre>
<p>Make sure <code>#showme</code> has a <code>position</code> other than <code>static</code>.</p>
27,570
<p>I was looking into using some .NET code from within a Delphi program, I will need to make my program extensible using .net assemblies and predefined functions (I already support regular DLLs).</p> <p>After a lot of searching online, I found <a href="http://www.managed-vcl.com/" rel="noreferrer">Managed-VCL</a>, but I'm not ready to pay $250 for what I need, I also found some newsgroups with code that's incomplete and doesn't work.</p> <p>I'm using Delphi 2007 for win32. What can I use to dynamically execute a function from an assembly with predefined parameters?</p> <p>Something like:</p> <pre><code>procedure ExecAssembly(AssemblyFileName:String; Parameters: Variant); </code></pre> <p>I just want to add that I need to be able to load an arbitrary assemblies (maybe all the assemblies in a specific folder), so creating a C# wrapper may not work.</p>
<p>In the Jedi Code Library (JCL) - free - there is a JclDotNet.pas, containing a class TJclClrHost, probably doing what you want:</p> <pre><code> TJclClrHost = class(TJclClrBase, ICorRuntimeHost) private FDefaultInterface: ICorRuntimeHost; FAppDomains: TObjectList; procedure EnumAppDomains; function GetAppDomain(const Idx: Integer): TJclClrAppDomain; function GetAppDomainCount: Integer; function GetDefaultAppDomain: IJclClrAppDomain; function GetCurrentAppDomain: IJclClrAppDomain; protected function AddAppDomain(const AppDomain: TJclClrAppDomain): Integer; function RemoveAppDomain(const AppDomain: TJclClrAppDomain): Integer; public constructor Create(const ClrVer: WideString = ''; const Flavor: TJclClrHostFlavor = hfWorkStation; const ConcurrentGC: Boolean = True; const LoaderFlags: TJclClrHostLoaderFlags = [hlOptSingleDomain]); destructor Destroy; override; procedure Start; procedure Stop; procedure Refresh; function CreateDomainSetup: TJclClrAppDomainSetup; function CreateAppDomain(const Name: WideString; const Setup: TJclClrAppDomainSetup = nil; const Evidence: IJclClrEvidence = nil): TJclClrAppDomain; function FindAppDomain(const Intf: IJclClrAppDomain; var Ret: TJclClrAppDomain): Boolean; overload; function FindAppDomain(const Name: WideString; var Ret: TJclClrAppDomain): Boolean; overload; class function CorSystemDirectory: WideString; class function CorVersion: WideString; class function CorRequiredVersion: WideString; class procedure GetClrVersions(VersionNames: TWideStrings); overload; class procedure GetClrVersions(VersionNames: TStrings); overload; property DefaultInterface: ICorRuntimeHost read FDefaultInterface implements ICorRuntimeHost; property AppDomains[const Idx: Integer]: TJclClrAppDomain read GetAppDomain; default; property AppDomainCount: Integer read GetAppDomainCount; property DefaultAppDomain: IJclClrAppDomain read GetDefaultAppDomain; property CurrentAppDomain: IJclClrAppDomain read GetCurrentAppDomain; end; </code></pre>
<p>You can use .Net classes as COM objects in Delphi:</p> <ul> <li>create assembly in C# </li> <li>create type library for assembly</li> <li>import type library in Delphi</li> </ul> <p>Now you can access classes from .Net assembly that are exported in type library.</p>
32,324
<p>I have an NFS-mounted directory on a Linux machine that has hung. I've tried to force an unmount, but it doesn't seem to work:</p> <pre><code>$ umount -f /mnt/data $ umount2: Device or resource busy $ umount: /mnt/data: device is busy </code></pre> <p>If I type "<code>mount</code>", it appears that the directory is no longer mounted, but it hangs if I do "<code>ls /mnt/data</code>", and if I try to remove the mountpoint, I get:</p> <pre><code>$ rmdir /mnt/data rmdir: /mnt/data: Device or resource busy </code></pre> <p>Is there anything I can do other than reboot the machine?</p>
<p>You might try a lazy unmount:</p> <pre><code>umount -l </code></pre>
<p>Your NFS server disappeared.</p> <p>Ideally your best bet is if the NFS server comes back.</p> <p>If not, the "umount -f" should have done the trick. It doesn't ALWAYS work, but it often will.</p> <p>If you happen to know what processes are USING the NFS filesystem, you could try killing those processes and then maybe an unmount would work.</p> <p>Finally, I'd guess you need to reboot.</p> <p>Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee that they worked. That's necessary if you're doing writes.</p>
6,153
<p>I'm working on a C++ library that (among other stuff) has functions to read config files; and I want to add tests for this. So far, this has lead me to create lots of valid and invalid config files, each with only a few lines that test one specific functionality. But it has now got very unwieldy, as there are so many files, and also lots of small C++ test apps. Somehow this seems wrong to me :-) so do you have hints how to organise all these tests, the test apps, and the test data?</p> <p>Note: the library's public API itself is not easily testable (it requires a config file as parameter). The juicy, bug-prone methods for actually reading and interpreting config values are private, so I don't see a way to test them directly?</p> <p>So: would you stick with testing against real files; and if so, how would you organise all these files and apps so that they are still maintainable?</p>
<p>Perhaps the library could accept some kind of stream input, so you could pass in a string-like object and avoid all the input files? Or depending on the type of configuration, you could provide "get/setAttribute()" functions to directly, publicy, fiddle the parameters. If that is not really a design goal, then never mind. Data-driven unit tests are frowned upon in some places, but it is definitely better than nothing! I would probably lay out the code like this:</p> <pre><code> project/ src/ tests/ test1/ input/ test2 input/ </code></pre> <p>In each testN directory you would have a cpp file associated to the config files in the input directory.</p> <p>Then, assuming you are using an xUnit-style test library (<a href="http://cppunit.sourceforge.net/" rel="nofollow noreferrer">cppunit</a>, <a href="http://code.google.com/p/googletest/" rel="nofollow noreferrer">googletest</a>, <a href="http://unittest-cpp.sourceforge.net/" rel="nofollow noreferrer">unittest++</a>, or whatever) you can add various testXXX() functions to a single class to test out associated groups of functionality. That way you could cut out part of the lots-of-little-programs problem by grouping at least some tests together.</p> <p>The only problem with this is if the library expects the config file to be called something specific, or to be in a specific place. That shouldn't be the case, but if it is would have to be worked around by copying your test file to the expected location.</p> <p>And don't worry about lots of tests cluttering your project up, if they are tucked away in a tests directory then they won't bother anyone.</p>
<p>In some tests I have done, I have actually used the test code to write the configuration files and then delete them after the test had made use of the file. It pads out the code somewhat and I have no idea if it is good practice, but it worked. If you happen to be using boost, then its filesystem module is useful for creating directories, navigating directories, and removing the files.</p>
22,592
<p>If I create classes, that are used at the moment only in a single thread, should I make them thread-safe, even if I don't need that at the moment? It could be happen, that I later use this class in multiple threads, and at that time I could get race conditions and may have a hard time to find them if I didn't made the class thread-safe in the first place. Or should I make the class not thread-safe, for better performance? But premature optimization is evil.</p> <p>Differently asked: Should I make my classes thread-safe if needed (if used in multiple threads, otherwise not) or should I optimize this issue then needed (if I see that the synchronization eats up an important part of processing time)?</p> <p>If I choose one of the both ways, are there methods to reduce the disadvantages? Or exists a third possibility, that I should use?</p> <p><strong>EDIT</strong>: I give the reason this question came up to my mind. At our company we have written a very simple user-management that writes the data into property-files. I used it in a web-app and after some work on it I got strange errors, that the user-management forgot about properties of users(including name and password) and roles. That was very annoying but not consistently reproducible, so I think it was race condition. Since I synchronized all methods reading and writing from/on disk, the problem disappeared. So I thought, that I probably could have been avoided all the hassle, if we had written the class with synchronization in the first place?</p> <p><strong>EDIT 2</strong>: As I look over the tips of Pragmatic Programmer, I saw tip #41: Always Design for Concurrency. This doesn't say that all code should be thread-safe, but it says the design should have the concurrency in mind.</p>
<p>Start from the data. Decide which data is explicitly shared and protect it. If at all possible, encapsulate the locking with the data. Use pre-existing thread-safe concurrent collections.</p> <p>Whenever possible, use immutable objects. Make attributes final, set their values in the constructors. If you need to "change" the data consider returning a new instance. Immutable objects don't need locking. </p> <p>For objects that are not shared or thread-confined, do not spend time making them thread-safe. </p> <p>Document the expectations in the code. The JCIP annotations are the best pre-defined choice available. </p>
<p>If you want to follow what Sun did in the Java API, you can take a look at the collection classes. Many common collection classes are not thread-safe, but have thread-safe counterparts. According to Jon Skeet (see comments), many of the Java classes were originally thread-safe, but they were not benefiting developers, so some classes now have two versions - one being thread-safe and the other not thread-safe.</p> <p>My advice is to not make the code thread-safe until you have to, as there is some overhead involved with thread-safety. I guess this falls into the same category as optimization - don't do it before you have to.</p>
29,010
<p>With Windows 7 probably going to RTM next October (and DirectX 11 with it), would it be worth waiting for DirectX 11's explicit GPGPU features, meaning it will be cross-platform (ATI/Nvidia, not Windows/Linux/Mac/Whatever); or should I create a CUDA application now?</p>
<p>From a learning point-of-view I think you would benefit from starting with CUDA now, since it will help you a lot with thinking in data-parallelism which is what the GPUs are good at. Then when/if you turn to DirectX 11, you have a good foundation for working with it, but it depends on the kind of time you have available (i.e. if you have time to experiment with stuff just for the learning experience).</p> <p>Alternatively, the mac people are pushing for OpenCL (Open Compute Language) to be the general solution, though not much is known at this point. This is another technology you can wait for and check out.</p> <p>The Microsoft PDC conference is held later this month, maybe they will announce some useful info on DX11 to help you make up your mind.</p> <p>My general advice would be that I think there is a lot to learn now which you will be able to use later (with DX11 or OpenCL) but that you have to ask yourself if you are willing to learn some technology which might not make it in the long run. Anyways, these are just my thoughts, I don't have a huge amount of experience with CUDA yet.</p> <p>On a highly speculative note, my gut feeling is that APIs such as CUDA won't survive for long and that DirectX and/or OpenCL are the only solutions which have a future (Unless they really botch their implementations, which I doubt).</p>
<p>If you want the learning experience, go for it!</p> <p>Another alternative is AMD/ATI's stream SDK which you can download here: <a href="http://ati.amd.com/technology/streamcomputing/sdkdwnld.html" rel="nofollow noreferrer">http://ati.amd.com/technology/streamcomputing/sdkdwnld.html</a></p> <p>nVidia's Cuda and ATI's CAL are roughly equivalent in features. Cuda only works on nVidia gpus and CAL only works on ATI gpus.</p> <p>Eventually, there will be good cross-platform development tools, but that's a huge void right now. DirectX 11 compute shaders and OpenCL will be fighting it out to be the tool of choice, but neither one is available yet.</p> <p>If you want build some "real" app, and not just a throw-away learning experience, <strong>and</strong> you want it to work cross-platform, there are some alternatives: Brook, for example. Also, people have been doing gpgpu work with both DirectX and OpenGL (not OpenCL) for several years, without waiting for explicit GPGPU features. Go to gpgpu.org for pointers</p>
27,810
<p>Suppose there´s a template function in C++ that does some useful work but also outputs a sequence of values via an output iterator. Now suppose that that sequence of values sometimes is interesting, but at others is not useful. Is there a ready-to-use iterator class in the STL that can be instantiated and passed to the function and will ignore any values the function tries to assign to the output iterator? To put in another way, send all data to /dev/null?</p>
<p>The STL does not provide such an iterator. But you could code it yourself (tested that code):</p> <pre><code>struct null_output_iterator : std::iterator&lt; std::output_iterator_tag, null_output_iterator &gt; { /* no-op assignment */ template&lt;typename T&gt; void operator=(T const&amp;) { } null_output_iterator &amp; operator++() { return *this; } null_output_iterator operator++(int) { return *this; } null_output_iterator &amp; operator*() { return *this; } }; </code></pre> <p>It doesn't need any data by using itself as the result of <code>operator*</code>. The result of <code>*it = x;</code> is not used in the output iterator requirements, so we can give it a return type of <code>void</code>.</p> <hr> <p>Edit: Let's go into how this <code>operator*</code> works. The Standard says in <strong>24.1.2/1</strong> about the requirements of an output iterator that in both these cases:</p> <pre><code>*it = t; *it++ = t; </code></pre> <p>That the result of those expressions is not used. That's what makes this work:</p> <pre><code>null_output_iterator it; *it; // returns a null_output_iterator&amp; per definition of the `operator*`. *it = some_value; // returns void per definition of the templated `operator=`. </code></pre> <p>Now we don't need to have any data that we return in <code>operator*</code>: We just use the iterator itself. Note that the templated operator= does not overwrite the builtin copy assignment operator. It's still provided.</p>
<p>I based mine on <a href="http://www.open-std.org/jtc1/sc22/open/n2356/lib-iterators.html#lib.back.insert.iterator" rel="nofollow noreferrer">std::back_insert_iterator</a>, but without the container:</p> <pre><code>#include &lt;iterator&gt; template&lt;typename T&gt; class NullOutputIter : public std::iterator&lt;std::output_iterator_tag,void,void,void,void&gt; { public: NullOutputIter &amp;operator=(const T &amp;) { return *this; } NullOutputIter &amp;operator*() { return *this; } NullOutputIter &amp;operator++() { return *this; } NullOutputIter operator++(int) { return *this; } }; </code></pre> <p>This is similar to Johannes's answer, but without the template <code>operator=</code> that takes whatever. I like strong typing; I want <code>*it = wrong_type_thing</code> to be a compile-time error. Also this uses <code>void</code> for the various template parameters to <code>std::iterator</code>, like the output iterators in the standard library.</p> <p>This is also similar to Mark's solution, but (a) it properly inherits from <code>std::iterator</code> and (b) it does not have the unneeded internal state variable.</p>
43,582
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/73713/how-do-i-check-for-nulls-in-an-operator-overload-without-infinite-recursion">How do I check for nulls in an &#39;==&#39; operator overload without infinite recursion?</a> </p> </blockquote> <p>When I overload the == operator for objects I typically write something like this:</p> <pre><code> public static bool operator ==(MyObject uq1, MyObject uq2) { if (((object)uq1 == null) || ((object)uq2 == null)) return false; return uq1.Field1 == uq2.Field1 &amp;&amp; uq1.Field2 == uq2.Field2; } </code></pre> <p>If you don't down-cast to object the function recurses into itself but I have to wonder if there isn't a better way?</p>
<p>As Microsoft says,</p> <blockquote> <p>A common error in overloads of operator == is to use (a == b), (a == null), or (b == null) to check for reference equality. This instead results in a call to the overloaded operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to avoid the loop.</p> </blockquote> <p>So use ReferenceEquals(a, null) || ReferenceEquals(b, null) is one possibility, but casting to object is just as good (is actually equivalent, I believe). </p> <p>So yes, it seems there should be a better way, but the method you use is the one recommended.</p> <p>However, as has been pointed out, you really SHOULD override Equals as well when overriding ==. With LINQ providers being written in different languages and doing expression resolution at runtime, who knows when you'll be bit by not doing it even if you own all the code yourself.</p>
<p>Follow the DB treatment:</p> <pre><code>null == &lt;anything&gt; is always false </code></pre>
11,245
<p>I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop:</p> <pre><code>var iWeeks = 6; for (int w = 0; w &lt; iWeeks; w++) { </code></pre> <p>This works fine, however, some month will only have 5 weeks and in some rare cases, 4.</p> <p>How can I calculate the number of rows that will be required for a particular month?</p> <p>This is an example of what I am creating:</p> <p><img src="https://i.stack.imgur.com/NkxN7.png" alt="enter image description here"></p> <p>As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.</p> <p><strong><em>Image found on google</em></strong></p> <hr> <p>This is an example of what I am creating:</p> <p><img src="https://i.stack.imgur.com/NkxN7.png" alt="enter image description here"></p> <p>As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.</p> <p><strong><em>Image found on google</em></strong></p>
<p>Here is the method that does it:</p> <pre><code>public int GetWeekRows(int year, int month) { DateTime firstDayOfMonth = new DateTime(year, month, 1); DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1); System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar; int lastWeek = calendar.GetWeekOfYear(lastDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); int firstWeek = calendar.GetWeekOfYear(firstDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); return lastWeek - firstWeek + 1; } </code></pre> <p>You can customize the calendar week rule by modifying the System.Globalization.CalendarWeekRule.FirstFourDayWeek part. I hope the code is self explanatory.</p>
<p>How about checking which week the first and last days will be in?</p>
3,116
<p>Following is some obviously-defective code for which I think the compiler should emit a diagnostic. But neither <code>gcc</code> nor <code>g++</code> does, even with all the warnings options I could think of: <code>-pedantic -Wall -Wextra</code></p> <pre><code>#include &lt;stdio.h&gt; short f(short x) { return x; } int main() { long x = 0x10000007; /* bigger than short */ printf("%d\n", f(x)); /* hoping for a warning here */ return 0; } </code></pre> <p>Is there a way to make <code>gcc</code> and <code>g++</code> warn about this? On a side note, do you have another compiler which warns about this by default or in a fairly common extra-warnings configuration?</p> <p>Note: I'm using GCC (both C and C++ compilers) version 4.2.4.</p> <p>Edit: I just found that <code>gcc -Wconversion</code> does the trick, but the same option to <code>g++</code> doesn't, and I'm really using C++ here, so I need a solution for <code>g++</code> (and am now wondering why <code>-Wconversion</code> doesn't seem to be it).</p> <p>Edit: <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34389" rel="noreferrer">http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34389</a> suggests that this may be fixed in <code>g++ 4.4</code>...maybe? It's not clear to me yet if it's the same issue and/or if the fix is really coming in that version. Maybe someone with 4.3 or 4.4 can try my test case.</p>
<p>Use -Wconversion -- the problem is an implicit cast (conversion) from long x to short when the function f(short x) is called [not printf], and -Wconversion will say something like "cast from long to short may alter value".</p> <p>..</p> <p>Edit: just saw your note. -Wconversion results in a warning for me, using g++ 4.3.2 on Linux... (4.3.2-1 on Debian)</p>
<p>I would strongly suggest investing in PC-lint/FlexeLint from <a href="http://gimpel.com/" rel="nofollow noreferrer">Gimpel</a>. The software is made for catching things like this that the compiler just isn't. It is relatively inexpensive and well worth the price. There is an online demo on the site that you can use to evaluate it, here is what it reports for the line in question from your example:</p> <pre><code>diy.cpp 14 Info 734: Loss of precision (arg. no. 1) (31 bits to 15 bits) </code></pre>
39,956
<p>So I'm using hibernate and working with an application that manages time. What is the best way to deal with times in a 24 hour clock?</p> <p>I do not need to worry about TimeZone issues at the beginning of this application but it would be best to ensure that this functionality is built in at the beginning.</p> <p>I'm using hibernate as well, just as an fyi</p>
<p>Store them as long ts = System.currentTimeMillis(). That format is actually TimeZone-safe as it return time in UTC.</p> <p>If you only need time part, well, I'm not aware of built-in type in Hib, but writing your own type Time24 is trivial -- just implement either org.hibernate.UserType or org.hibernate.CompositeUserType (load=nullSafeGet and store=nullSafeSet methods in them). </p> <p>See <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-types-custom" rel="nofollow noreferrer">http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-types-custom</a></p> <p>But I'd still save absolute time anyway. May help in future.</p> <p>P.S. That's all presuming storing Date is out of question for some reason. TimeZone in Date sometimes gets in the way, really. ;)</p>
<p><code>java.util.Date</code> should be used; not a long (and definitely not a <code>Calendar</code>).</p> <p>If you are using annotations be sure to use <code>@Temporal</code></p>
15,122
<p>I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore. </p> <p>There are several places in the codebase where it would clean up the code substantially if only there were a way to make the pre-processor ignore certain <code>#includes</code> if the file didn't exist in the current folder. Does anyone know a way to achieve that?</p> <p>Presently, we use an <code>#ifdef</code> around the <code>#include</code> in the shared file, with a second project-specific file that #defines whether or not the <code>#include</code> exists in the project. This works, but it's ugly. People often forget to properly update the definitions when they add or remove files from the project. I've contemplated writing a pre-build tool to keep this file up to date, but if there's a platform-independent way to do this with the preprocessor I'd much rather do it that way instead. Any ideas?</p>
<h1>Little Update</h1> <p>Some compilers might support <code>__has_include ( header-name )</code>.</p> <p>The extension was added to the <a href="https://isocpp.org/files/papers/p0636r0.html" rel="noreferrer">C++17 standard</a> (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0061r1.html" rel="noreferrer">P0061R1</a>).</p> <h2>Compiler Support</h2> <ul> <li>Clang</li> <li>GCC from 5.X</li> <li>Visual Studio from VS2015 Update 2 (?)</li> </ul> <h2>Example (from clang website):</h2> <pre><code>// Note the two possible file name string formats. #if __has_include("myinclude.h") &amp;&amp; __has_include(&lt;stdint.h&gt;) # include "myinclude.h" #endif </code></pre> <h1>Sources</h1> <ul> <li><a href="https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations" rel="noreferrer">SD-6: SG10 Feature Test Recommendations</a></li> <li><a href="http://clang.llvm.org/docs/LanguageExtensions.html#langext-has-include" rel="noreferrer">Clang Language Extensions</a></li> </ul>
<p><strong>I had to do something similar for the Symbian OS. This is how i did it: lets say you want to check if the file "file_strange.h" exists and you want to include some headers or link to some libraries depending on the existance of that file.</strong></p> <p><strong>first creat a small batch file for checking the existence of that file.</strong></p> <p>autoconf is good but an over kill for many small projects.</p> <p>----------check.bat</p> <pre><code>@echo off IF EXIST [\epoc32\include\domain\middleware\file_strange] GOTO NEW_API GOTO OLD_API GOTO :EOF :NEW_API echo.#define NEW_API_SUPPORTED&gt;../inc/file_strange_supported.h GOTO :EOF :OLD_API echo.#define OLD_API_SUPPORTED&gt;../inc/file_strange_supported.h GOTO :EOF </code></pre> <p>----------check.bat ends</p> <p><strong>then i created a gnumake file</strong></p> <p>----------checkmedialist.mk</p> <pre><code>do_nothing : @rem do_nothing MAKMAKE : check.bat BLD : do_nothing CLEAN : do_nothing LIB : do_nothing CLEANLIB : do_nothing RESOURCE : do_nothing FREEZE : do_nothing SAVESPACE : do_nothing RELEASABLES : do_nothing FINAL : do_nothing </code></pre> <p>----------check.mk ends</p> <p><strong>include the check.mk file in your bld.inf file, it MUST be before your MMP files</strong></p> <pre><code>PRJ_MMPFILES gnumakefile checkmedialist.mk </code></pre> <p><strong>now at compile time the file <code>file_strange_supported.h</code> will have an appropriate flag set. you can use this flag in your cpp files or even in the mmp file for example in mmp</strong></p> <pre><code>#include "../inc/file_strange_supported.h" #ifdef NEW_API_SUPPORTED LIBRARY newapi.lib #else LIBRARY oldapi.lib #endif </code></pre> <p><strong>and in .cpp</strong></p> <pre><code>#include "../inc/file_strange_supported.h" #ifdef NEW_API_SUPPORTED CStrangeApi* api = Api::NewLC(); #else // .. #endif </code></pre>
17,266
<p>I am writing a program that does a lot of writes to a Postgres database. In a typical scenario I would be writing say 100,000 rows to a table that's well normalized (three foreign integer keys, the combination of which is the primary key and the index of the table). I am using PreparedStatements and executeBatch(), yet I can only manage to push in say 100k rows in about 70 seconds on my laptop, when the embedded database we're replacing (which has the same foreign key constraints and indices) does it in 10.</p> <p>I am new at JDBC and I don't expect it to beat a custom embedded DB, but I was hoping it to be only 2-3x slower, not 7x. Anything obvious that I maybe missing? does the order of the writes matter? (i.e. say if it's not the order of the index?). Things to look at to squeeze out a bit more speed?</p>
<p>This is an issue that I have had to deal with often on my current project. For our application, insert speed is a critical bottleneck. However, we have discovered for the vast majority of database users, the select speed as their chief bottleneck so you will find that there are more resources dealing with that issue.</p> <p>So here are a few solutions that we have come up with:</p> <p>First, all solutions involve using the postgres <a href="http://www.postgresql.org/docs/8.3/static/sql-copy.html" rel="noreferrer">COPY command</a>. Using COPY to import data into postgres is by far the quickest method available. However, the JDBC driver by default does not currently support COPY accross the network socket. So, if you want to use it you will need to do one of two workarounds:</p> <ol> <li>A JDBC driver patched to support COPY, such as this <a href="http://kato.iki.fi/sw/db/postgresql/jdbc/copy/" rel="noreferrer">one</a>.</li> <li>If the data you are inserting and the database are on the same physical machine, you can write the data out to a file on the filesystem and then use the COPY command to import the data in bulk.</li> </ol> <p>Other options for increasing speed are using JNI to hit the postgres api so you can talk over the unix socket, removing indexes and the <a href="http://pgfoundry.org/projects/pgbulkload/" rel="noreferrer">pg_bulkload project</a>. However, in the end if you don't implement COPY you will always find performance disappointing.</p>
<p>You can obviously try to change the size of your batch to find the best size for your configuration, but I doubt that you will gain a factor 3.</p> <p>You could also try to tune your database structure. You might have better performances when using a single field as a primary key than using a composed PK. Depending on the level of integrity you need, you might save quite some time by deactivating integrity checks on your DB.</p> <p>You might also change the database you are using. MySQL is supposed to be pretty good for high speed simple inserts ... and I know there is a fork of MySQL around that tries to cut functionalities to get very high performances on highly concurrent access.</p> <p>Good luck !</p>
48,141
<p>I'm taking a course in computational complexity and have so far had an impression that it won't be of much help to a developer. </p> <p>I might be wrong but if you have gone down this path before, could you please provide an example of how the complexity theory helped you in your work? Tons of thanks.</p>
<p>O(1): Plain code without loops. Just flows through. Lookups in a lookup table are O(1), too.</p> <p>O(log(n)): efficiently optimized algorithms. Example: binary tree algorithms and binary search. Usually doesn't hurt. You're lucky if you have such an algorithm at hand.</p> <p>O(n): a single loop over data. Hurts for very large n.</p> <p>O(n*log(n)): an algorithm that does some sort of divide and conquer strategy. Hurts for large n. Typical example: merge sort</p> <p>O(n*n): a nested loop of some sort. Hurts even with small n. Common with naive matrix calculations. You want to avoid this sort of algorithm if you can.</p> <p>O(n^x for x>2): a wicked construction with multiple nested loops. Hurts for very small n. </p> <p>O(x^n, n! and worse): freaky (and often recursive) algorithms you don't want to have in production code except in very controlled cases, for very small n and if there really is no better alternative. Computation time may explode with n=n+1.</p> <p>Moving your algorithm down from a higher complexity class can make your algorithm fly. Think of Fourier transformation which has an O(n*n) algorithm that was unusable with 1960s hardware except in rare cases. Then Cooley and Tukey made some clever complexity reductions by re-using already calculated values. That led to the widespread introduction of FFT into signal processing. And in the end it's also why Steve Jobs made a fortune with the iPod.</p> <p>Simple example: Naive C programmers write this sort of loop:</p> <pre><code>for (int cnt=0; cnt &lt; strlen(s) ; cnt++) { /* some code */ } </code></pre> <p>That's an O(n*n) algorithm because of the implementation of strlen(). Nesting loops leads to multiplication of complexities inside the big-O. O(n) inside O(n) gives O(n*n). O(n^3) inside O(n) gives O(n^4). In the example, precalculating the string length will immediately turn the loop into O(n). <a href="http://www.joelonsoftware.com/articles/fog0000000319.html" rel="noreferrer">Joel has also written about this.</a></p> <p>Yet the complexity class is not everything. You have to keep an eye on the size of n. Reworking an O(n*log(n)) algorithm to O(n) won't help if the number of (now linear) instructions grows massively due to the reworking. And if n is small anyway, optimizing won't give much bang, too.</p>
<p>A good example could be when your boss tells you to do some program and you can demonstrate by using the computational complexity theory that what your boss is asking you to do is not possible.</p>
13,663
<p>I'm wondering where I find the source to show how the operator ** is implemented in Python. Can someone point me in the right direction? </p>
<p>The python grammar definition (from which the parser is generated using <a href="http://www.python.org/dev/peps/pep-0269/" rel="noreferrer">pgen</a>), look for 'power': <a href="http://svn.python.org/view/python/trunk/Grammar/Grammar?rev=65872&amp;view=markup" rel="noreferrer">Gramar/Gramar</a></p> <p>The python ast, look for 'ast_for_power': <a href="http://svn.python.org/view/python/trunk/Python/ast.c?rev=67590&amp;view=markup" rel="noreferrer">Python/ast.c</a></p> <p>The python eval loop, look for 'BINARY_POWER': <a href="http://svn.python.org/view/python/trunk/Python/ceval.c?rev=67666&amp;view=markup" rel="noreferrer">Python/ceval.c</a></p> <p>Which calls PyNumber_Power (implemented in <a href="http://svn.python.org/view/python/trunk/Objects/abstract.c?rev=66043&amp;view=markup" rel="noreferrer">Objects/abstract.c</a>):</p> <pre><code>PyObject * PyNumber_Power(PyObject *v, PyObject *w, PyObject *z) { return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); } </code></pre> <p>Essentially, invoke the <strong>pow</strong> slot. For long objects (the only default integer type in 3.0) this is implemented in the long_pow function <a href="http://svn.python.org/view/python/trunk/Objects/longobject.c?rev=65518&amp;view=markup" rel="noreferrer">Objects/longobject.c</a>, for int objects (in the 2.x branches) it is implemented in the int_pow function <a href="http://svn.python.org/view/python/trunk/Objects/intobject.c?rev=64753&amp;view=markup" rel="noreferrer">Object/intobject.c</a></p> <p>If you dig into long_pow, you can see that after vetting the arguments and doing a bit of set up, the heart of the exponentiation can be see here:</p> <pre><code>if (Py_SIZE(b) &lt;= FIVEARY_CUTOFF) { /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ for (i = Py_SIZE(b) - 1; i &gt;= 0; --i) { digit bi = b-&gt;ob_digit[i]; for (j = 1 &lt;&lt; (PyLong_SHIFT-1); j != 0; j &gt;&gt;= 1) { MULT(z, z, z) if (bi &amp; j) MULT(z, a, z) } } } else { /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ Py_INCREF(z); /* still holds 1L */ table[0] = z; for (i = 1; i &lt; 32; ++i) MULT(table[i-1], a, table[i]) for (i = Py_SIZE(b) - 1; i &gt;= 0; --i) { const digit bi = b-&gt;ob_digit[i]; for (j = PyLong_SHIFT - 5; j &gt;= 0; j -= 5) { const int index = (bi &gt;&gt; j) &amp; 0x1f; for (k = 0; k &lt; 5; ++k) MULT(z, z, z) if (index) MULT(z, table[index], z) } } } </code></pre> <p>Which uses algorithms discussed in <a href="http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf" rel="noreferrer">Chapter 14.6</a> of the <a href="http://www.cacr.math.uwaterloo.ca/hac/" rel="noreferrer">Handbook of Applied Cryptography</a> which describes efficient exponentiation algorithms for arbitrary precision arithmetic.</p>
<p>It's the power to operator</p> <p><a href="http://www.python.org/doc/2.5.2/ref/power.html" rel="nofollow noreferrer">python.org doc - Power operator</a></p> <p>Edit: Oh, dang, the code, right. Hope the link still helps. Sloppy read from my part</p>
46,173
<p>I have a SQL Server 2005 sp2 box where tempdb has either 8 data files or 5 data files dependingo n where you look. DBCC showfilestates and sys.database_files (both queried in tempdb) show 8 data files (tempdev - tempdev8), however when I query sys.master_files (in master db, which is also what the GUI uses), I only see 5 (tempdev, tempdev5 - tempdev8). I cannot add a tempdev2 - tempdev4 as I get an error that it already exists and I can't restart the SQL Server anytime soon to recreate tempdb.</p> <p>Anyone know: 1.) how this can happen? 2.) more importantly, how I can correct it?</p> <p>Thanks,</p>
<p>It's possible that one view is showing outdated information. One scenario is that those files were dropped from tempdb but SQL Server has not been restarted to delete those files our their entries from some of the system catalog. And you can't add new ones until the old ones are really gone. Anything destructive you do to tempdb (moving, dropping files, etc.) usually requires a restart of SQL Server.</p> <p>My guess is they are showing two different states of the system and will reconcile one the instance restarts.</p>
<p>The first question I have to ask is, why are you messing with tempdb? Are you experiencing bottlenecks because of tempdb?</p>
27,932
<p>I have an HTML wrapper that contains a Flex application, is there an Event that I can listen on, that is triggered when a user leaves the HTML wrapper either by navigation arrows or closing the browser?</p> <p>Thanks. </p>
<p>You can also listen for Event.ACTIVATE and Event.DEACTIVATE in Flash. All EventDispatchers receive these events when Flash/AIR gains or loses focus from the OS.</p> <p><a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/EventDispatcher.html#event:deactivate" rel="nofollow noreferrer">http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/EventDispatcher.html#event:deactivate</a></p> <p>This is very helpful for when you you provide a link that opens a new window and you want to reduce functionality and load (pause and mute a video for example) and then resume when the user comes back.</p>
<p>There is Body.onUnload, but i'm not sure how reliable it actually is.</p>
21,730
<p>I have a Trac project installed on top of a Subversion implementation (easy to do thanks to Webfaction's control panel), but now I have configuration work to do. With that in mind, are there <em>easy</em> ways to do the following in Trac:</p> <p>1) Ensure that customers can only see a high level progress indicator.<br> 2) Give daily summary reports on tickets, testing, and tasks.</p> <p>Also, I am interested in knowing if there are any <strong>highly</strong> recommended plugins that I would be sorry I forgot to install.</p>
<p>I would not recommend using the same Trac project for tracking development tasks and showing the customer progress. You want to be able to be candid with your development tickets, comments, etc. Customers can focus on the wrong things and misinterpret data you put in the tickets. I would recommend providing the customer with a separate project that contains high level tasks and only shows the progress on those tasks, not the nitty gritty.</p>
<p>@Dave Dunkin is right. Use Trac for your internal use, and use a system like <a href="http://www.basecamphq.com/" rel="nofollow noreferrer">Basecamp</a> to give your clients a high-level overview of what's going on in the project.</p>
23,504
<p>Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?</p>
<p><a href="http://www.w3schools.com/css/css_image_transparency.asp" rel="nofollow noreferrer">Here's some good information about image opacity and transparency with CSS</a>.</p> <p>So to make an image with opacity 50%, you'd do this:</p> <pre><code>&lt;img src="image.png" style="opacity: 0.5; filter: alpha(opacity=50)" /&gt; </code></pre> <p>The <strong>opacity:</strong> part is how Firefox does it, and it's a value between 0.0 and 1.0. <strong>filter:</strong> is how IE does it, and it's a value from 0 to 100.</p>
<p>The way I usually see things done with smaller images such as buttons it that only a certain portion of the image is shown. Then many states of the picture will make up a larger picture which gets shifted around behind the visible port. I'll delete this when someone has code.</p>
8,516
<p><strong>I was wondering if there was a .NET-compatible CLR that was implemented using the CLI</strong> (common language infrastructure), e.g., using .NET itself, or at least if there were any resources that would help with building one.</p> <p>Basically, something like a .NET program that loads assemblies as MemoryStreams, parses the bytecode, constructs the types, and executes the instructions. Optionally, it can JIT-compile to standard IL using Reflection.Emit or however. </p> <p><strong>I don't want to <em>compile</em> a .NET language to be run by the original CLR. I want a CLR that's <em>written</em> in a .NET language</strong> (not unmanaged C++ or C as it usually is) <strong>and <em>runs</em> CIL.</strong> If done right, it should be able to run itself.</p> <p>Any thoughts on using Mono.Cecil for this kind of thing?</p>
<p>I don't think there are currently any standalone .net VMs that are self hosting but both <a href="http://www.gocosmos.org" rel="noreferrer">Cosmos</a> and <a href="http://sharpos.org" rel="noreferrer">SharpOS</a> are .net runtimes written in C#.</p> <p>It may be possible to reuse some of their runtime code to extra a standalone runtime. Cosmos can be used to host a custom application on boot: <a href="http://www.codeproject.com/KB/system/CosmosIntro.aspx" rel="noreferrer">http://www.codeproject.com/KB/system/CosmosIntro.aspx</a></p>
<p>Look at the System.Reflection.Emit namespace, specifically the ILGenerator class.</p> <p>You can emit IL on the fly.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.ilgenerator_members.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.reflection.emit.ilgenerator_members.aspx</a></p>
18,236
<p>How would you append an integer to a <code>char*</code> in c++?</p>
<p>First convert the int to a <code>char*</code> using <code>sprintf()</code>:</p> <pre><code>char integer_string[32]; int integer = 1234; sprintf(integer_string, "%d", integer); </code></pre> <p>Then to append it to your other char*, use <code>strcat()</code>:</p> <pre><code>char other_string[64] = "Integer: "; // make sure you allocate enough space to append the other string strcat(other_string, integer_string); // other_string now contains "Integer: 1234" </code></pre>
<p>Something like:</p> <pre><code>width = floor(log10(num))+1; result = malloc(strlen(str)+len)); sprintf(result, "%s%*d", str, width, num); </code></pre> <p>You could simplify len by using the maximum length for an integer on your system.</p> <p><em>edit</em> oops - didn't see the "++". Still, it's an alternative.</p>
45,167
<p>Does anybody know how I can get the number of the elements (rows*cols) returned after I do an SQL query? If that can't be done, then is there something that's going to be relatively representative of the size of data I get back?</p> <p>I'm trying to make a status bar that indicates how much of the returned data I have processed, so I want to be somewhere relatively close. Any ideas?</p> <p>Please note that SQLRowCount only returns returns the number of rows affected by an UPDATE, INSERT, or DELETE statement; not the number of rows returned from a SELECT statement (as far as I can tell). So I can't multiply that directly to the SQLColCount.</p> <p>My last option is to have a status bar that goes back and forth, indicating that data is being processed.</p>
<p>That is frequently a problem when you wan to reserve dynamic memory to hold the entire result set. </p> <p>One technique is to return the count as part of the result set.</p> <pre><code>WITH data AS ( SELECT interesting-data FROM interesting-table WHERE some-condition ) SELECT COUNT(*), data.* from data </code></pre> <p>If you don't know beforehand what columns you are selecting or use a *, like the example above, then number of columns can be selected out of the USER_TAB_COLS table</p> <pre><code>SELECT COUNT(*) FROM USER_TAB_COLS WHERE TABLE_NAME = 'interesting-table' </code></pre>
<p>SQLRowCount can return the number of rows for SELECT queries if the driver supports it. Many drivers dont however, because it can be expensive for the server to compute this. If you want to guarantee you always have a count, you must use COUNT(*), thus forcing the server into doing the potentially time consuming calculation (or causing it to delay returning any results until the entire result is known). </p> <p>My suggestion would be to attempt SQLRowCount, so that the server or driver can decide if the number of rows is easily computable. If it returns a value, then multiply by the result from SQLNumResultCols. Otherwise, if it returns -1, use the back and forth status bar. Sometimes this is better because you can appear more responsive to the user.</p>
45,706
<p>I have a setup executable that I need to install. When I run it, it launches a msi to do the actual install and then dies immediately. The side effect of this is it will return control back to any console you call it from before the install finishes. Depending on what machine I run it on, it can take from three to ten minutes so having the calling script sleep is undesirable. I would launch the msi directly but it complains about missing components. </p> <p>I have a WSH script that uses WMI to start a process and then watch until it's pid is no longer running. Is there some way to determine the pid of the MSI the initial executable is executing, and then watch for that pid to end using WMI? Is the launching process information even associated with a process?</p>
<p>Would doing a WMI lookup of processes that have the initial setup as the parent process do the trick? For example, if I launch an MSI from a command prompt with process id 4000, I can execute the following command line to find information about msiexec process:</p> <pre><code>c:\&gt;wmic PROCESS WHERE ParentProcessId=4000 GET CommandLine, ProcessId CommandLine ProcessId "C:\Windows\System32\msiexec.exe" /i "C:\blahblahblah.msi" 2752 </code></pre> <p>That may be one way to find the information you need. Here is a demo of looking up that information in vbs:</p> <pre><code>Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") Set colProcesses = objWMIService.ExecQuery("select * from Win32_Process where ParentProcessId = 4000") For Each objProcess in colProcesses Wscript.Echo "Process ID: " &amp; objProcess.ProcessId Next </code></pre> <p>I hope this helps.</p>
<p>If you're using a .NET language (you can do it in Win32, but waaaay easier in .NET) you can enumerate all the Processes in the system (after your initial call to Setup.exe completes) and find all the processes which parent's PID equal to the PID of the Setup.exe - and then monitor all those processes. When they will complete - setup is complete. Make sure that they don't spawn any more child processes as well.</p>
13,203
<p>Is it possible to create a stored procedure as</p> <pre><code>CREATE PROCEDURE Dummy @ID INT NOT NULL AS BEGIN END </code></pre> <p>Why is it not possible to do something like this?</p>
<p>You could check for its NULL-ness in the sproc and <code>RAISERROR</code> to report the state back to the calling location. </p> <pre><code>CREATE proc dbo.CheckForNull @i int as begin if @i is null raiserror('The value for @i should not be null', 15, 1) -- with log end GO </code></pre> <p>Then call: </p> <pre><code>exec dbo.CheckForNull @i = 1 </code></pre> <p>or </p> <pre><code>exec dbo.CheckForNull @i = null </code></pre>
<p>Parameter validation is not currently a feature of procedural logic in SQL Server, and NOT NULL is only one possible type of data validation. The CHAR datatype in a table has a length specification. Should that be implemented as well? And how do you handle exceptions? There is an extensive, highly developed and somewhat standards-based methodology for exception handling in table schemas; but not for procedural logic, probably because procedural logic is defined out of relational systems. On the other hand, stored procedures already have an existing mechanism for raising error events, tied into numerous APIs and languages. There is no such support for declarative data type constraints on parameters. The implications of adding it are extensive; especially since it's well-supported, and extensible, to simply add the code:</p> <pre><code>IF ISNULL(@param) THEN raise error .... END IF </code></pre> <p>The concept of NULL in the context of a stored procedure isn't even well-defined especially compared to the context of a table or an SQL expression. And it's not Microsoft's definition. The SQL standards groups have spent a lot of years generating a lot of literature establishing the behavior of NULL and the bounds of the definitions for that behavior. And stored procedures isn't one of them.</p> <p>A stored procedure is designed to be as light-weight as possible to make database performance as efficient as possible. The datatypes of parameters are there not for validation, but to enable the compiler to give the query optimizer better information for compiling the best possible query plan. A NOT NULL constraint on a parameter is headed down a whole nother path by making the compiler more complex for the new purpose of validating arguments. And hence less efficient and heavier.</p> <p>There's a reason stored procedures aren't written as C# functions.</p>
42,787
<p>This seems to be an overlooked area that could really use some insight. What are your best practices for:</p> <ul> <li>making an upgrade procedure</li> <li>backing out in case of errors</li> <li>syncing code and database changes</li> <li>testing prior to deployment</li> <li>mechanics of modifying the table</li> </ul> <p>etc...</p>
<p>That's a great question. ( There is a high chance this is going to end up a normalised versus denormalised database debate..which I am not going to start... okay now for some input.)</p> <p>some off the top of my head things I have done (will add more when I have some more time or need a break)</p> <p>client design - this is where the VB method of inline sql (even with prepared statements) gets you into trouble. You can spend AGES just finding those statements. If you use something like Hibernate and put as much SQL into named queries you have a single place for most of the sql (nothing worse than trying to test sql that is inside of some IF statement and you just don't hit the "trigger" criteria in your testing for that IF statement). Prior to using hibernate (or other orms') when I would do SQL directly in JDBC or ODBC I would put all the sql statements as either public fields of an object (with a naming convention) or in a property file (also with a naming convention for the values say PREP_STMT_xxxx. And use either reflection or iterate over the values at startup in a) test cases b) startup of the application (some rdbms allow you to pre-compile with prepared statements before execution, so on startup post login I would pre-compile the prep-stmts at startup to make the application self testing. Even for 100's of statements on a good rdbms thats only a few seconds. and only once. And it has saved my butt a lot. On one project the DBA's wouldn't communicate (a different team, in a different country) and the schema seemed to change NIGHTLY, for no reason. And each morning we got a list of exactly where it broke the application, on startup.</p> <p>If you need adhoc functionality , put it in a well named class (ie. again a naming convention helps with auto mated testing) that acts as some sort of factory for you query (ie. it builds the query). You are going to have to write the equivalent code anyway right, just put in a place you can test it. You can even write some basic test methods on the same object or in a separate class.</p> <p>If you can , also try to use stored procedures. They are a bit harder to test as above. Some db's also don't pre-validate the sql in stored procs against the schema at compile time only at run time. It usually involves say taking a copy of the schema structure (no data) and then creating all stored procs against this copy (in case the db team making the changes DIDn't validate correctly). Thus the structure can be checked. but as a point of change management stored procs are great. On change all get it. Especially when the db changes are a result of business process changes. And all languages (java, vb, etc get the change )</p> <p>I usually also setup a table I use called system_setting etc. In this table we keep a VERSION identifier. This is so that client libraries can connection and validate if they are valid for this version of the schema. Depending on the changes to your schema, you don't want to allow clients to connect if they can corrupt your schema (ie. you don't have a lot of referential rules in the db, but on the client). It depends if you are also going to have multiple client versions (which does happen in NON - web apps, ie. they are running the wrong binary). You could also have batch tools etc. Another approach which I have also done is define a set of schema to operation versions in some sort of property file or again in a system_info table. This table is loaded on login, and then used by each "manager" (I usually have some sort of client side api to do most db stuff) to validate for that operation if it is the right version. Thus most operations can succeed, but you can also fail (throw some exception) on out of date methods and tells you WHY.</p> <p>managing the change to schema -> do you update the table or add 1-1 relationships to new tables ? I have seen a lot of shops which always access data via a view for this reason. This allows table names to change , columns etc. I have played with the idea of actually treating views like interfaces in COM. ie. you add a new VIEW for new functionality / versions. Often, what gets you here is that you can have a lot of reports (especially end user custom reports) that assume table formats. The views allow you to deploy a new table format but support existing client apps (remember all those pesky adhoc reports).</p> <p>Also, need to write update and rollback scripts. and again TEST, TEST, TEST...</p> <p>------------ OKAY - THIS IS A BIT RANDOM DISCUSSION TIME --------------</p> <p>Actually had a large commercial project (ie. software shop) where we had the same problem. The architecture was a 2 tier and they were using a product a bit like PHP but pre-php. Same thing. different name. anyway i came in in version 2....</p> <p>It was costing A LOT OF MONEY to do upgrades. A lot. ie. give away weeks of free consulting time on site. </p> <p>And it was getting to the point of wanting to either add new features or optimize the code. Some of the existing code used stored procedures , so we had common points where we could manage code. but other areas were this embedded sql markup in html. Which was great for getting to market quickly but with each interaction of new features the cost at least doubled to test and maintain. So when we were looking at pulling out the php type code out, putting in data layers (this was 2001-2002, pre any ORM's etc) and adding a lot of new features (customer feedback) looked at this issue of how to engineer UPGRADES into the system. Which is a big deal, as upgrades cost a lot of money to do correctly. Now, most patterns and all the other stuff people discuss with a degree of energy deals with OO code that is running, but what about the fact that your data has to a) integrate to this logic, b) the meaning and also the structure of the data can change over time, and often due to the way data works you end up with a lot of sub process / applications in your clients organisation that needs that data -> ad hoc reporting or any complex custom reporting, as well as batch jobs that have been done for custom data feeds etc.</p> <p>With this in mind i started playing with something a bit left of field. It also has a few assumptions. a) data is heavily read more than write. b) updates do happen, but not at bank levels ie. one or 2 a second say.</p> <p>The idea was to apply a COM / Interface view to how data was accessed by clients over a set of CONCRETE tables (which varied with schema changes). You could create a seperate view for each type operation - update, delete, insert and read. This is important. The views would either map directly to a table , or allow you to trigger of a dummy table that does the real updates or inserts etc. What i actually wanted was some sort of trappable level indirection that could still be used by crystal reports etc. NOTE - For inserts , update and deletes you could also use stored procs. And you had a version for each version of the product. That way your version 1.0 had its version of the schema, and if the tables changed, you would still have the version 1.0 VIEWS but with NEW backend logic to map to the new tables as needed, but you also had version 2.0 views that would support new fields etc. This was really just to support ad hoc reporting, which if your a BUSINESS person and not a coder is probably the whole point of why you have the product. (your product can be crap but if you have the best reporting in the world you can still win, the reverse is true - your product can be the best feature wise, but if its the worse on reporting you can very easily loose).</p> <p>okay, hope some of those ideas help.</p>
<p>As Pat said, use liquibase. Especially when you have several developers with their own dev databases making changes that will become part of the production database.</p> <p>If there's only one dev, as on one project I'm on now(ha), I just commit the schema changes as SQL text files into a CVS repo, which I check out in batches on the production server when the code changes go in.</p> <p>But liquibase is better organized than that!</p>
4,950
<p>I'm trying to convert an XML file into the markup used by dokuwiki, using XSLT. This actually works to some degree, but the indentation in the XSL file is getting inserted into the results. At the moment, I have two choices: abandon this XSLT thing entirely, and find another way to convert from XML to dokuwiki markup, or delete about 95% of the whitespace from the XSL file, making it nigh-unreadable and a maintenance nightmare.</p> <p>Is there some way to keep the indentation in the XSL file without passing all that whitespace on to the final document?</p> <p>Background: I'm migrating an autodoc tool from static HTML pages over to dokuwiki, so the API developed by the server team can be further documented by the applications team whenever the apps team runs into poorly-documented code. The logic is to have a section of each page set aside for the autodoc tool, and to allow comments anywhere outside this block. I'm using XSLT because we already have the XSL file to convert from XML to XHTML, and I'm assuming it will be faster to rewrite the XSL than to roll my own solution from scratch.</p> <p><i>Edit: Ah, right, foolish me, I neglected the indent attribute. (Other background note: I am new to XSLT.) On the other hand, I still have to deal with newlines. Dokuwiki uses pipes to differentiate between table columns, which means that all of the data in a table line must be on one line. Is there a way to suppress newlines being outputted (just occasionally), so I can do some fairly complex logic for each table cell in a somewhat readable fasion?</i></p>
<p>There are three reasons for getting unwanted whitespace in the result of an XSLT transformation:</p> <ol> <li>whitespace that comes from between nodes in the source document</li> <li>whitespace that comes from within nodes in the source document</li> <li>whitespace that comes from the stylesheet</li> </ol> <p>I'm going to talk about all three because it can be hard to tell where whitespace comes from so you might need to use several strategies.</p> <p>To address the whitespace that is between nodes in your source document, you should use <code>&lt;xsl:strip-space&gt;</code> to strip out any whitespace that appears between two nodes, and then use <code>&lt;xsl:preserve-space&gt;</code> to preserve the significant whitespace that might appear within mixed content. For example, if your source document looks like:</p> <pre><code>&lt;ul&gt; &lt;li&gt;This is an &lt;strong&gt;important&lt;/strong&gt; &lt;em&gt;point&lt;/em&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>then you will want to ignore the whitespace between the <code>&lt;ul&gt;</code> and the <code>&lt;li&gt;</code> and between the <code>&lt;/li&gt;</code> and the <code>&lt;/ul&gt;</code>, which is not significant, but preserve the whitespace between the <code>&lt;strong&gt;</code> and <code>&lt;em&gt;</code> elements, which <em>is</em> significant (otherwise you'd get "This is an **important***point*"). To do this use</p> <pre><code>&lt;xsl:strip-space elements="*" /&gt; &lt;xsl:preserve-space elements="li" /&gt; </code></pre> <p>The <code>elements</code> attribute on <code>&lt;xsl:preserve-space&gt;</code> should basically list all the elements in your document that have mixed content.</p> <blockquote> <p>Aside: using <code>&lt;xsl:strip-space&gt;</code> also reduces the size of the source tree in memory, and makes your stylesheet more efficient, so it's worth doing even if you don't have whitespace problems of this sort.</p> </blockquote> <p>To address the whitespace that appears within nodes in your source document, you should use <code>normalize-space()</code>. For example, if you have:</p> <pre><code>&lt;dt&gt; a definition &lt;/dt&gt; </code></pre> <p>and you can be sure that the <code>&lt;dt&gt;</code> element won't hold any elements that you want to do something with, then you can do:</p> <pre><code>&lt;xsl:template match="dt"&gt; ... &lt;xsl:value-of select="normalize-space(.)" /&gt; ... &lt;/xsl:template&gt; </code></pre> <p>The leading and trailing whitespace will be stripped from the value of the <code>&lt;dt&gt;</code> element and you will just get the string <code>"a definition"</code>.</p> <p>To address whitespace coming from the stylesheet, which is perhaps the one you're experiencing, is when you have text within a template like this:</p> <pre><code>&lt;xsl:template match="name"&gt; Name: &lt;xsl:value-of select="." /&gt; &lt;/xsl:template&gt; </code></pre> <p>XSLT stylesheets are parsed in the same way as the source documents that they process, so the above XSLT is interpreted as a tree that holds an <code>&lt;xsl:template&gt;</code> element with a <code>match</code> attribute whose first child is a text node and whose second child is a <code>&lt;xsl:value-of&gt;</code> element with a <code>select</code> attribute. The text node has leading and trailing whitespace (including line breaks); since it's literal text in the stylesheet, it gets literally copied over into the result, with all the leading and trailing whitespace.</p> <p>But <em>some</em> whitespace in XSLT stylesheets get stripped automatically, namely those between nodes. You don't get a line break in your result because there's a line break between the <code>&lt;xsl:value-of&gt;</code> and the close of the <code>&lt;xsl:template&gt;</code>.</p> <p>To get only the text you want in the result, use the <code>&lt;xsl:text&gt;</code> element like this:</p> <pre><code>&lt;xsl:template match="name"&gt; &lt;xsl:text&gt;Name: &lt;/xsl:text&gt; &lt;xsl:value-of select="." /&gt; &lt;/xsl:template&gt; </code></pre> <p>The XSLT processor will ignore the line breaks and indentation that appear between nodes, and only output the text within the <code>&lt;xsl:text&gt;</code> element.</p>
<p>Regarding your edit about new lines, you can use this template to recursively replace one string within another string, and you can use it for line breaks:</p> <pre><code>&lt;xsl:template name="replace.string.section"&gt; &lt;xsl:param name="in.string"/&gt; &lt;xsl:param name="in.characters"/&gt; &lt;xsl:param name="out.characters"/&gt; &lt;xsl:choose&gt; &lt;xsl:when test="contains($in.string,$in.characters)"&gt; &lt;xsl:value-of select="concat(substring-before($in.string,$in.characters),$out.characters)"/&gt; &lt;xsl:call-template name="replace.string.section"&gt; &lt;xsl:with-param name="in.string" select="substring-after($in.string,$in.characters)"/&gt; &lt;xsl:with-param name="in.characters" select="$in.characters"/&gt; &lt;xsl:with-param name="out.characters" select="$out.characters"/&gt; &lt;/xsl:call-template&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:value-of select="$in.string"/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:template&gt; </code></pre> <p>Call it as follows (this example replaces line breaks in the $some.string variable with a space):</p> <pre><code> &lt;xsl:call-template name="replace.string.section"&gt; &lt;xsl:with-param name="in.string" select="$some.string"/&gt; &lt;xsl:with-param name="in.characters" select="'&amp;#xA;'"/&gt; &lt;xsl:with-param name="out.characters" select="' '"/&gt; &lt;/xsl:call-template&gt; </code></pre>
22,298
<p>Is it good practice to have a unit test that specifies how long a certain function takes to return a value. I'm unit testing a curl function and want to specify that it needs to time out after 5 seconds. Is this in line with the way unit tests work?</p>
<p>Testing your function plus curl plus the server is more integration test than unit test. That being said, you don't have to be that dogmatic, if you only have one test like that this certainly is viable. I've written, and still have tests that are not pure unit tests, but they do their job. I'll keep them as far as they don't go in my way. </p> <p>The only thing I'd be bothered with is the five seconds timeout, which is very long for an unit test. Now, it depends on how often it occurs. Did you consider a basic test (e.g. pinging the server) prior launching curl to avoid starting a needless test. </p> <p>If you're looking for alternatives, what about splitting your test in two parts: 1/ test how curl is invoked ; 2/ test what your function does with the result ? That way you'll be isolated from the server and you won't need any timeout. </p>
<p>I think you should be mocking the method the function uses to detect that it has spent long enough waiting, then you can test the timeout instantly and not wait in real time.</p>
39,196
<p>If you're building an <code>AJA~Xy</code> app, are there any downsides to using <code>JSONP</code> requests/responses even if you're not planning on any <code>cross-domain</code> requests? </p> <p>The only thing I can think of is that there are a couple extra bytes for the callback wrapper... </p> <p><strong>Edit:</strong></p> <p>I found <a href="http://remysharp.com/2007/10/08/what-is-jsonp/" rel="nofollow noreferrer">this</a> which also suggests <code>security and error handling</code> as potential problems... </p> <blockquote> <p>There's no error handling. The <code>script injection</code> either works, or it doesn't. If there's an error from the <code>injection</code>, it'll hit the page, and short of a window wide error handler (bad, bad, very bad), you need to be sure the return value is valid on the <code>server side</code>.</p> </blockquote> <p>I don't think <code>error handling</code> is much of a problem... most of us would use a library to generate the <code>JSON</code>... the well-formedness of my response isn't a concern for this question.</p> <p><strong>and security:</strong></p> <blockquote> <p>There are documents out on the web that can help, but as a cursory check, I would check the referrer in the <code>server side</code> script.</p> </blockquote> <p>it seems like this is a potential problem with any type of response... certainly, there's nothing unique to <code>JSONP</code> in the security arena...?</p>
<p>Downside? It's fairly limited - you trigger a "GET" request and get back some script that's executed. You don't get error handling if your server throws an error, so you need to wrap all errors in JSON as well. You can't really cancel or retry the request. You're at the mercy of the various browser author opinions of "correct" behavior for dynamically-generated <code>&lt;script&gt;</code> tags. Debugging is somewhat more difficult. </p> <p>That said, i've used it on occasion, and haven't suffered. YMMV.</p>
<p>Here is another bit you may want to consider with JSONP.. possible memory leaks.. </p> <p><a href="http://neil.fraser.name/news/2009/07/27/" rel="nofollow noreferrer">http://neil.fraser.name/news/2009/07/27/</a></p>
3,965
<p>I'm looking for a GWT common purpose paging widget. So far I have found <a href="http://gwt-widget.sourceforge.net/" rel="nofollow noreferrer">GWT widget library</a> and the <a href="http://code.google.com/p/google-web-toolkit-incubator/w/list" rel="nofollow noreferrer">Google Incubator widgets</a>. Is there any other free (possibly open source) widget library implementing a paging behavior.</p>
<p>You found the two major ones. The Google Incubator widgets might be a good bet, because the intention is for these to eventually make it into the main library. In general the GWT widget library widgets tend to be fancier, but the GWT incubator library widgets tend to be more modular and also more robust across more web browsers.</p>
<p>This GXT library have a commercial lisence!</p>
28,649
<p>Is there a way to make stack trace to display the whole generated SQL statement when there is an error instead just the first few characters of it?</p> <p>This is what it currently displays</p> <blockquote> <p>...\Zend\Db\Adapter\Pdo\Abstract.php(220): Zend_Db_Adapter_Abstract->query('UPDATE "diction...', Array)</p> </blockquote> <p>..and I would like to see the whole update statement before sent to the db to track what is wrong with it.</p> <p>Thanks for the help. SWK</p>
<p>If you want to view the complete sql statement you can use Zend_Debug. For example if your sql statement is in the variable $select and you want to view the complete sql statement you can use the following line of code:</p> <pre><code>Zend_Debug::Dump($select); exit; </code></pre> <p>Or if your code is created withe the Zend_Db_Table class you can use:</p> <pre><code>$select = new Zend_Db_Select(Zend_Registry::get('db')); $select-&gt;from('string'); Zend_Debug::Dump($select-&gt;assemble()); exit; </code></pre> <p>I think the best way to view the sql statement is by using the profiling function on the database connection. This is combination withe the logging function and the firePHP add-on for Firefox is my favorite setup.</p> <p>If you use the MVC configuration of Zend Framework this is done white this lines of code:</p> <pre><code>// setup the database connection $db = Zend_Db::factory(Zend_Registry::get('config')-&gt;database-&gt;adapter,Zend_Registry::get('config')-&gt;database-&gt;params); // create a new profiler profiler = new Zend_Db_Profiler_Firebug('All DB Queries'); // enable profiling (this is only recommended in development mode, disable this in production mode) $profiler-&gt;setEnabled(true); // add the profiler to the database object $db-&gt;setProfiler($profiler); // setup the default adapter to use for database communication Zend_Db_Table_Abstract::setDefaultAdapter($db); // register the database object to access it in other parts of the project Zend_Registry::set('db',$db); /** * * This part is optional * * You can use this logger to log debug information to the firephp add-on for Firefox * This is handy for debugging but must be disabled in production mode * */ // create logger $logger = new Zend_Log(); // create firebug writer $firebug_writer = new Zend_Log_Writer_Firebug(); // add writer to logger $logger-&gt;addWriter($firebug_writer); // register the logger object to access it in other parts of the project Zend_Registry::set('log',$logger); </code></pre> <p>The firebug add-on (requirement for firephp) can be found on this website: <a href="http://getfirebug.com/" rel="nofollow noreferrer">Firebug</a></p> <p>The FirePHP add-on can be found on this website: <a href="http://www.firephp.org/" rel="nofollow noreferrer">FirePHP</a></p> <p>Ivo Trompert</p>
<p>whilst the profiler is V cool - it doesn't help debug when the system throws an exception..</p> <p>check out this post on giving a more detailed stack trace inc full SQL</p> <p>ONLY TO BE USED IN DEV ENVIRONMENTS for obvious reasons</p> <p><a href="http://www.edmondscommerce.co.uk/blog/zend-framework/zend-framework-more-detailed-stack-trace/" rel="nofollow noreferrer">http://www.edmondscommerce.co.uk/blog/zend-framework/zend-framework-more-detailed-stack-trace/</a></p>
42,829
<p>I have a loop (for item in @dataset) and I want, in each iteration, to get different data from another table and make some operations that will be printed in the view. I cant't get this data from the dataset used in the loop.</p> <p>How can I do this according to MVC? I can put the code into the loop, in the view, but I think it's horrible.</p> <p>Must I use a helper for do this, and call the function from the view? </p>
<p>If you have one table, and want to get data from another table, usually this is in the situation of a <code>has_many</code> relation. For example, we have <code>@people</code> (<code>Person</code> model), and each person <code>has_many</code> addresses (<code>Address</code> model). In those cases the best thing to do is this</p> <pre><code># Controller @people = Person.find(:all, :include =&gt; :addresses) ... # View @people.each do |p| p.addresses.each do |address| ... </code></pre> <p>If your data is not just normal database tables (maybe you get it from a web service or so on), then a good thing to do is to build all the data in the controller ahead-of-time, then pass that to the view. Something like this</p> <pre><code># Controller @people = Person.find(:all) @people.each do |p| # attach loaded data to the person object in controller p.addresses = Address.load_from_somewhere_by_name(p.name) ... </code></pre> <p>This way the view code stays clean, like this:</p> <pre><code># View @people.each do |p| p.addresses.each do |address| ... </code></pre>
<ul> <li>Keep all the logic on your @dataset item inside the controller action</li> <li>Utilize methods in your models for the interaction with other model objects you need</li> <li>You should be left with only @dataset for your view that you can render in a partial.</li> </ul> <p>You would need to further explain your situation for any more of answer on that. What kind of operations and other models do you need to interact with? If you post your model associations I'm sure we could really square you away.</p> <p>Good luck!</p>
35,565
<p>I'm working on a design for a hierarchical database structure which models a catalogue containing products (this is similar to <a href="https://stackoverflow.com/questions/112866/database-schema-for-a-hierarchial-groups">this question</a>). The database platform is SQL Server 2005 and the catalogue is quite large (750,000 products, 8,500 catalogue sections over 4 levels) but is relatively static (reloaded once a day) and so we are only concerned about READ performance.</p> <p>The general structure of the catalogue hierarchy is:-</p> <ul> <li>Level 1 Section <ul> <li>Level 2 Section <ul> <li>Level 3 Section <ul> <li>Level 4 Section (products are linked to here)</li> </ul></li> </ul></li> </ul></li> </ul> <p>We are using the Nested Sets pattern for storing the hierarchy levels and storing the products which exist at that level in a separate linked table. So the simplified database structure would be</p> <pre><code>CREATE TABLE CatalogueSection ( SectionID INTEGER, ParentID INTEGER, LeftExtent INTEGER, RightExtent INTEGER ) CREATE TABLE CatalogueProduct ( ProductID INTEGER, SectionID INTEGER ) </code></pre> <p>We do have an added complication in that we have about 1000 separate customer groups which may or may not see all products in the catalogue. Because of this we need to maintain a separate "copy" of the catalogue hierarchy for each customer group so that when they browse the catalogue, they only see their products and they also don't see any sections which are empty.</p> <p>To facilitate this we maintain a table of the number of products at each level of the hierarchy "rolled up" from the section below. So, even though products are only directly linked to the lowest level of the hierarchy, they are counted all the way up the tree. The structure of this table is </p> <pre><code>CREATE TABLE CatalogueSectionCount ( SectionID INTEGER, CustomerGroupID INTEGER, SubSectionCount INTEGER, ProductCount INTEGER ) </code></pre> <p><strong>So, onto the problem</strong> Performance is very poor at the top levels of the hierarchy. The general query to show the "top 10" products in the selected catalogue section (and all child sections) is taking somewhere in the region of 1 minute to complete. At lower sections in the hierarchy it is faster but still not good enough.</p> <p>I've put indexes (including covering indexes where applicable) on all key tables, run it through the query analyzer, index tuning wizard etc but still cannot get it to perform fast enough.</p> <p>I'm wondering whether the design is fundamentally flawed or whether it's because we have such a large dataset? We have a reasonable development server (3.8GHZ Xeon, 4GB RAM) but it's just not working :)</p> <p>Thanks for any help</p> <p>James</p>
<p>Use a closure table. If your basic structure is a parent-child with the fields ID and ParentID, then the structure for a closure table is ID and DescendantID. In other words, a closure table is an ancestor-descendant table, where each possible ancestor is associated with all descendants. You may include a LevelsBetween field if you need. Closure table implementations usually include self-referencing records, i.e. ID 1 is an ancestor of descendant ID 1 with LevelsBetween of zero.</p> <p>Example: Parent/Child<br> ParentID - ID<br> 1 - 2<br> 1 - 3<br> 3 - 4<br> 3 - 5<br> 4 - 6<br></p> <p>Ancestor/Descendant<br> ID - DescendantID - LevelsBetween<br> 1 - 1 - 0<br> 1 - 2 - 1<br> 1 - 3 - 1<br> 1 - 4 - 2<br> 1 - 6 - 3<br> 2 - 2 - 0<br> 3 - 3 - 0<br> 3 - 4 - 1<br> 3 - 5 - 1<br> 3 - 6 - 2<br> 4 - 4 - 0<br> 4 - 6 - 1<br> 5 - 5 - 0<br></p> <p>The table is intended to eliminate recursive joins. You push the load of the recursive join into an ETL cycle that you do when you load the data once a day. That shifts it away from the query.</p> <p>Also, it allows variable-level hierarchies. You won't be stuck at 4.</p> <p>Finally, it allows you to slot products in non-leaf nodes. A lot of catalogs create "Miscellaneous" buckets at higher levels of the hierarchy to create a leaf-node to attach products to. You don't need to do that since intermediate nodes are included in the closure.</p> <p>As far as indexing goes, I would do a clustered index on ID/DescendantID.</p> <p>Now for your query performance. This takes a chunk out but not all. You mentioned a "Top 10". This implies ranking over a set of facts that you haven't mentioned. We need details to help tune those. Plus, this gets only gets the leaf-level sections, not the products. At the very least, you should have an index on your CatalogueProduct that orders by SectionID/ProductID. I would force Section to Product joins to be loop joins based on the cardinality you provided. A report on a catalog section would go to the closure table to get descendants (using a clustered index seek). That list of descendants would then be used to get products from CatalogueProduct using the index by looped index seeks. Then, with those products, you would get the facts necessary to do the ranking.</p>
<p>you might be able to solve the customer groups problem with roles and treeId's but you'll have to provide us with the query.</p>
46,353
<p>I'm using the JSP <a href="http://displaytag.sourceforge.net/11/" rel="nofollow noreferrer">displaytag</a> tag lib to create HTML tables. I'd like the user to able to click on a column header in order to sort the data. My JSP code is shown below:</p> <pre><code>&lt;display:table name="tableData" id="stat" sort="page"&gt; &lt;display:column property="name" title="Name" sortable="true"/&gt; &lt;display:column property="age" title="Age" sortable="true"/&gt; &lt;/display:table&gt; </code></pre> <p>I thought this would cause the data to be sorted on the client-side (in JavaScript), but what it actually does is create a broken hyperlink on the column header back to the server.</p> <p>Is it possible to use displaytag to sort data on the client-side? If so, how?</p> <p>Cheers, Don</p>
<p>As far as I know, this is not possible. JQuery's tablesorter may work for the small tables that it uses for its examples, but most tables have to come from an actual database. This hit is far too great to simply retrieve all the data before returning to the client with this information, and then allowing it to be sorted.</p> <p>Displaytag has a "requestURI" element for the tag that allows its requests to go to your configured url-handler. </p> <p>So, if you use this:</p> <pre><code>&lt;display:table requestURI="yourUrlMappedController.yourExtension" ...&gt; </code></pre> <p>This will allow for the stopgap solution of retrieving the data again from your controller.</p> <p>Ultimately, though, you'll want to eventually work out a strategy that uses the displaytag sorting parameters to use as options in your "order by" clause and page the data from the database instead of pulling it all at once. This is a tricky thing to do, but the upfront effort can be very rewarding in terms of performance.</p> <p>The displaytag site has three things you should always check for reference, just as an aside. The <a href="http://displaytag.sourceforge.net/11/displaytag/tagreference.html" rel="nofollow noreferrer">Tag Reference</a>, the <a href="http://displaytag.sourceforge.net/11/configuration.html" rel="nofollow noreferrer">Configuration Guide</a> and, of course, their (downloadable) <a href="http://displaytag.homeip.net/displaytag-examples-1.1/" rel="nofollow noreferrer">Live Examples.</a></p>
<p>Take a look at using <a href="http://jquery.com" rel="nofollow noreferrer">jquery</a> and its excellent <a href="http://tablesorter.com" rel="nofollow noreferrer">tablesorter</a> API. This will let you sort the table on the client side using Javascript.</p>
33,490
<p>How do you automatically start a service after running an install from a Visual Studio Setup Project?</p> <p>I just figured this one out and thought I would share the answer for the general good. Answer to follow. I am open to other and better ways of doing this.</p>
<p>Add the following class to your project.</p> <pre><code>using System.ServiceProcess; class ServInstaller : ServiceInstaller { protected override void OnCommitted(System.Collections.IDictionary savedState) { ServiceController sc = new ServiceController("YourServiceNameGoesHere"); sc.Start(); } } </code></pre> <p>The Setup Project will pick up the class and run your service after the installer finishes.</p>
<p>There is also another way which does not involve code. You can use the Service Control Table. Edit the generated msi file with orca.exe, and add an entry to the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa371634(v=vs.85).aspx" rel="nofollow noreferrer">ServiceControl Table</a>.</p> <p>Only the ServiceControl, Name,Event and Component_ columns are mandatory. The Component_ column contains the ComponentId from the File Table. (Select the File in the file table, and copy the Component_value to the ServiceControl table.)</p> <p>The last step is to update the value of StartServices to 6575 in table InstallExecutesequence. This is sufficient to start the service.</p> <p>By the way, the service install table allows you to configure the installer to install the windows service.</p>
26,146
<p>How do you create non scrolling div that looks like the MS Office 2007 ribbon on a web page without two sets of scroll bars. One for the window and one for the div.</p>
<p>Try this:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;Fixed Header/Full Page Content&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;style type="text/css"&gt; body, div { margin: 0; padding: 0; } body { /* Disable scrollbars and ensure that the body fills the window */ overflow: hidden; width: 100%; height: 100%; } #header { /* Provide scrollbars if needed and fix the header dimensions */ overflow: auto; position: absolute; width: 100%; height: 200px; } #main { /* Provide scrollbars if needed, position below header, and derive height from top/bottom */ overflow: auto; position: absolute; width: 100%; top: 200px; bottom: 0; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="header"&gt;HEADER&lt;/div&gt; &lt;div id="main"&gt; &lt;p&gt;FIRST&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;MAIN&lt;/p&gt; &lt;p&gt;LAST&lt;/p&gt; &lt;/div&gt; &lt;!--[if lt IE 7]&gt; &lt;script type="text/javascript"&gt; var elMain = document.getElementById('main'); setMainDims(); document.body.onresize = setMainDims; function setMainDims() { elMain.style.height = (document.body.clientHeight - 200) + 'px'; elMain.style.width = '99%' setTimeout("elMain.style.width = '100%'", 0); } &lt;/script&gt; &lt;![endif]--&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Basically, what you are doing is removing the scrollbars from the body and applying scrollbars to elements inside the document. That is simple. The trick is to get the <code>#main</code> div to size to fill the space below the header. This is accomplished in most browsers by setting both the <code>top</code> and the <code>bottom</code> positions and leaving the <code>height</code> unset. The result is that the top of the div is fixed below the header and the bottom of the div will always stretch to the bottom of the screen.</p> <p>Of course there is always IE6 there to make sure that we earn our paychecks. Prior to version 7 IE wouldn't derive dimensions from conflicting absolute positions. <a href="http://www.alistapart.com/articles/conflictingabsolutepositions" rel="noreferrer">Some people</a> use IE's css expressions to solve this problem for IE6, but these expressions literally evaluate on every mousemove, so I'm simply resizing the <code>#main</code> div on the resize event and hiding that block of javascript from other browsers using a conditional comment.</p> <p>The lines setting the width to 99% and the setTimeout to set it back to 100% fixes a little rendering oddity in IE6 that causes the horizontal scrollbar to appear occasionally when you resize the window.</p> <p><em>Note: You must use a doctype and get IE out of quirks mode.</em></p>
<p>You could alternatively use </p> <pre><code> &lt;div style='position:absolute;top:0px:left:0px;'&gt;Text&lt/div&gt;; </code></pre> <p>It will jamm the div on the top of the page, but if your page scrolls down it will stay there. </p>
32,043
<p>I've got a unfinished project that a developer just didn't finish and didn't leave any documentation about the installation process. I've downloaded the production directory to my windows machine (running InstantRails 2), I created the databases as required in the <code>database.yml</code> and I tried to run the <code>rake:db:migrate --trace</code> but I'm receiving the following error message:</p> <pre><code>(in D:/projects/broke2) ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:migrate rake aborted! uninitialized constant Admin D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:279:in `load_missing_constant' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:468:in `const_missing' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:480:in `const_missing' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:285:in `constantize' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:284:in `each' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:284:in `constantize' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/string/inflections.rb:143:in `constantize' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:481:in `migrations' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/mysql_adapter.rb:15:in `inject' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `each' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `inject' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `migrations' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:431:in `migrate' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99 D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `call' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `execute' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `each' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `execute' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:578:in `invoke_with_call_chain' D:/InstantRails-2.0-win/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:564:in `invoke' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2019:in `invoke_task' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `each' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1991:in `top_level' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1970:in `run' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1967:in `run' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/bin/rake:31 D:/InstantRails-2.0-win/ruby/bin/rake:19:in `load' D:/InstantRails-2.0-win/ruby/bin/rake:19 </code></pre> <p>I'm a regular Rails developer (it's not my first app) but I never saw this error and I don't have a clue where to start to debug.</p>
<p>Sometimes Rails will throw this error if there's a syntax error where Admin is defined.</p> <p>Try looking for admin.rb and make sure that it parses.</p> <p>Also, you may want to try running the migrations one at a time (<code>rake db:migrate VERSION=1</code>, etc.) to see if that helps you track down which migration causes the error, or if it is a problem simply booting the application.</p>
<p>It don't points me where i have a Admin constant. There is a way to check at least where should I look? my models, my controllers, etc?</p> <p>rake db:migrate VERSION=1, gives me a error already. As I told you, am I just trying to finish a project unfinished by another guy.</p> <p>How can i do a migration file per file?</p> <p>Regards,</p> <p>Victor</p>
26,993
<p>C# What is the easiest way to disable a control after 10 seconds? Using a Timer or a stopwatch? I'm new to both so thanks for the help.</p>
<p>I'm not sure how you'd expect stopwatch to help. A timer certainly sounds like the right answer to me. You should be aware that there are <a href="http://pobox.com/~skeet/csharp/threads/timers.shtml" rel="nofollow noreferrer">several different timers available</a> - in this case <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx" rel="nofollow noreferrer"><code>System.Windows.Forms.Timer</code></a> is probably the one you want for a WinForms app, or a <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer.aspx" rel="nofollow noreferrer"><code>System.Windows.Threading.DispatcherTimer</code></a> for WPF.</p>
<p>Use a timer. It suits your needs better.</p> <p>EDIT: As other have said, go with the <code>System.Windows.Forms.Timer</code></p>
35,152
<p>For various reasons a web application would be best suite a project that I am working on but I am worried about the user interface. There will be a lot of pick and choose options that could be handled by check lists, combo boxes, etc… and to a lesser extent their will be some free text fields. However, I am concerned about the usability of standard components because users will have to access the application from touchscreen computers that will be wall mounted in a manufacturing environment (i.e. they will be very dirty and poorly maintained).</p>
<p>We are currently in the process of rolling out an application that is exactly as you describe. There are a number of issues that you will run into.</p> <p>You will probably need a "Soft keyboard" at some point. We have not found a decent third party one, but they are not too difiicult to write yourself.</p> <p>If you want to implement any kind of keypress button that writes text into another control, you need to be able to call the SetStyle() method to ensure that focus does not change. We found that the Janus button controls did not allow us to make this change so we reverted back to the standard winforms button.</p> <p>I have not seen any existing component libraries that are designed specifically for touch screens. We have used a combination of the standard winforms controls and the Janus UI components.</p> <p>If I were starting again now though, I would start with WPF. It is such a huge improvement over Winforms that it would be an easy choice for me.</p> <p>If you are really stuck with doing it in a web browser, then I would consider Silverlight as a viable option. Personally, I would never touch HTML for an application where quick data entry is important.</p> <p>Don't forget about bar-code input, sooner or later someone is going to tell you they want to do input with a scanner.</p>
<p>You might want to take a look at Baobab Health's <a href="http://github.com/baobab/touchscreentoolkit" rel="nofollow noreferrer">open source touchscreen tookit</a>. It does a nice job converting an html form into a touchscreen interaction using only javascript. Documentation is a little light, but it might at least be a good starting point.</p>
16,230
<p>I want to prevent XSS attacks in my web application. I found that HTML Encoding the output can really prevent XSS attacks. Now the problem is that how do I HTML encode every single output in my application? I there a way to automate this?</p> <p>I appreciate answers for JSP, ASP.net and PHP.</p>
<p>You don't want to encode all HTML, you only want to HTML-encode any user input that you're outputting. </p> <p>For PHP: <a href="http://us.php.net/htmlentities" rel="nofollow noreferrer">htmlentities</a> and <a href="http://us.php.net/manual/en/function.htmlspecialchars.php" rel="nofollow noreferrer">htmlspecialchars</a></p>
<p>If you do actually HTML encode every single output, the user will see plain text of &amp;lt;html&amp;gt; instead of a functioning web app.</p> <p>EDIT: If you HTML encode every single input, you'll have problem accepting external password containing &lt; etc..</p>
8,311
<p>I have a query:</p> <p>UPDATE choices SET votes = votes + 1 WHERE choice_id = '$user_choice'</p> <p>But when I execute it in my script, the votes field is updated twice, so the votes will go from 4 to 6 instead to 5. It doesn't seem that it is getting called twice because I echo out stuff to test this and only get one echo. Is there a way to have it so PHP will only execute this query once per page "refresh"?</p> <p><strong>EDIT</strong>: Thanks for the responses, I'm using regular MySQL, no MySQLi or PDO. Another thing I found is that when doing the query, it works when you start out with 0 and update to 1, but then after that it goes 3, 5, 7, ...</p>
<p>There are several SQL interfaces for many different brands of database in PHP. You haven't shown the PHP code you use to execute the query, nor have you identified which brand of database you use.</p> <p>In some SQL interfaces in PHP, creating the statement implicitly executes the SQL. Then you have the opportunity to fetch results (if it was a SELECT statement). If your statement was a SELECT or DELETE, it's likely that no harm was done, though it's unnecessary to execute the statement twice. If your statement was an INSERT or UPDATE, though, you may find it has taken effect twice.</p> <p>For example, using PDO:</p> <pre><code>$pdo = new PDO(...options...); $stmt = $pdo-&gt;query('UPDATE ...'); // executes once $stmt-&gt;execute(); // executes a second time </code></pre>
<p>I just created the a database table to test this query, I must say it is running fine on my side.</p> <blockquote> <p>UPDATE <code>choices</code> SET <code>votes</code> = ( votes +1 ) WHERE <code>choice_id</code> = '1' </p> </blockquote> <p>I think the code my be executed twice in your application, can you try and print out the sql as it is being ran. You can also run the outputted sql statement natively against your database. </p> <p>To conclude , The sql statement is fine just double your application scripts.</p>
29,542
<p>As an example, Google App Engine uses Google Datastore, not a standard database, to store data. Does anybody have any tips for using Google Datastore instead of databases? It seems I've trained my mind to think 100% in object relationships that map directly to table structures, and now it's hard to see anything differently. I can understand some of the benefits of Google Datastore (e.g. performance and the ability to distribute data), but some good database functionality is sacrificed (e.g. joins).</p> <p>Does anybody who has worked with Google Datastore or BigTable have any good advice to working with them?</p>
<p>There's two main things to get used to about the App Engine datastore when compared to 'traditional' relational databases:</p> <ul> <li>The datastore makes no distinction between inserts and updates. When you call put() on an entity, that entity gets stored to the datastore with its unique key, and anything that has that key gets overwritten. Basically, each entity kind in the datastore acts like an enormous map or sorted list.</li> <li>Querying, as you alluded to, is much more limited. No joins, for a start.</li> </ul> <p>The key thing to realise - and the reason behind both these differences - is that Bigtable basically acts like an enormous ordered dictionary. Thus, a put operation just sets the value for a given key - regardless of any previous value for that key, and fetch operations are limited to fetching single keys or contiguous ranges of keys. More sophisticated queries are made possible with indexes, which are basically just tables of their own, allowing you to implement more complex queries as scans on contiguous ranges.</p> <p>Once you've absorbed that, you have the basic knowledge needed to understand the capabilities and limitations of the datastore. Restrictions that may have seemed arbitrary probably make more sense.</p> <p>The key thing here is that although these are restrictions over what you can do in a relational database, these same restrictions are what make it practical to scale up to the sort of magnitude that Bigtable is designed to handle. You simply can't execute the sort of query that looks good on paper but is atrociously slow in an SQL database.</p> <p>In terms of how to change how you represent data, the most important thing is precalculation. Instead of doing joins at query time, precalculate data and store it in the datastore wherever possible. If you want to pick a random record, generate a random number and store it with each record. There's a whole cookbook of this sort of tips and tricks <a href="https://web.archive.org/web/20090416113704/http://appengine-cookbook.appspot.com/" rel="nofollow noreferrer">here</a>.</p>
<p>Being rooted in the database world, a data store to me would be a giant table (hence the name "bigtable"). BigTable is a bad example though because it does a lot of other things that a typical database might not do, and yet it is still a database. Chances are unless you know you need to build something like Google's "bigtable", you will probably be fine with a standard database. They need that because they are handling insane amounts of data and systems together, and no commercially available system can really do the job the exact way they can demonstrate that they need the job to be done.</p> <p>(bigtable reference: <a href="http://en.wikipedia.org/wiki/BigTable" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/BigTable</a>)</p>
12,940
<p>I want to set the backgroun color for a GridViewColumn that is databound inside of a listview in WPF. I'm not sure how to ask this question being fairly new to WPF, otherwise I wouldn't have bothered all of you.</p> <p>I want to change the background color of the whole row, based on a bool flag in my databound object.</p> <p>In this case, I have, well, a "CaseDetail" object, that when there are internal notes "IsInternalNote" I want the color of the row to change.</p> <p>How can I pull this off in WPF?</p> <p>What I have now, ( very simple ), which does NOT change the color.</p> <pre><code>&lt;ListView ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" &gt; &lt;ListView.View&gt; &lt;GridView&gt; &lt;GridViewColumn DisplayMemberBinding="{Binding Date, StringFormat=MMM dd\, yyyy h:mm tt}" Header="Date" Width="Auto" /&gt; &lt;GridViewColumn DisplayMemberBinding="{Binding SubmittedBy}" Header="Submitted By" Width="Auto" /&gt; &lt;GridViewColumn Width="Auto" Header="Description" x:Name="colDesc"&gt; &lt;GridViewColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;ScrollViewer MaxHeight="80" Width="300"&gt; &lt;StackPanel Orientation="Vertical"&gt; &lt;TextBlock Text="{Binding Description}" TextWrapping="Wrap" /&gt; &lt;TextBlock Text="{Binding File.FileName}" TextWrapping="Wrap" /&gt; &lt;/StackPanel&gt; &lt;/ScrollViewer&gt; &lt;/DataTemplate&gt; &lt;/GridViewColumn.CellTemplate&gt; &lt;/GridViewColumn&gt; &lt;/GridView&gt; &lt;/ListView.View&gt; &lt;/ListView&gt; </code></pre>
<p>I ran into a few troubles trying to do this, ended up like so</p> <pre><code>&lt;ListBox ...&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Border x:Name="BGBorder"&gt; &lt;!-- --&gt; &lt;/Border&gt; &lt;DataTemplate.Triggers&gt; &lt;DataTrigger Binding="{Binding Path=DataContext.IsAborted, RelativeSource={RelativeSource TemplatedParent}}" Value="True"&gt; &lt;Setter Property="Background" TargetName="BGBorder" Value="Red"&gt; &lt;/Setter&gt; &lt;/DataTrigger&gt; &lt;/DataTemplate.Triggers&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>There may be alternatives, but once I had it working, I stopped looking :)</p>
<p>I haven't tested this yet so it might need some tweaks but you're going to want to trigger off the value to set your background color.</p> <pre><code>&lt;DataTemplate.Triggers&gt; &lt;Trigger Property="IsInternalNote" Value="True"&gt; &lt;Setter Property="Background" Value="Red" /&gt; &lt;/Trigger&gt; &lt;/DataTemplate.Triggers&gt; </code></pre>
44,914
<p>I would like to know how to write PHPUnit tests with Zend_Test and in general with PHP.</p>
<p>I'm using Zend_Test to completely test all controllers. It's quite simple to set up, as you only have to set up your bootstrap file (the bootstrap file itself should NOT dispatch the front controller!). My base test-case class looks like this:</p> <pre><code>abstract class Controller_TestCase extends Zend_Test_PHPUnit_ControllerTestCase { protected function setUp() { $this-&gt;bootstrap=array($this, 'appBootstrap'); Zend_Auth::getInstance()-&gt;setStorage(new Zend_Auth_Storage_NonPersistent()); parent::setUp(); } protected function tearDown() { Zend_Auth::getInstance()-&gt;clearIdentity(); } protected function appBootstrap() { Application::setup(); } } </code></pre> <p>where <code>Application::setup();</code> does all the setup up tasks which also set up the real application. A simple test then would look like this:</p> <pre><code>class Controller_IndexControllerTest extends Controller_TestCase { public function testShowist() { $this-&gt;dispatch('/'); $this-&gt;assertController('index'); $this-&gt;assertAction('list'); $this-&gt;assertQueryContentContains('ul li a', 'Test String'); } } </code></pre> <p>That's all...</p>
<p>I haven't used Zend_Test but I have written tests against apps using Zend_MVC and the like. The biggest part is getting enough of your bootstrap code in your test setup.</p>
9,138
<p>I need an encoder that can convert mp3 files to he-aac (aka aac+). So far the best one I have found is <a href="http://www.nero.com/eng/down-ndaudio.php" rel="nofollow noreferrer">nero aac encoder</a> . I have two problemes with it : - Only one input format : wav . It is a little bit slow to transform mp3 files to wav and then to he-aac. - a free license for <strong>non commercial</strong> use.</p> <p>Too bad ffmpeg does not support he-aac ... There is a commercial solution, <a href="https://flix.on2.com/" rel="nofollow noreferrer">on2 flix</a>, but it seems to be a golden hammer for the simple task I need to do.</p>
<p>Nero AAC is the only one as far as I know. Even if FAAC supported HE-AAC it would be useless, since as an encoder its pretty awfully designed and its quality is not even competitive with LAME, let alone a good AAC encoder.</p> <p>Kostya on the FFMPEG team is currently working on an AAC encoder but it has a long way to go--its not ready for primetime with LC-AAC, let alone HE-AAC (its not even committed to the repository yet). The first step before anything will be to get the ffmpeg decoder to support HE-AAC; currently it can only be decoded through FAAD.</p> <p>I don't believe there is <em>any</em> HE-AAC encoder on any platform with a more permissive license than Nero's at this point in time.</p>
<p>I don't have an idea about the quality, but I just found <a href="http://dgaapenc.berlios.de/en/" rel="nofollow noreferrer">enhAacPlusEnc</a></p>
10,718
<p>I am currently working with a developer who is experienced at Ms-SQL, but not much at MySQL. He has been cursing MySQL for having Bugs, and also being far harder to use.</p> <p>Is is because his experience has been so good with Management studio. It seems to me that his problems are with using phpMyAdmin.</p> <p>For example, he cites not being able to cross join and compare between tables of different structures using MySQL. Is the problem actually our choice of management tool, or does MySQL have these flaws that my developer thinks. I hope not, as I have just been blown away how fast doing various data management tasks have been in Studio Manager.</p>
<p>You should really check <a href="http://www.webyog.com" rel="noreferrer">SQLYog</a>. It's great, and has a community version.</p> <p><img src="https://i.stack.imgur.com/gGnji.png" alt="enter image description here"></p>
<p><a href="http://www.sqlpp.com/products/mysql-management/" rel="nofollow">VSQL++ for MySQL</a> is a powerful GUI database management tool for MySQL</p>
36,460
<p>There is a little circuit board, or breadboard or something <a href="http://reprap.org/wiki/Prusa_i3_Rework_Electronics_and_wiring#Wiring" rel="nofollow noreferrer">in the diagram of the wiring for the i3</a>.</p> <p>And it's mentioned that the z-axis motors need to be <a href="http://reprap.org/wiki/Prusa_i3_Rework_Electronics_and_wiring#Motors_wiring" rel="nofollow noreferrer">wired in parallel</a> but beyond that they don't give you much detail about parts or how the wires go in. </p> <p>Can someone provide me with some more detail on this?</p>
<p>In the diagram, they do show the wires connecting together, which is right. You can accomplish that just about any way you like, so long as you pair up the wires correctly from one motor to the other.</p> <p>I'm assuming both "Z" motors are the same type and have the same color-coding for their wires. If not, you'll need to figure out the correspondences first (you may want to post another question if you need a hand with that, since it's pretty specific and generally useful).</p> <p>Many control boards have "headers" sticking up, with 4 bare pins for each motor. Connectors that plug right onto those are readily available, such as at <a href="https://www.sparkfun.com/products/10364" rel="nofollow noreferrer">https://www.sparkfun.com/products/10364</a>.</p> <p>Some ways you can wire the motors in parallel:</p> <ul> <li><p>Some control boards, like my RAMPS 1.4, provide 2 sets of header pins next to the Z stepper driver board. In that case, just put a connector on each motor (if they're not there already), and plug them in next to each other.</p></li> <li><p>If there's just one set of header pins (or one Z-motor socket of some other kind) on your controller, make a "Y-cord" by soldering the wires from one connector (that plugs to the controller) to <em>2</em> 4 pin connectors, one to mate with each motor.</p></li> <li><p>Or you can skip the 2 extra connectors entirely, and just solder the motor wires to the wires from the connector: 2 reds to red, 2 blacks to black, or whatever.</p></li> <li><p>If your controller just has empty holes, either solder in header pins and do as above (preferred, IMHO), or wire directly into the holes, splicing the 2 sets of motor wires if there's only one set of holes.</p></li> </ul> <p>Motor and connector wires are wildly inconsistent, so make sure you get them sorted out right if they aren't already. The first thing is to check continuity: find 2 pairs of wires, which are the ends of two separate coils. If your motors have more than 4 wires it's trickier.</p> <p>With RAMPS (see handy diagram <a href="http://makerdev.com/blog/wp-content/uploads/2014/02/ramps_fanboard_annotations.jpg" rel="nofollow noreferrer">RAMPS 1.4 RepRap Arduino Mega Pololu shield</a>), </p> <p><a href="https://i.stack.imgur.com/A6lsT.jpg" rel="nofollow noreferrer" title="RAMPS 1.4 RepRap Arduino Mega Pololu shield"><img src="https://i.stack.imgur.com/A6lsT.jpg" alt="RAMPS 1.4 RepRap Arduino Mega Pololu shield" title="RAMPS 1.4 RepRap Arduino Mega Pololu shield"></a></p> <p>the 4 pins are commonly labelled (starting from the one nearest the power-supply end of the RAMPS board):</p> <pre><code>2B 2A 1A 1B </code></pre> <p>It means coil 1 and coil 2, each of which has ends A and B. I find this unclear because it could just as well have been numbers for the coils, and letters for the ends (if you wire it that way it won't work). So be sure you have continuity (maybe 15 ohms or so) between the wires you connect to 2B and 2A, and between the wires you connect to 1A and 1B.</p> <p>The <em>really good thing</em> about this pin order is that if a motor is running backwards all you have to do is power off and then turn the plug around. That's one reason I think it's important to keep connectors in there, rather than soldering directly.</p>
<p>For some unknown reason, everywhere everybody is saying that Z stepper motors need to be connected in parallel... And this was always the only obvious way, until recently some people started to connect these motors in series.</p> <p>And I personally started to believe the right way is to connect them in series.</p> <p>All stepstick drivers are some kind of current limiting devices (you could read more about chopper mode). It is all about current. Connecting in series will guarantee that both motors receive the same current in all situations. And as result you could expect the same behaviour from both of them.</p> <p>The bad thing when they are in parallel, is that the motor with the bigger load will get more current and as a result the other one will get less current and could skip steps. Of course, in an ideal situation, this should never happen but don't forget about Murphy's law ("whatever can go wrong, will go wrong").</p> <p>One more thing - why did I change my wiring and connected my Z motors in series: At some moment I found that one Z motor was disconnected but the other one was working and this resulted in a broken printer geometry. When Z motors are in series and if one of them fails or disconnects, the other one will not work either. You will get always synchronous operation from both of them!</p> <p>I made this Z splitter that works fantastic: </p> <p><a href="https://i.stack.imgur.com/WM9F3.jpg" rel="noreferrer" title="Z splitter"><img src="https://i.stack.imgur.com/WM9F3.jpg" alt="Z splitter" title="Z splitter"></a></p>
171
<p>This is very interesting to me... This image displays perfectly well in Safari, but not at all in Firefox! Here's the relevant code:</p> <pre><code>&lt;div id="ad"&gt; &lt;p&gt;Advertisment&lt;/p&gt; &lt;img src="/ADS/fakead1.gif" /&gt; &lt;/div&gt; </code></pre> <p>With CSS:</p> <pre><code>#ad{color: #666;} #ad p{ font-size: .5em; text-align: center; padding: 0; margin: 0; } #ad img{ width: 9em; padding: .5em; margin: 0; } </code></pre> <p>Why would this code cause Firefox to simply <em>ignore</em> the image? (Again, it works perfectly fine with Safari.)</p>
<p>Wow, I'm not so smart...</p> <p>AdBlock Plus is smarter that I would have thought! I'll need to change the div name to something less obvious than "ad" (!)</p> <p>I should have known.</p> <p>A word to the wise: if you want your ad to get through, name the div in klingon.</p>
<p>it works for me here. its just your adblock i would say</p>
46,244
<p>I have a class library with some extension methods written in C# and an old website written in VB.</p> <p>I want to call my extension methods from the VB code but they don't appear in intelisense and I get compile errors when I visit the site.</p> <p>I have got all the required <em>Import</em>s because other classes contained in the same namespaces are appearing fine in Intelisense.</p> <p>Any suggestions</p> <p><strong>EDIT:</strong> More info to help with some comments.</p> <p>my implementation looks like this </p> <pre><code>//C# code compiled as DLL namespace x.y { public static class z { public static string q (this string s){ return s + " " + s; } } } </code></pre> <p>and my usage like this </p> <pre><code>Imports x.y '...' Dim r as string = "greg" Dim s as string = r.q() ' does not show in intelisense ' and throws error : Compiler Error Message: BC30203: Identifier expected. </code></pre>
<p>It works for me, although there are a couple of quirks. First, I created a C# class library targeting .NET 3.5. Here's the only code in the project:</p> <pre><code>using System; namespace ExtensionLibrary { public static class Extensions { public static string CustomExtension(this string text) { char[] chars = text.ToCharArray(); Array.Reverse(chars); return new string(chars); } } } </code></pre> <p>Then I created a VB console app targeting .NET 3.5, and added a reference to my C# project. I renamed Module1.vb to Test.vb, and here's the code:</p> <pre><code>Imports ExtensionLibrary Module Test Sub Main() Console.WriteLine("Hello".CustomExtension()) End Sub End Module </code></pre> <p>This compiles and runs. (I would have called the method Reverse() but I wasn't sure whether VB might magically have reverse abilities already somewhere - I'm not a VB expert by a long chalk.)</p> <p>Initially, I wasn't offered ExtensionLibrary as an import from Intellisense. Even after building, the "Imports ExtensionLibrary" is greyed out, and a lightbulb offers the opportunity to remove the supposedly redundant import. (Doing so breaks the project.) It's possible that this is ReSharper rather than Visual Studio, mind you.</p> <p>So to cut a long story short, it can be done, and it should work just fine. I don't suppose the problem is that you're either using an old version of VB or your project isn't targeting .NET 3.5?</p> <p>As noted in comments: there's one additional quirk, which is that <a href="https://stackoverflow.com/questions/3227888">extension methods won't be found when the compile-time type of the target is <code>Object</code></a>.</p>
<p>This was quite a while ago and I can't really how I solved it, but needless to say, it was user error. I probably restarted my computer and away it went.</p>
26,183
<p>In SQL, How we make a check to filter all row which contain a column data is null or empty ?<br> For examile </p> <pre><code>Select Name,Age from MEMBERS </code></pre> <p>We need a check Name should not equal to null or empty.</p>
<p>This will work in all sane databases (<em>wink, wink</em>) and will return the rows for which name is not null nor empty</p> <pre><code>select name,age from members where name is not null and name &lt;&gt; '' </code></pre>
<p>nvl(Name, 'some dumb string') this will return Name if Name is not null and different of '' (oracle, don't know for others). It will be equal to 'some dumb string' if null or equal to ''.</p>
42,130
<p>In low latency trading applications we are very conscious of latency issues. There is some concern that our application may experience increased latency if the server on which it is running changes PowerNow state.</p> <p>Any kernel developers familiar with calling PowerNow changes and how much processor time is used for the operation and what the latency/delay characteristics are like?</p> <p>The same information for Intel SpeedStep would be useful but PowerNow is what we actually use.</p> <p>Thanks!</p>
<p>The Linux kernel appears to assume an upper bound of a fifth of a millisecond for a PowerNow state change operation to complete.</p> <p>I would have thought a bigger worry than the cost of the state change itself, though, would be that downclocking the CPU will make your application run slower, increasing latency across the board.</p>
<p>I doubt it has any latency. PowerNow just lowers core frequency and core voltage. I don't know that it will halt the CPU for a short time to do so and then resume processing after the change. AFAIK the change happens on the fly, the processing is not interrupted for that.</p> <p>Thus the bigger problem might be that you rely on a certain speed (e.g. you assume the processor can perform that many operations a second), however when the core frequency is lowered, it will behave like a slower CPU (less operations per second) and the core frequency doesn't jump to max just because the CPU is not 100% idle. It will jump up again, when the CPU thinks it needs more processing power than it currently has.</p> <p>On Linux PowerNow can cause bad issues if you run VMWare with Windows on it. Windows fails to correctly update the internal clock, as it seems to not detect that PowerNow is in effect (I guess because it runs within a virtual machine) and VMWare for Linux fails to handle the situation correctly as well. So the Windows clock will fall behind as soon as PowerNow is active and every now and then VMWare detects that and corrects the clock again. So far so well, but applications relying on the Windows clock will see this strange jump and behave rather oddly (e.g. a radio streaming software I know will jump within the MP3 stream and skip a couple of milliseconds every time the clock is resynced).</p> <p>If your application depends strongly on a steady program flow, you may like to disable the PowerNow feature completely. With the Internet radio stream software, that was the only way to solve the skipping issue.</p>
19,101
<p>As you work in a legacy codebase what will have the greatest impact over time that will improve the quality of the codebase?</p> <ul> <li>Remove unused code</li> <li>Remove duplicated code </li> <li>Add unit tests to improve test coverage where coverage is low</li> <li>Create consistent formatting across files</li> <li>Update 3rd party software</li> <li>Reduce warnings generated by static analysis tools (i.e.Findbugs)</li> </ul> <p>The codebase has been written by many developers with varying levels of expertise over many years, with a lot of areas untested and some untestable without spending a significant time on writing tests.</p>
<ul> <li>Read Michael Feather's book <a href="https://rads.stackoverflow.com/amzn/click/com/0131177052" rel="noreferrer" rel="nofollow noreferrer">"Working effectively with Legacy Code"</a></li> </ul> <p>This is a GREAT book.</p> <p>If you don't like that answer, then the best advice I can give would be:</p> <ul> <li>First, stop making new legacy code[1]</li> </ul> <p>[1]: Legacy code = code without unit tests and therefore an unknown </p> <p>Changing legacy code without an automated test suite in place is dangerous and irresponsible. Without good unit test coverage, you can't possibly know what affect those changes will have. Feathers recommends a "stranglehold" approach where you isolate areas of code you need to change, write some basic tests to verify basic assumptions, make small changes backed by unit tests, and work out from there.</p> <p>NOTE: I'm not saying you need to stop everything and spend weeks writing tests for everything. Quite the contrary, just test around the areas you need to test and work out from there. </p> <p>Jimmy Bogard and Ray Houston did an interesting screen cast on a subject very similar to this: <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/05/06/pablotv-eliminating-static-dependencies-screencast.aspx" rel="noreferrer">http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/05/06/pablotv-eliminating-static-dependencies-screencast.aspx</a></p>
<p>The single biggest thing that I've done to the legacy code that I have to work with is to build a real API around it. It's a 1970's style COBOL API that I've built a .NET object model around, so that all the unsafe code is in one place, all of the translation between the API's native data types and .NET data types is in one place, the primary methods return and accept DataSets, and so on.</p> <p>This was immensely difficult to do right, and there are still some defects in it that I know about. It's not terrifically efficient either, with all the marshalling that goes on. But on the other hand, I can build a DataGridView that round-trips data to a 15-year-old application which persists its data in Btrieve (!) in about half an hour, and it works. When customers come to me with projects, my estimates are in days and weeks rather than months and years.</p>
17,691
<p>I'm a doing some blackbox testing of a ASP.Net website and I need to test different session timeout scenarios. </p> <p>I'm not sure they fully encapsulated session timeouts. Other then leaving a page open for 20 minutes is there an easier way to force a session timeout?</p>
<p><strong>Decrease the timeout</strong></p> <p>The easiest and most non-intrusive way to test this is probably to just decrease the timeout to a fairly small number, such as 3 or 5 minutes. This way you can pause for a few minutes to simulate a longer pause without worrying about application restarts or special reset code having any affect on your test results.</p> <p>You can modify the session state timeout in a few locations - globally (in the web.config located in the config folder for the applicable .NET framework version), or just for your application.</p> <p>To modify the timeout just for your application, you can add the following to your application's web.config:</p> <pre><code> &lt;system.web&gt; &lt;sessionState timeout="60" /&gt; ... </code></pre> <p>Alternatively, you can also modify this same setting for your application through an IIS configuration dialog (I believe you still need to have a web.config defined for your application though, otherwise Edit Configuration will be disabled).</p> <p>To access this, right-click on your web application in IIS, and navigate to Properties | ASP.NET tab | Edit Configuration | State Management tab | Session timeout (minutes).</p> <p>Note that you can also manipulate this setting through code - if this is already being done, than the setting in the web.config file will effectively be ignored and you will need to use another technique.</p> <p><strong>Call Session.Abandon()</strong></p> <p>A slightly more intrusive technique than setting a low timeout would be to call Session.Abandon(). Be sure to call this from a page separate from your application though, as the session isn't actually ended until all script commands on the current page are processed.</p> <p>My understanding is that this would be a fairly clean way to test session timeouts without actually waiting for them.</p> <p><strong>Force an application restart</strong></p> <p>In a default configuration of session state, you can simulate a session timeout by blowing away the sessions entirely by causing the application to restart. This can be done several ways, a few of which are listed below:</p> <ul> <li>Recycle the app pool through <ul> <li>the IIS MMC snap-in</li> <li>the command-line (iisapp /a AppPoolID /r)</li> <li>modifying web.config, global.asax, or a dll in the bin directory</li> </ul></li> <li>Restart IIS through <ul> <li>the IIS MMC snap-in</li> <li>services.msc and restarting the IIS Admin service</li> <li>the command-line (iisreset)</li> </ul></li> </ul> <p>When I mention "default configuration", I mean a web application that is configured to use "InProc" session state mode. There are others modes that can actually maintain session state even if the web application is restarted (StateServer, SQLServer, Custom).</p> <p><strong>Tamper with the state tracking mechanism</strong></p> <p>Assuming your web application isn't configured with a "cookie-less" mode (by default, cookies will be used), you could remove the cookie containing the session ID from the client browser.</p> <p>However, my understanding is that this isn't really simulating a time-out, as the server will still be aware of the session, it just won't see anyone using it. The request without a session ID will simply be treated as an unseen request in need of a new session, which may or may not be what you want to test.</p>
<p>You have two options:-</p> <p>1- Decrease the session timeout in web.config. 2- Restart IIS or Application pool.</p>
22,348
<p>A client has installed Sql server 2005 reporting services. When we go to the web bit at <code>http://servername/reports/</code> we just see a blank screen like: <img src="https://i.stack.imgur.com/nGQXH.jpg" alt="http://img91.imageshack.us/img91/3787/rsblankqx4.jpg"></p> <p>We are using windows authentication and I think it has authenticated us as the "site settings" button is appearing and we can alter site security, add to roles etc. </p> <p>I have had this before and cant remember how I fixed it. </p> <p>Any ideas?</p> <p>Thanks,</p> <p>Alex</p>
<p>I don't recognize that magic number, and neither does <a href="http://en.wikipedia.org/wiki/Magic_number_(programming)" rel="nofollow noreferrer">Wikipedia</a>. I would guess that some code in your program (or in a library you're using) is using <code>memset()</code> and hitting your pointer. Have you grepped your code base case-insensitively for the string "0x7c"?</p>
<p>0x7c7c = 01111100 01111100 in binary. That could be one of those "most difficult to read" bit patterns that format utilities fill unused space on hard drives with.</p>
46,905
<p>I have a table with doctor offices and doctors in those offices that I'm populating to a repeater control. The data coming back is not aggregated. So, if there are 2 doctors in 1 office, there are 2 rows, same office, different doctor. </p> <p>Is there a way to aggregate the data so the repeater shows 1 office with all of the doctors from that office so I can avoid the duplication?</p>
<p>In your aspx markup:</p> <pre><code>&lt;table&gt;&lt;tr&gt;&lt;th&gt;Office&lt;/th&gt;&lt;th&gt;Doctors&lt;/th&gt;&lt;/tr&gt; &lt;asp:repeater id="Repeater" runat="server" OnItemDataBound="NextItem" ... &gt; &lt;ItemTemplate&gt;&lt;asp:Literal id="RepeaterRow" runat="server" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:repeater&gt; &lt;asp:Literal id="LastRow" runat="server" /&gt; &lt;/table&gt; </code></pre> <p>In your code behind:</p> <pre><code>public class Office { public string OfficeName {get;set;}; List&lt;string&gt; _doctors = new List&lt;string&gt;(); public List&lt;string&gt; Doctors {get{ return _doctors; } }; void Clear() { OfficeName = ""; _doctors.Clear(); } public override string ToString() { StringBuilder result = new StringBuilder("&lt;tr&gt;"); result.AppendFormat("&lt;td&gt;{0}&lt;/td&gt;", OfficeName); string delimiter = ""; result.Append("&lt;td&gt;"); foreach(string doctor in Doctors) { result.Append(doctor).Append(delimiter); delimiter = "&lt;br/&gt;"; } result.Append("&lt;/td&gt;&lt;/tr&gt;"); return result.ToString(); } } </code></pre> <p>. </p> <pre><code>private string CurOffice = ""; private Office CurRecord = new Office(); void NextItem(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType != ListItemType.Item &amp;&amp; e.Item.ItemType != ListItemType.AlternatingItem) return; Literal repeaterRow = e.Item.FindControl("RepeaterRow") as Literal; if (repeaterRow == null) return; DataRow row = ((DataRowView)e.Item.DataItem).Row; if ( CurOffice != (string)row["Office"] ) { repeaterRow.Text = CurRecord.ToString(); repeaterRow.Visible = true; CurRecord.Clear(); CurOffice = row["Office"]; CurRecord.Office = CurOffice; } else e.Item.Visible = false; CurRecord.Doctors.Add((string)row["doctor"]); } void Page_PreRender(object sender, EventArgs e) { LastRow.Text = CurRecord.ToString(); } </code></pre>
<p>I think you'd be best doing the aggregation in the database.</p>
48,193
<p>This seems very noisy to me. Five lines of overhead is just too much.</p> <pre><code>m_Lock.EnterReadLock() Try Return m_List.Count Finally m_Lock.ExitReadLock() End Try </code></pre> <p>So how would you simply this?</p>
<p>I was thinking the same, but in C# ;-p</p> <pre><code>using System; using System.Threading; class Program { static void Main() { ReaderWriterLockSlim sync = new ReaderWriterLockSlim(); using (sync.Read()) { // etc } } } public static class ReaderWriterExt { sealed class ReadLockToken : IDisposable { private ReaderWriterLockSlim sync; public ReadLockToken(ReaderWriterLockSlim sync) { this.sync = sync; sync.EnterReadLock(); } public void Dispose() { if (sync != null) { sync.ExitReadLock(); sync = null; } } } public static IDisposable Read(this ReaderWriterLockSlim obj) { return new ReadLockToken(obj); } } </code></pre>
<p>I ended up doing this, but I'm still open to better ways or flaws in my design.</p> <pre><code>Using m_Lock.ReadSection Return m_List.Count End Using </code></pre> <p>This uses this extension method/class:</p> <pre><code>&lt;Extension()&gt; Public Function ReadSection(ByVal lock As ReaderWriterLockSlim) As ReadWrapper Return New ReadWrapper(lock) End Function Public NotInheritable Class ReadWrapper Implements IDisposable Private m_Lock As ReaderWriterLockSlim Public Sub New(ByVal lock As ReaderWriterLockSlim) m_Lock = lock m_Lock.EnterReadLock() End Sub Public Sub Dispose() Implements IDisposable.Dispose m_Lock.ExitReadLock() End Sub End Class </code></pre>
20,523
<p>What is the best way to extract the MAC address from <code>ifconfig</code>'s output?</p> <p>Sample output:</p> <pre><code>bash-3.00# ifconfig eth0 eth0 Link encap:Ethernet HWaddr 1F:2E:19:10:3B:52 inet addr:127.0.0.66 Bcast:127.255.255.255 Mask:255.0.0.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 .... .... </code></pre> <p>Should I use cut, <a href="http://en.wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a> or anything else, and what are the merits and demerits of one method over the other.</p>
<p>You can do a cat under <code>/sys/class/</code> </p> <pre><code>cat /sys/class/net/*/address </code></pre> <p>Specifically for <code>eth0</code></p> <pre><code>cat /sys/class/net/eth0/address </code></pre>
<p>Output of ifconfig:</p> <pre><code>$ifconfig eth0 Link encap:Ethernet HWaddr 00:1b:fc:72:84:12 inet addr:172.16.1.13 Bcast:172.16.1.255 Mask:255.255.255.0 inet6 addr: fe80::21b:fcff:fe72:8412/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:638661 errors:0 dropped:20 overruns:0 frame:0 TX packets:93858 errors:0 dropped:0 overruns:0 carrier:2 collisions:0 txqueuelen:1000 RX bytes:101655955 (101.6 MB) TX bytes:42802760 (42.8 MB) Memory:dffc0000-e0000000 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:3796 errors:0 dropped:0 overruns:0 frame:0 TX packets:3796 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:517624 (517.6 KB) TX bytes:517624 (517.6 KB) </code></pre> <p>The best way to extract MAC address is:</p> <pre><code>ifconfig | sed '1,1!d' | sed 's/.*HWaddr //' | sed 's/\ .*//' | sed -e 's/:/-/g' &gt; mac_address </code></pre>
30,510
<p>I am developing a .NET application which uses a few projects that I've pieced together from other internal projects. I was thinking about merging the .exe and the DLLS into a single executable file with a tool called <a href="http://research.microsoft.com/~mbarnett/ilmerge.aspx" rel="nofollow noreferrer">ILMerge</a>.</p> <p>I may be sending the executable outside the company, so merging everything into a single file would be easier to pass out. But, I was wondering if there are any downsides to merging DLLs with the executable? </p>
<p>As long as they're your libraries, I don't think there's any big problem with it. Unless it makes the image absolutely and monstrously huge, I think it's better if the executable relies on itself as much as it can (exceptions being, of course, when you're replicating system functionality... no point in that).</p> <p>On the other hand, if the libraries don't actually belong to you, you had better make sure that their terms of use allow for this. You may not be allowed to package them up into your executable and distribute them as your own code (even if you give your product away and the library was "free", you may still have to acknowledge that you use it some how so make sure to check the terms of use for <em>all</em> the libraries you include).</p>
<p>Many of the advantages of shared libraries stem from the fact that they are in fact shared. Do you have other applications which use the same DLLs which are also distributed publicly or might be in the future? If so, then sticking with the shared libraries can give several advantages. Typically, only one copy of the library is stored in memory, even if multiple applications use it, so it can reduce memory usage. It also simplifies upgrades, as a change to the library will only affect the DLL itself, where as if it is statically linked into one or more applications, they must all be upgraded when the library changes.</p> <p>It's been a while since I did much with .NET, but I was always fairly happy with the GAC and support for library versioning it provided. Do you have a compelling reason to <em>not</em> use shared libraries? I suspect that in most cases, reducing the application to a single file is not enough of a convenience to outweigh the potential advantages.</p>
38,520
<p>What tools do you use to develop Oracle stored procedures, in a team :</p> <ul> <li>To automatically "lock" the current procedure you are working with, so nobody else in the team can make changes to it until you are finished.</li> <li>To automatically send the changes you make in the stored procedure, in an Oracle database, to a Subversion, CVS, ... repository</li> </ul> <p>Thanks!</p>
<p>I'm not sure if the original poster is still monitoring this, but I'll ask the question anyways.</p> <p>The original post requested to be able to:</p> <blockquote> <p>To automatically "lock" the current procedure you are working with, so nobody else in the team can make changes to it until you are finished.</p> </blockquote> <p>Perhaps the problem here is one of development paradigm more than the inability of a product to "lock" the stored proc. Whenever I hear "I want to lock this so noone else changes it" I immediately get the feeling that people are sharing a schema and everyone is developing in the same space.</p> <p>If this is the case, why not simply let everyone have their own schema with a copy of the data model? I mean seriously folks, it doesn't "cost" anything to create another schema. That way, each developer can make changes until they're blue in the face without affecting anyone else. </p> <p>Another trick I've used in the past (on small teams) when it wasn't feasible to let every developer have their own copy of the data because of size, was to have a master schema with all the tables and code in it, with public synonyms pointing to it all. Then, if the developer wants to work on a stored proc, he simply creates it in <em>his</em> schema. That way Oracle name resolution finds that one first instead of the copy in the master schema, allowing them to test their code without affecting anyone else. This does have it's drawbacks, but this was a very specific case where we could live with them. I would NEVER implement something like this in production obviously.</p> <p>As for the second requirement:</p> <blockquote> <p>To automatically send the changes you make in the stored procedure, in an Oracle database, to a Subversion, CVS, ... repository</p> </blockquote> <p>I'd be surprised to find tools out there smart enough to do this (perhaps an opportunity :). It would have to connect to your db, query the data dictionary (USER_SOURCE) and pull out the associated text. A tall order for source control systems where are almost universally file based.</p>
<p>Toad also does this without requiring CVS / SVN.</p>
13,705
<p>I have a page which work like a navigation and a iframe in this page which show the content. </p> <p>Now there are some situation when the inner page is directly shown in the browser. eg: if somebody types the inner page's url in the browser address bar, the page is displayed in the window. </p> <p>I want to prevent this. </p> <p>Better still, I would like to redirect to any other page.</p>
<p><b>window.parent</b>: The window object that contains the frame. If the the window is the top level window then window.parent refers the window itself. (It is never null.)</p> <p><b>window.top</b>: The top level window object, even if the current window is the top level window object.</p> <p><b>window.self</b>: The current window object. (It is a synonym of window.)</p> <p>So, I'd write my check like this:</p> <pre><code>if (window.top == window.self) { window.location = "index.html"; } </code></pre> <p>Which would be identical to the slightly more ambiguous:</p> <pre><code>if (window.top == window) { window.location = "index.html"; } </code></pre>
<pre><code>&lt;script language="Javascript"&gt;&lt;!-- if (top.location == self.location) { top.location = "index.html" // must be viewed in main index } //--&gt;&lt;/script&gt; </code></pre> <p>modified it from a situation where an an iframe decides to become the main frame.</p>
43,170
<p>I'm implementing charts using <a href="http://www.ziya.liquidrail.com/" rel="nofollow noreferrer">The Ziya Charts Gem</a>. Unfortunately, the documentation isn't really helpful or I haven't had enough coffee to figure out theming. I know I can set a theme using</p> <pre><code>chart.add(:theme, 'whatever') </code></pre> <p>Problem: I haven't found any predefined themes, nor have I found a reference to the required format. </p>
<p>As I understand it, the themes are used by initializing the theme directory in your ziya.rb file like so: </p> <p><code>Ziya.initialize(:themes_dir =&gt; File.join( File.dirname(__FILE__), %w[.. .. public charts themes]) ) </code></p> <p>And you'll need to set up the proper directory, in this case public/charts/themes. It doesn't come with any in there to start with as I recall. Are you having problems past this?</p>
<p>To partly answer my own question, there are some themes in the website sources which can be checked out at </p> <pre><code>svn co svn://rubyforge.org/var/svn/liquidrail/samples/charting </code></pre> <p>(then go to /public/charts/themes/)</p>
14,894
<p>Ok here's what I'm trying to do I want to write a class that inherits everything from the class ListItem</p> <pre><code>class RealListItem : ListItem { public string anExtraStringINeed; } </code></pre> <p>For some reason or another .net is treating all the members like they are private when I try to do this so my class is worthless.</p> <p>I tried to do a work around and do it like this:</p> <pre><code>class RealListItem : ListItem { public string anExtraStringINeed; public ListItem list; } </code></pre> <p>but it still doesn't work because I need to use it in a function that uses the accepts type ListItem and RealListItem isn't playing nice like it should. I can do aRealListItem.list but that only passes the list from RealListItem I need the whole object to be passed along.</p> <p>Whats with this am I doing something wrong or will microsoft just not let you inherit .net classes?</p>
<p>The System.Web.UI.Controls.ListItem class is "sealed"... That means you cannot inherit from it... </p>
<p>As Charles states, ListItem is sealed which means you can't inherit from it. In the framework, some classes are marked as sealed and others are not. (The ones that aren't sealed you can inherit.)</p> <p>You could create your own ListItem that contains a System.Web.UI.WebControls.ListItem, but I don't think this will actually provide you much benefit.</p> <p>What is it that you are trying to accomplish? You may need to find an alternate way to do things.</p>
39,018
<p>Sorry, I'm new to SVN and I looked around a little for this. How do you mark a major version in SVN, kind of like set up a restore point. Right now I just setup my server and added all my files- I've been intermittently committing different changes. When I have something in a stable state is there a way to mark this so I can easily revert back to it if necessary?</p>
<p>Sounds like you're looking for tags.</p> <p><a href="http://svnbook.red-bean.com/en/1.1/ch04s06.html" rel="nofollow noreferrer">Tags in the Subversion book</a></p> <p>"A tag is just a “snapshot” of a project in time"</p>
<p>try reading this page <a href="http://svnbook.red-bean.com/en/1.1/re07.html" rel="nofollow noreferrer">svn copy</a> . Basically you just need to do a svn copy</p>
12,770
<p>I need to test a site with a dynamic menu in Mac Firefox, but I'm running in Windows. A simple browsershot.com test won't help; I need to actually use the site.</p> <p>How can I acquire a method of doing Mac emulation without physically having a Mac? Is there some kind of remote VM product out there?</p>
<p>We use <a href="http://www.browsercam.com/" rel="noreferrer">BrowserCam</a> for exactly that.</p>
<p>Check out the <a href="http://wiki.osx86project.org/wiki/index.php/Vmware_how_to" rel="nofollow noreferrer">OSx86 Project</a>. I've used this before, it works quite well and is pretty easy to understand.</p>
21,486
<p>I spend some time editing configurations in .htaccess files across several projects in Eclipse. How would I go about telling Eclipse to auto color this file in a similar fashion as shell scripts or HTML?</p>
<p>I found using the "Properties File Editor" seems to give a decent color output. It's actually for Java files, so it comes with a stock Eclipse.</p> <p>In Preferences, "General" -> "Content Types" -> "Text" -> "Java Properties File" click "Add..." button, enter ".htaccess", click "OK".</p>
<p>You could use the <a href="http://www.gstaff.org/colorEditor/" rel="nofollow noreferrer"><strong>ColorEditor</strong></a> from Gstaff, in order to define your <a href="http://www.codecommit.com/blog/eclipse/general-purpose-editor-within-eclipse" rel="nofollow noreferrer"><strong>own syntax coloring</strong></a>.</p>
47,539
<p>I have a table with multiple rows. Each row is a form. I want to use JQuery to submit all the forms that have the check box checked. The form is posting to an IFrame so there is not much need for AJAX.</p> <p>So far I have:</p> <pre><code> $("form").submit(); </code></pre> <p>which submits the form. but all forms. There is arbritary number of rows, could be 80-100.</p>
<p>Off the top of my head, you probably want something like this</p> <pre><code>$("input:checked").parent("form").submit(); </code></pre> <p>This will find the checked form fields, traverse up to find the parent form object and submit that.</p>
<p>This is kinda a guess since I'm not sure of your layout, but here goes....</p> <pre><code>$("td &gt; input:checked &gt; form").submit(); </code></pre>
28,536
<p>I want to continuously sample from my PC's audio line in using C# (then process that data). What is the best way to do the sampling?</p>
<p>You can do some (basic) audio capture using the open source <a href="http://www.codeplex.com/naudio" rel="nofollow noreferrer">NAudio</a> .NET Audio Library. Have a look at the NAudioDemo project to see a simple example of recording to a WAV file using the WaveIn functions. NAudio also now includes the ability to capture audio using WASAPI (Windows Vista and above) and ASIO (if your soundcard has an ASIO driver).</p>
<p>Managed DirectX supports direct capture of audio and is very easy to use, but is no longer supported and was removed from the DirectX SDK last year. It's still possible to <a href="http://www.microsoft.com/downloads/details.aspx?familyid=86cf7fa2-e953-475c-abde-f016e4f7b61a&amp;displaylang=en" rel="nofollow noreferrer">get it</a> by installing an SDK version from before August 2007.</p> <p>While not strictly meeting your requirements, a more robust approach would be to create a C++/CLI wrapper assembly around the native C++ DirectSound API, again from the DirectX SDK. This could then be called directly from C# code. This is definitely a more powerful and maintainable approach, despite requiring some knowledge of C++ and COM.</p> <p>I have used both of these techniques in the past and they both work well.</p>
28,297
<p>I have html code that looks roughly like this:</p> <pre><code>&lt;div id="id1"&gt; &lt;div id="id2"&gt; &lt;p&gt;some html&lt;/p&gt; &lt;span&gt;maybe some more&lt;/span&gt; &lt;/div&gt; &lt;div id="id3"&gt; &lt;p&gt;different text here&lt;/p&gt; &lt;input type="text"&gt; &lt;span&gt;maybe even a form item&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Obviously there's more to it than that, but that's the basic idea. What I need to do is switch the location of #id2 and #id3, so the result is:</p> <pre><code>&lt;div id="id1"&gt; &lt;div id="id3"&gt;...&lt;/div&gt; &lt;div id="id2"&gt;...&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Does anyone know of a function (I'm sure I'm not the first person to require this functionality) that can read and write the two nodes (and all their children) so as to swap their location in the DOM?</p>
<p>In this case, <code>document.getElementById('id1').appendChild(document.getElementById('id2'));</code> should do the trick.</p> <p>More generally you can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore" rel="noreferrer"><code>insertBefore()</code></a>.</p>
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement" rel="nofollow noreferrer">insertAdjacentElement</a> instead of <code>appendChild</code> to have more control about the position of element with respect to a target element.</p> <p>Syntax: <code>targetElement.insertAdjacentElement(position, element)</code>. It has four position codes as:</p> <ul> <li>'beforebegin': Before the targetElement itself.</li> <li>'afterbegin': Just inside the targetElement, before its first child.</li> <li>'beforeend': Just inside the targetElement, after its last child.</li> <li>'afterend': After the targetElement itself.</li> </ul> <p>it appears as:</p> <pre><code>//beforebegin &lt;p&gt; //afterbegin foo //beforeend &lt;/p&gt; //afterend </code></pre> <p>In your case, you can write the code as:</p> <pre><code>document.getElementById('id2').insertAdjacentElement('beforebegin', document.getElementById('id3')); </code></pre> <p>Note that this way, you don't need reference the parent (container) element!</p> <p>Also consider You have more elements than id2, id3, eg: id4, id5, id6. Now, if you want to reposition for example id5 after id2, its as simple as:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function changePosition() { document.getElementById('id2').insertAdjacentElement('afterend', document.getElementById('id5')); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id='container'&gt; &lt;div id='id1'&gt;id1&lt;/div&gt; &lt;div id='id2'&gt;&lt;u&gt;id2&lt;/u&gt;&lt;/div&gt; &lt;div id='id3'&gt;id3&lt;/div&gt; &lt;div id='id4'&gt;id4&lt;/div&gt; &lt;div id='id5'&gt;&lt;b&gt;id5&lt;/b&gt;&lt;/div&gt; &lt;div id='id6'&gt;id6&lt;/div&gt; &lt;/div&gt; &lt;p&gt;&lt;input type='button' onclick="changePosition()" value="change position"&gt;&lt;/p&gt;</code></pre> </div> </div> </p>
41,998
<p>Where can I find algorithms for image distortions? There are so much info of Blur and other classic algorithms but so little of more complex ones. In particular, I am interested in swirl effect image distortion algorithm.</p>
<p>I can't find any references, but I can give a basic idea of how distortion effects work.</p> <p>The key to the distortion is a function which takes two coordinates (x,y) in the distorted image, and transforms them to coordinates (u,v) in the original image. This specifies the inverse function of the distortion, since it takes the distorted image back to the original image</p> <p>To generate the distorted image, one loops over x and y, calculates the point (u,v) from (x,y) using the inverse distortion function, and sets the colour components at (x,y) to be the same as those at (u,v) in the original image. One ususally uses interpolation (e.g. <a href="http://en.wikipedia.org/wiki/Bilinear_interpolation" rel="noreferrer">http://en.wikipedia.org/wiki/Bilinear_interpolation</a> ) to determine the colour at (u,v), since (u,v) usually does not lie exactly on the centre of a pixel, but rather at some fractional point between pixels.</p> <p>A swirl is essentially a rotation, where the angle of rotation is dependent on the distance from the centre of the image. An example would be:</p> <pre><code>a = amount of rotation b = size of effect angle = a*exp(-(x*x+y*y)/(b*b)) u = cos(angle)*x + sin(angle)*y v = -sin(angle)*x + cos(angle)*y </code></pre> <p>Here, I assume for simplicity that the centre of the swirl is at (0,0). The swirl can be put anywhere by subtracting the swirl position coordinates from x and y before the distortion function, and adding them to u and v after it.</p> <p>There are various swirl effects around: some (like the above) swirl only a localised area, and have the amount of swirl decreasing towards the edge of the image. Others increase the swirling towards the edge of the image. This sort of thing can be done by playing about with the angle= line, e.g.</p> <pre><code>angle = a*(x*x+y*y) </code></pre>
<p>Take a look at <a href="http://www.imagemagick.org/script/index.php" rel="nofollow noreferrer">ImageMagick</a>. It's a image conversion and editing toolkit and has interfaces for all popular languages.</p> <p>The -displace operator can create swirls with the correct displacement map.</p> <p>If you are for some reason not satisfied with the ImageMagick interface, you can always take a look at the source code of the filters and go from there.</p>
27,878
<p>I've written this to try and log onto a forum (phpBB3).</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) output = page.read() </code></pre> <p>However when I run it it comes up with;</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) TypeError: string indices must be integers </code></pre> <p>any ideas as to how to solve this?</p> <p><em>edit</em></p> <p>adding a comma between the string and the data gives this error instead</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login",[logindata]) File "C:\Python25\lib\urllib.py", line 84, in urlopen return opener.open(url, data) File "C:\Python25\lib\urllib.py", line 192, in open return getattr(self, name)(url, data) File "C:\Python25\lib\urllib.py", line 327, in open_http h.send(data) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "&lt;string&gt;", line 1, in sendall TypeError: sendall() argument 1 must be string or read-only buffer, not list </code></pre> <p><em>edit2</em></p> <p>I've changed the code from what it was to;</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) output = page.read() </code></pre> <p>This doesn't throw any error messages, it just gives 3 blank lines. Is this because I'm trying to read from the log in page which disappears after logging in. If so how do I get it to display the index which is what should appear after hitting log in.</p>
<p>Your line</p> <pre><code>page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) </code></pre> <p>is semantically invalid Python. Presumably you meant</p> <pre><code>page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login", [logindata]) </code></pre> <p>which has a comma separating the arguments. However, what you ACTUALLY want is simply</p> <pre><code>page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) </code></pre> <p>without trying to enclose logindata into a list and using the more up-to-date version of urlopen is the urllib2 library.</p>
<p>This would be easier with the high-level "mechanize" module.</p>
41,584
<p>I want to work with versioned ActiveRecord associations. <i>E.g.</i>, I want to find the object that another object belongs_to as of a certain past date, or the one that it belonged to before that. Does there already exist a library subclassing Rails' ActiveRecord to provide versioned relations? Or some other Ruby library which provides persistable versioned relations?</p>
<p>Try the <a href="http://ar-versioned.rubyforge.org/" rel="noreferrer">ActsAsVersioned</a> plugin</p>
<p>Supporting historical state in a transactional application is a good way to massively expand complexity, slow DB performance and make life difficult for yourself. If you only need to display or report on historical state and do not need it up to the minute consider building a star schema with <a href="http://en.wikipedia.org/wiki/Slowly_changing_dimension" rel="nofollow noreferrer">Type-II slowly changing dimensions</a> and a periodic process that updates it.</p> <p>This will be substantially less complex than building an application with systemic ad-hoc history tracking running through the code base. If this approach will do what you require of the application you will probably be better off doing it. It also means that the application database will play nicely with the vanilla database access mechanisms that come with the system.</p> <p>If you need reasonably frequent refresh you can implement a changed-data capture system on the database, which is relatively simple if the application only has to be concerned with current state. With a CDC mechanism the load process only has to update based on changes and will run relatively quickly.</p>
33,856
<h2>Problem</h2> <p>I have timestamped data, which I need to search based on the timestamp in order to get the one existing timestamp which matches my input timestamp the closest.<br> Preferably this should be solved with the STL. boost::* or stl::tr1::* (from VS9 with Featurepack) are also possible.<br> Example of timestamped data:</p> <pre><code>struct STimestampedData { time_t m_timestamp; // Sorting criterion CData m_data; // Payload } </code></pre> <h2>Approach with <code>stl::vector</code>, <code>sort()</code> and <code>equal_range()</code></h2> <p>Since a <code>map</code> or <code>set</code> only allows me to find exact matches, I don't get any further using one of these. So now I have a <code>vector</code> to which I append data as it is coming in. Before searching I use <code>&lt;algorithm&gt;</code>'s <code>sort()</code> and supply it with a custom comparison function.<br> After that I use <code>&lt;algorithm&gt;</code>'s <code>equal_range()</code> to find the two neighbors of a specified value <code>x</code>. From these two values I check which one is closest to <code>x</code> and then I have my best match.</p> <p><br> While this is not too complex, I wonder if there are more elegant solutions to this.<br> Maybe the STL already has an algorithm which does exactly that so I'm not re-inventing something here?</p> <h2>Update: Linear vs. binary search</h2> <p>I forgot to mention that I have quite a lot of data to handle so I don't want to have to search linearly.<br> The reason I am sorting a vector with <code>sort()</code> is because it has random access iterators which is not the case with a <code>map</code>. Using a <code>map</code> would not allow <code>equal_range()</code> to do a search with twice logarithmic complexity.<br> Am I correct?</p>
<p>I would use set::lower_bound to find the matching or greater value, then decrement the iterator to check the next lower value. You should use std::set rather than std::map since your key is embedded in the object - you'll need to provide a functor that compares the timestamp members.</p> <pre><code>struct TimestampCompare { bool operator()(const STimestampedData &amp; left, const STimestampedData &amp; right) const { return left.m_timestamp &lt; right.m_timestamp; } }; typedef std::set&lt;STimestampedData,TimestampCompare&gt; TimestampedDataSet; TimestampedDataSet::iterator FindClosest(TimestampedDataSet &amp; data, STimestampedData &amp; searchkey) { if (data.empty()) return data.end(); TimestampedDataSet::iterator upper = data.lower_bound(searchkey); if (upper == data.end()) return --upper; if (upper == data.begin() || upper-&gt;m_timestamp == searchkey.m_timestamp) return upper; TimestampedDataSet::iterator lower = upper; --lower; if ((searchkey.m_timestamp - lower-&gt;m_timestamp) &lt; (upper-&gt;m_timestamp - searchkey.m_timestamp)) return lower; return upper; } </code></pre>
<p>Depending on what your usage is, you could do a simple linear search instead of a sort. Come up with a "distance" function, loop through keeping track of the best match so far, and its distance. When you find a better match, forget the previous one, and keep the new one and its distance. When you've looped through everything, you have your match.</p> <p>This works out to be O(N*S) where N is the number of items in the vector and S is the number of searches.</p> <p>Your current way is O((N+S)*LogN) which is greater if the number of searches is small and bounded. Otherwise the sort / binary search is better.</p>
26,879
<p>I'm trying to create a table with two columns comprising the primary key in MySQL, but I can't figure out the syntax. I understand single-column PKs, but the syntax isn't the same to create a primary key with two columns.</p>
<pre><code>CREATE TABLE table_name ( c1 INT NOT NULL, c2 INT NOT NULL, PRIMARY KEY (c1, c2) ) </code></pre>
<p>Example:</p> <pre><code> CREATE TABLE `synthesis`.`INV_MasterItemList` ( `MasterItemList_ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `Customer_ID` INTEGER UNSIGNED NOT NULL, `Model_ID` INTEGER UNSIGNED NOT NULL, `Serial` VARCHAR(45) NOT NULL, PRIMARY KEY (`MasterItemList_ID`), UNIQUE INDEX `INDEX_UNIQUE`(`Customer_ID`, `Model_ID`, `Serial`) ) </code></pre>
20,236
<p>Joel Spolsky <a href="http://www.joelonsoftware.com/articles/PleaseLinker.html" rel="noreferrer">praised</a> native-code versions of programs that have no dependencies on runtimes. </p> <p>What native-code compilers are available for functional languages?</p>
<p>This post is really quite unclear. The question appears to be "Are there compilers for functional languages which can produce native executables without the need to install additional software?"</p> <p>The answer, generally, is yes. For example, <a href="http://www.haskell.org/" rel="noreferrer">Haskell</a> has <a href="http://www.haskell.org/ghc/" rel="noreferrer">a compiler</a> that produces native binaries. Many other functional languages have similar compilers.</p>
<p><a href="http://plt-scheme.org/" rel="nofollow noreferrer">PLT Scheme</a> has got a JIT compiler.</p> <p><a href="http://community.schemewiki.org/?Stalin" rel="nofollow noreferrer">Stalin</a> is a Scheme compiler which does ridiculously aggressive optimisation.</p> <p>All Common Lisp implementations that I know of except <a href="http://clisp.cons.org/" rel="nofollow noreferrer">CLISP</a> compile to native code. (Whether one ought to consider CL a functional language depends on what is meant by the term “functional”, however.)</p> <p><a href="http://mlton.org/" rel="nofollow noreferrer">MLton</a> is a highly optimising compiler for Standard ML.</p> <p>Functional languages can be and have for some time been compiled very effectively. There is no difference to imperative languages in this regard.</p>
13,031
<p>Is it realistic to try and learn and code a Flex 3 application without purchasing FlexBuilder? Since the SDK and BlazeDS are open source, it seems technically possible to develop without Flex Builder, but how realistic is it.</p> <p>I would like to test out Flex but don't want to get into a situation where I am dependent on the purchase of FlexBuilder (at least not until I am confident and competent enough with the technology to recommend purchase to my employer).</p> <p>I am experimenting right now, so I'm taking a long time and the trial license on my Windows machine has expired. Also Linux is my primary development platform and there is only an alpha available for Linux.</p> <p>Most of the documentation I've found seem to use Flex Builder.</p> <p>Maybe I should use Laszlo...</p>
<p>I've been using Flex since version 2 and Flex3/BlazeDS since it came out of beta. I also have some experience with Lazzlo and the difference is day and night (Flex rocks!). I have not regretted once using Flex. Regarding FlexBuilder, it is worth every penny. While it is completely possible and reasonable to write Flex application without FlexBuilder, the productivity gains of using it will more than recoup the investment. Try the evaluation for 30 days and compare it to some of the other options suggested about (I'm going to try FlashDevelop). </p> <p>Some things you get with FlexBuilder include:</p> <ul> <li>Code completion</li> <li>Visual editor</li> <li>Debugger (it is fantastic!!)</li> <li>Profiler (also very good)</li> </ul> <p>Regarding Linux, the alpha version of FlexBuilder does not have a visual editor. Other than that, I understand it is reasonably feature complete, still free, and many of the Adobe employees I've talked with that use Linux are happy with it.</p>
<p>Absolutely. I've been a Flex developer since Flex 2 and until recently I've used my regular editor, TextMate, for coding and Ant for building. TextMate has some good extensions for ActionScript and Flex coding, but I think you could get that for any decent editor.</p> <p>What's been missing from my setup is a usable debugger, the command line version is a pain to work with. Because of that I've been starting to use FlexBuilder on the side, using it in parallel with my regular setup.</p> <p>Having a profiler doesn't hurt too.</p>
6,185
<p>I have several long running report type transactions that take 5-10 minutes. Would I see any performance increase by using stored procs? Would it be significant?</p> <p>each query runs once a night.</p>
<p>Probably not. Stored procs give you the advantage of pre-compiled SQL. If your SQL is invoked infrequently, they this advantage will be pretty worthless. So if you have SQL that is expensive because the queries themselves are expensive, then stored procs will gain you no meaningful performance advantage. If you have queries that are invoked very frequently and which themselves execute quickly, then it's worth having a proc.</p>
<p>yes, the query plan for stored procs can be optimized and even if it can't procs are preferred over embedded sql</p> <p>"would you see any performance improvement" - the only way to know for certain is to try it</p> <p>in theory, stored procedures pre-parse the sql and store the query plan instead of figuring out each time, so there should be some speedup just from that, however, i doubt it would be significant in a 5-10 minute process</p> <p>if the speed is of concern your best bet is to look at the query plan and see if it can be improved with different query structures and/or adding indices et al</p> <p>if the speed is not of concern, stored procs provide better encapsulation than inline sql</p>
15,743
<p>Are there any 'standard' plugins for detecting the CPU architecture in <strong>scons</strong>? </p> <p>BTW, this question was asked already <a href="https://stackoverflow.com/questions/152016/detecting-cpu-architecture-compile-time">here</a> in a more general form... just wondering if anyone has already taken the time to incorporate this information into scons. </p>
<p>Using <strong>i386</strong> is rather compiler dependant, and won't detect non x86 32 bits archs. Assuming the python interpreter used by scons runs on the CPU you are interested in (not always the case - think cross compilation), you can just use python itself.</p> <pre><code>import platform print platform.machine() print platform.architecture() </code></pre> <p>If you need something more sophisticated, then maybe you will have to write your own configure function - but it may be better to deal with it in your code directly.</p>
<p>Something like this?</p> <pre><code>env = Environment() conf = Configure(env) if conf.CheckDeclaration("__i386__"): conf.Define("MY_ARCH", "blahblablah") env = conf.Finish() </code></pre>
30,470
<p>What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site. </p> <p>I have done this by using </p> <pre><code> Response.Clear(); Response.ContentType = "image/pjpeg"; Response.BinaryWrite(imageConents); Response.End(); </code></pre> <p>but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?</p>
<p>Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this:</p> <pre><code>public class ImageHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { using(Image image = GetImage(context.Request.QueryString["ID"])) { context.Response.ContentType = "image/jpeg"; image.Save(context.Response.OutputStream, ImageFormat.Jpeg); } } public bool IsReusable { get { return true; } } } </code></pre> <p>Now just implement the GetImage method to load the image with the given ID, and you can use</p> <pre><code>&lt;asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" /&gt; </code></pre> <p>to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).</p>
<p>We actually just released some classes that help with exactly this kind of thing:</p> <p><a href="http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449" rel="nofollow noreferrer">http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449</a></p> <p>Specifically, check out the DatabaseImage sample.</p>
4,191
<p>I am working with some input that is in the possible forms</p> <pre><code>$1,200 20 cents/ inch $10 </code></pre> <p>Is there a way to parse these to numbers in VB? Also printing these numbers?</p> <p><strong>EDIT:</strong> Regular expressions would be great.</p> <p><strong>EDIT:</strong> VB 6 in particular</p>
<p>Ehh...Assuming all that you want is the digits, I would use a Regular Expression to simply replace any non-digit with "".</p> <p>You would need to reference Microsoft VBScript Regular Expressions in your project. Then let's say that your text was in a variable called strTest. Here is some off the cuff untested code:</p> <pre><code>Dim oRE As Object Set oRE = New VBScript_RegExp.RegExp oRe.Pattern = "\D" strTest = oRE.Replace(strTest, "") </code></pre>
<p>Sometimes it just takes brute force!</p> <p>Here is a routine that takes in a string with numbers and returns a number properly handled with fractions, M or B suffixes, and more. You can modify i to handle any special condition or text algebra (miles / hour, cents / inch, etc)</p> <p>This is taken from one of our production applications thus the line numbers which we use in our error handler (ERHandler), as well as the standard exit routine.</p> <pre><code>Function GetNumberFromString(s As String) As Currency 12800 Const ProcID = "GetNumberFromString" 12810 Dim c As String 12820 Dim d As Integer 12830 Dim Denominator As Double ' currency only handles 4 places 12840 Dim HaveDec As Boolean 12850 Dim HaveSlash As Boolean 12860 Dim HaveSpace As Boolean 12870 Dim i As Integer 12880 Dim LenV As Integer 12890 Dim NegMult As Integer 12900 Dim Numerator As Currency 12910 Dim TempVal As Currency 12920 Dim v As String 'Provides the functionality of VAL, but handles commas, fractions ' also million and billion 12930 On Error GoTo ErrLbl 12940 oLog.LogProcEntry ModuleID, ProcID, "v=" &amp; v 12950 v = Trim(s) 12960 LenV = Len(v) 12970 If LenV = 0 Then 12980 GetNumberFromString = 0 12990 GoTo ExitProc 13000 End If 13010 TempVal = 0 13020 d = 0 13030 NegMult = 1 ' 13040 For i = 1 To LenV 13050 c = Mid(v, i, 1) 13060 Select Case c Case "0" To "9" 13070 If HaveSpace Then 13080 If Not HaveSlash Then 13090 Numerator = 10 * Numerator + Asc(c) - 48 13100 Else 13110 Denominator = 10 * Denominator + Asc(c) - 48 13120 End If 13130 ElseIf Not HaveDec Then 13140 TempVal = 10 * TempVal + Asc(c) - 48 13150 Else 13160 TempVal = TempVal + ((Asc(c) - 48)) / (10 ^ d) 13170 d = d + 1 13180 End If 13190 Case ",", "$" ' do nothing 13200 Case "-" 'let handle negatives ns 12/20/96 13210 NegMult = -1 * NegMult 13220 Case "(" 'let handle negatives mt 6/9/99 13230 NegMult = -1 * NegMult 13240 Case "." 13250 HaveDec = True 13260 d = 1 13270 Case " " 13280 HaveSpace = True 13290 d = 1 13300 Case "/" 13310 HaveSlash = True 13320 If Not HaveSpace Then 13330 HaveSpace = True 13340 Numerator = TempVal 13350 TempVal = 0 13360 End If 13370 Case "b", "B" 13380 If UCase(Mid(v, i, 7)) = "BILLION" Then 13390 TempVal = TempVal * 1000000000# 13400 Exit For 13410 End If 13420 Case "m", "M" 13430 If UCase(Mid(v, i, 7)) = "MILLION" Then 13440 TempVal = TempVal * 1000000# 13450 Exit For 13460 End If 13470 Case Else ' ignore character/error 13480 End Select 13490 Next i 13500 If HaveSlash And Denominator &lt;&gt; 0 Then 13510 TempVal = TempVal + Numerator / Denominator 13520 End If 13530 GetNumberFromString = TempVal * NegMult ExitProc: 13540 oLog.LogProcExit ModuleID, ProcID 13550 Exit Function ErrLbl: 13560 Debug.Print Err.Description, Err.Number 13570 Debug.Assert False 13580 ERHandler ModuleID, ProcID 13590 Resume End Function </code></pre>
28,587
<p>The performance of a Direct3D application seems to be significantly better in full screen mode compared to windowed mode. What are the technical reasons behind this?</p> <p>I guess it has something to do with the fact that a full screen application can gain exclusive control for the display. But why the application cannot gain exclusive control for <em>part</em> of the screen (i.e. window) and have the same performance benefits?</p>
<p>Here are the cliff notes on how things work underneath. </p> <p>Monitor screen always needs to be associated with so-called primary surface to be able to display anything, i.e. videocard can only scan out of one surface in video memory.</p> <p>When application is fullscreen (and everything was set up correctly to enable flipping), primary surface is just one of the application backbuffers, and flipped to another backbuffer every frame. It is the most efficient way of presenting on the screen, but it requires application to own the entire monitor area (i.e. entire primary surface).</p> <p>When there's no fullscreen application and DWM is off, primary surface is owned by OS, and every windowed application performs a blit from application backbuffer to a primary surface. This blit takes some GPU time to complete (as well as blits from the other applications visible on the screen), so it's not as efficient as fullscreen presentation. XP worked that way.</p> <p>When DWM is composing the screen, things get even more complicated. Here, DWM owns the primary surface and needs to draw application windows there. To make it possible, every window has an associated surface holding its contents, called redirection surface (which allows DWM to enable window ghosting, glass effects, and all that good stuff). Every time D3D application issues a frame, it adds a blit to a redirection surface. That way, several blits need to happen: blit to a redirection surface by the app, blit from a redirection surface to the primary by DWM, which is, again, some overhead compared to fullscreen.</p> <p>Note all of that additional work is on the GPU, so it doesn't affect CPU performance.</p> <p>Stuff to read further:</p> <p><a href="http://blogs.msdn.com/greg_schechter/archive/2006/03/19/555087.aspx" rel="noreferrer">http://blogs.msdn.com/greg_schechter/archive/2006/03/19/555087.aspx</a></p> <p><a href="http://blogs.msdn.com/greg_schechter/archive/2006/05/02/588934.aspx" rel="noreferrer">http://blogs.msdn.com/greg_schechter/archive/2006/05/02/588934.aspx</a></p> <p><a href="http://blogs.msdn.com/greg_schechter/archive/2006/03/05/544314.aspx" rel="noreferrer">http://blogs.msdn.com/greg_schechter/archive/2006/03/05/544314.aspx</a></p>
<p>Basically, the video hardware is completely dedicated to the exclusive mode application.</p> <p>There is no contention for video resources (pipeline, texture memory, etc...)</p> <p>In particular, texture upload can be a big bottleneck. The less you have to do it (because you have it all), the better.</p>
39,160
<p>I have an editable DataGridView with SelectionMode set to FullRowSelect (so the whole row is highlighted when the user clicks on any cell). However I would like the cell that currently has focus to be highlighted with a different back color (so the user can clearly see what cell they are about to edit). How can I do this (I do not want to change the SelectionMode)?</p>
<p>I figured out a better way of doing this, using the CellFormatting event:</p> <pre><code>Private Sub uxContacts_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles uxContacts.CellFormatting If uxContacts.CurrentCell IsNot Nothing Then If e.RowIndex = uxContacts.CurrentCell.RowIndex And e.ColumnIndex = uxContacts.CurrentCell.ColumnIndex Then e.CellStyle.SelectionBackColor = Color.SteelBlue Else e.CellStyle.SelectionBackColor = uxContacts.DefaultCellStyle.SelectionBackColor End If End If End Sub </code></pre>
<p>You want to use the DataGridView RowPostPaint method. Let the framework draw the row, and afterwards go back and color in the cell you're interested in.</p> <p>An example is here at <a href="http://msdn.microsoft.com/en-us/library/85kxk29c.aspx" rel="nofollow noreferrer">MSDN</a></p>
9,913
<p>We prototype a design, GUI, just to analyze a particular problem, proof of concept, etc. Sometimes we throw away the prototype, and sometimes it ends up in the production code. We use different languages, technologies, strategies, and styles to prototype.</p> <p>What are the different situations you prototype usually and how do you prototype? Any good resource out there to master the craft?</p>
<p>One hot title is <em><a href="https://rads.stackoverflow.com/amzn/click/com/0120885689" rel="noreferrer" rel="nofollow noreferrer">Effective Prototyping for Software Makers</a></em>. The issue is that there are several schools of thought.</p> <ul> <li><p>Rapid Prototyping. Use fancy tools; get something done soon.</p></li> <li><p>Evolutionary Prototyping. Evolve from prototype to production.</p></li> </ul> <p>Some of this is legacy thinking, based on an era where tools were primitive and projects had to be meticulously planned from the beginning. When I started in this industry, the "green-screen" character-mode applications where rocket science and very painful to mock up. Tools and formal techniques were essential to manage the costs and risks.</p> <p>This thinking is trumped by some more recent thinking. </p> <ol> <li><p>Powerful tools remove the need for complex prototypes. HTML mockups can be slapped together quickly. Is it still a prototype when you barely have to budget or plan for it? [You can mock it up in MS-Word and save it as HTML. It's quicker for a Business Analyst to do it than to specify it and have a programmer do it.]</p></li> <li><p>Also, powerful tools can reduce the cost of mistakes. If it only took a week to put something together -- production-ready -- what's the point of an formal prototype effort?</p></li> <li><p>Agile techniques reduce the need to do quite so much detailed up-front planning. When you put something that works in the hands of users quickly, you don't have quite so much need to be sure every nuance is <em>right</em> before you start. It just has to be good enough to consider it progress. </p></li> </ol> <p>What can happen is the following. [The hidden question is: is this still "prototyping" -- or is this just an Agile approach with powerful tools?]</p> <p>Using tools like Django, you can put together the essential, core data structure and exercise it almost immediately. Use the default Django admin pages and you should be up and running as soon as you can articulate the data structures and write load utilities.</p> <p>Then, add presentation pages wrapped around real, working data. Be sure you've got things right. Since you've only built data model and template-driven HTML pages, your investment is minimal. Explore.</p> <p>Iterate until people start asking for smarter transactions than those available in the default admin pages. At this point, you're moving away from "discovery" and "elaboration" and into "construction". Did you do any prototyping? I suppose each HTML template you discarded was a kind of prototype. For that matter, so where the ones you kept.</p> <p>The whole time, you can be working with more-or-less live, production users.</p>
<p>I start off making a prototype that makes the most interesting part work, then I throw it away and move on to a new, more interesting project...</p> <p>*kills self*</p>
13,295
<p>Ok, so I'm looking for a bit of architecture guidance, my team is getting a chance to re-cast certain decisions with a new feature that we're building, and I wanted to see what SO thought :-) There are of course certain things that we're not changing, so the solution would have to fit in this model. Namely, that we've got an ASP.NET application, which uses web services to allow users to perform actions on the system.</p> <p>The problem comes in because, as with many systems, different users need access to different functions. Some roles have access to Y button, and others have access to Y and B button, while another still only has access to B. Most of the time that I see this, developers just put in a mish-mosh of if statements to deal with the UI state. My fear is that left unchecked, this will become an unmaintainable mess, because in addition to putting authorization logic in the GUI, it needs to be put in the web services (which are called via ajax) to ensure that only authorized users call certain methods.</p> <p>so my question to you is, how can a system be designed to decrease the random ad-hoc if statements here and there that check for specific roles, which could be re-used in both GUI/webform code, and web service code.</p> <p>Just for clarity, this is an ASP.NET web application, using webforms, and <a href="http://projects.nikhilk.net/ScriptSharp/" rel="nofollow noreferrer">Script#</a> for the AJAX functionality. Don't let the script# throw you off of answering, it's not fundamentally different than asp.net ajax :-)</p>
<pre><code>Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName); </code></pre>
<p>Use the <a href="http://www.pinvoke.net/default.aspx/shell32/ExtractIconEx.html" rel="nofollow noreferrer">ExtractIconEx</a> (and <a href="http://msdn.microsoft.com/en-us/library/ms648069.aspx" rel="nofollow noreferrer">here</a>) p/invoke. You can extract small and large icons from any dll or exe. Shell32.dll itself has over 200 icons that are quite useful for a standard Windows application. You just have to first figure out what the index is for the icon(s) you want.</p> <p>Edit: I did quick SO search and found <a href="https://stackoverflow.com/questions/189031/set-same-icon-for-all-my-forms#189618">this</a>. The index 0 icon is the application icon.</p>
24,894
<p>Normally I program in C# but have been forced to do some work in C++. It seems that the integration with Visual Studio (2008) is really poor compared to C# but I was wondering if there are any good tools, plugins or configurations that can improve the situation.</p> <p>Another post pointed out the program Visual Assist X, which at least helps with some things such as refactoring (though it is a bit expensive for me). My major problem is, though, that the compile errors give little clue about what is wrong and I spend most of my time figuring out what I did wrong. It just feels like it is possibly to statically check for a lot more errors than VS does out of the box. And why doesn't it provide the blue underlines as with C#, that shouldn't be too hard?!</p> <p>I realize that half the problem is just the fact that I am new to C++ but I really feel that it can be unreasonably hard to get a program to compile. Are there any tools of this sort out there or are my demands too high?</p>
<p>I think there are two possibilities: 1) either you're trying out C++ stuff that is waaay over your knowledge (and consequently, you don't know what you did wrong and how to interpret error messages), 2) you have too high expectations.</p> <p>A hint: many subsequent errors are caused by the first error. When I get a huge list of errors, I usually correct just the first error and recompile. You'd be amazed how much garbage (in terms of error messages) a missing delimiter or type declaration could produce :)</p> <p>It is difficult to syntactically analyze a C++ program before compilation mainly for two reasons: 1) the C++ grammar is context-dependent, 2) templates are Turing-complete (think of them as of a functional programming language with a weird syntax).</p>
<p>My suggestions:</p> <ul> <li>If you want more features like you get in C#, get <a href="http://www.wholetomato.com/" rel="nofollow noreferrer">VisualAssist X</a>, and learn how to use it. It isn't free but it can save you a lot of time.</li> <li>Set your <a href="http://msdn.microsoft.com/en-us/library/thxezb7y.aspx" rel="nofollow noreferrer">warning level high</a> (this will initially generate more compile-errors but as you fix them, you'll get a feel for common mistakes).</li> <li>Set warning as error so you don't get in the habit of ignoring warnings.</li> <li>To understand compile errors, use Google (don't waste your time with the help system) to search on warning error numbers (they look like this: C4127).</li> <li>Avoid templates until you get your code compiling without errors using the above methods. If you don't know templates well, study! Get some books, do some tutorials and start small. Template compile errors are notoriously hard to figure out. Visual C++ 2008 has much better error messages than previous versions but it's still hard.</li> <li>If you start doing templates in earnest, get a wide-screen monitor (maybe even two) to make reading the verbose errors easier.</li> </ul>
19,745
<p>I'm looking for a good reader/writer lock in C++. We have a use case of a single infrequent writer and many frequent readers and would like to optimize for this. Preferable I would like a cross-platform solution, however a Windows only one would be acceptable. </p>
<p>Newer versions of <a href="http://www.boost.org/doc/libs/1_50_0/doc/html/thread.html" rel="noreferrer">boost::thread</a> have read/write locks (1.35.0 and later, apparently the previous versions did not work correctly).</p> <p>They have the names <a href="http://www.boost.org/doc/libs/1_50_0/doc/html/thread/synchronization.html#thread.synchronization.locks.unique_lock" rel="noreferrer"><code>shared_lock</code></a>, <a href="http://www.boost.org/doc/libs/1_50_0/doc/html/thread/synchronization.html#thread.synchronization.locks.shared_lock" rel="noreferrer"><code>unique_lock</code></a>, and <a href="http://www.boost.org/doc/libs/1_50_0/doc/html/thread/synchronization.html#thread.synchronization.locks.upgrade_lock" rel="noreferrer"><code>upgrade_lock</code></a> and operate on a <a href="http://www.boost.org/doc/libs/1_50_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex" rel="noreferrer"><code>shared_mutex</code></a>.</p>
<p>You could copy Sun's excellent <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html" rel="nofollow noreferrer">ReentrantReadWriteLock</a>. It includes features such as optional fairness, lock downgrading, and of course reentrancy.</p> <p>Yes it's in Java, but you can easily read and transpose it to C++, even if you don't know any Java. The documentation I linked to contains all the behavioral properties of this implementation so you can make sure it does what you want.</p> <p>If nothing else, it's a guide.</p>
30,293
<p>Excuting the line of SQL:</p> <pre><code>SELECT * INTO assignment_20081120 FROM assignment ; </code></pre> <p>against a database in oracle to back up a table called assignment gives me the following ORACLE error: ORA-00905: Missing keyword</p>
<p>Unless there is a single row in the <code>ASSIGNMENT</code> table and <code>ASSIGNMENT_20081120</code> is a local PL/SQL variable of type <code>ASSIGNMENT%ROWTYPE</code>, this is not what you want.</p> <p>Assuming you are trying to create a new table and copy the existing data to that new table</p> <pre><code>CREATE TABLE assignment_20081120 AS SELECT * FROM assignment </code></pre>
<p>Late answer, but I just came on this list today!</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE assignment_20101120 AS SELECT * FROM assignment; </code></pre> <p>Does the same.</p>
39,309
<p>i'm interested in project management software similar to MS Project. the project is a serious rebuild of my software. we have a bug management system already but i need to track project progress.</p> <p>i don't like web-based apps so much because the data is either hosted off-site or i need to set up my own server.</p> <p>i like MS Project but it doesn't seem to compare estimated time with actual time and use it to pro-rate the future work estimates.</p> <p>i'd like a gantt chart &amp; calendar view.</p> <p>thank you for your help!</p>
<p>Please give <a href="https://sourceforge.net/projects/openworkbench/" rel="nofollow noreferrer">open workbench</a> a try.</p>
<p>I used primavera some time back, and I think it can do the said comparison.</p>
14,212
<p>I have a lot of constants that are somehow related, at some point I need to pair them, something like this:</p> <pre><code>const key1 = '1'; key2 = '2'; key3 = '3'; value1 = 'a'; value2 = 'b'; value3 = 'c'; </code></pre> <p>I want to avoid doing:</p> <pre><code>if MyValue = key1 then Result := value1; </code></pre> <p>I know how to do it with string lists using:</p> <pre><code>MyStringList.Add(key1 + '=' + value1); Result := MyStringList.Values[key1]; </code></pre> <p>But, is there any simpler way to do this?</p>
<p>Yes, assignment can be done this way instead, avoiding manual string concatenation:</p> <pre><code>MyStringList.Values[Key1] := Value1; </code></pre>
<p>You can use a multi-dimensional constant array with an enumeration for at least one of the dimensions:</p> <p>Define it like this:</p> <pre><code>type TKVEnum = (tKey, tValue); // You could give this a better name const Count = 3; KeyValues: array [1..Count, TKVEnum] of string = // This is each of your name / value paris (('1', 'a'), ('2', 'b'), ('3', 'd')); </code></pre> <p>Then you use it like this:</p> <pre><code>if MyValue = KeyValues[1, TKVEnum.tKey] then Result := KeyValues[1, TKVEnum.tValue] </code></pre> <p>You could use a <strong>For</strong> loop on it too. This is just as efficient as doing them as individual constant strings, but gives you the added advantage that they are intrinsically associated. </p> <p>Instead of defining the first dimension numerically, I would suggest </p> <pre><code>type TConstPairs = (tcUsername, tcDatabase, tcEtcetera); </code></pre> <p>But I guess that totally depends on what you constants represent.</p>
30,798
<p>I find I can do more with NHibernate, and even Castle than with the Linq to Entities, or linq to SQL.</p> <p>Am I crazy?</p>
<p>No you're not crazy. nHibernate is a full OR Mapper, Linq to SQL and Linq to Entities don't implement everything you'd expect from an OR mapper and targeted at a slightly different group of developers.</p> <p>But don't let that put you off linq though. Linq is still a pretty good idea.. Try Linq to nHibernate :-)</p>
<p>I have not tried the Entity Framework, but I definitely would recommend NHibernate over Linq to SQL; The biggest reason I can give is just the control. Linq to SQL likes to have a lot more control over everything, loading the object and maintaining all kinds of tracking information about the object. If you serialize/deserialize, the tracking information can be lost and strange things can happen when saving it again. NHibernate works more as a repository should - You hand it whatever object you want (that you have configured it to understand, of course), and it puts it away in the database, regardless of what you've done with it.</p>
9,750
<p>What is the best way to version control my database objects? I'm using Visual studio 2005/2008 and SQL server 2005. I would prefer a solution which can be used with SVN.</p>
<p>Same as your other code, add a "Database project" to your application solution and keep the sql files used to build the database objects in there. Use the same version control for those code files as you do for the application.</p>
<p>We do dumps to plaintext and keep them in our VCS.</p> <p>You'd be able to script a backup-and-commit to do something similar.</p>
17,646
<p>Multiple approaches exist to write your unit tests when using Rhino Mocks:</p> <ul> <li>The Standard Syntax</li> <li>Record/Replay Syntax</li> <li>The Fluent Syntax</li> </ul> <p>What is the ideal and most frictionless way?</p>
<p>For .NET 2.0, I recommend the record/playback model. We like this because it separates clearly your expectations from your verifications.</p> <pre><code>using(mocks.Record()) { Expect.Call(foo.Bar()); } using(mocks.Playback()) { MakeItAllHappen(); } </code></pre> <p>If you're using .NET 3.5 and C# 3, then I'd recommend the fluent syntax.</p>
<p>Interesting question! My own preference is the for the reflection-based syntax (what I guess you mean by the Standard Syntax). I would argue that this is the most frictionless, as it does not add much extra code: you reference the stubs directly on your interfaces as though they were properly implemented. </p> <p>I do also quite like the Fluent syntax, although this is quite cumbersome. The Record/Replay syntax is as cumbersome as the Fluent syntax (if not more so, seemingly), but less intuitive (to me at least). I've only used NMock2, so the Record/Replay syntax is a bit alien to me, whilst the Fluent syntax is quite familiar. </p> <p>However, as <a href="https://yellowduckguy.wordpress.com/2007/10/06/rhino-mocks-v3-2-new-syntax/" rel="nofollow noreferrer">this post</a> suggests, if you prefer separating your expectations from your verifications/assertions, you should opt for the Fluent syntax. It's all a matter of style and personal preference, ultimately :-)</p>
7,831
<p>I have a mature MFC C++ application that displays on screen and prints using CDC wrappings on the Win32 GDI. While it has been optimized over the years, I would like to replace it with something a bit faster. The graphics included rendered triangular surface models, complex polylines and polygons, and lots of text. It needs to meet the following criteria;</p> <ul> <li><p>The number of vectors displayed is likely to be very large. For example a single surface triangle is likely to generate a number lines and solid fills when rendered. At present this information is not stored anywhere, it is generated and drawn on the fly. The SDK should support limit the total number of buffered vectors, or it is liable to run out of memory.</p></li> <li><p>The SDK should be able to render to any CWnd derived class including CView and ScrollView classes.</p></li> <li><p>The SDK should support printing to any Windows print device,</p></li> <li><p>The SDK should be low level enough to make the port from low level CDC / GDI calls relatively straightforward.</p></li> <li><p>Open source is always nice, but a one off cost of up to say $2k, with optional upgrades/support would also be ok. A license cost per user is not acceptable,</p></li> <li><p>Access to source code would be a big bonus, specifically with the idea of running portions of the SDK on Windows CE / Mobile.</p></li> <li><p>I currenly handle my own 3d to 2d viewport management. If a decent low level SDK is not available, a higher level SDK must handle 3d well, and work with millions of triangles, polygons and text entities on a 32 bit windows platform.</p></li> </ul> <p>Any suggestions? Listing the specific pros and cons in your proposed suggestion would be greatly appreciated.</p>
<p>I think DirectX or <a href="http://libsdl.org/" rel="nofollow noreferrer">SDL</a> will suit your needs. They are designed for 3D but work for 2D as well. Both support Windows CE / Mobile and SDL is also available for a bunch of non-Microsoft OS.</p> <p>Unfortunately direct compatibility with GDI is not supported in the libraries. But you can do the trick by creating a converter class, which will accept all output graphics from your GDI designed application classes and convert the format to fit the needs of DirectX or SDL classes (depending what do you want to use).</p> <p>Personally I made such converter class once. I had a game written for Pocket PC, using SDL and I needed to port it to Palm device. There I had to use different graphics library (I don't remember the name of the lib now) but I succeeded to port all SDL functions output to the format needed by the other lib. I needed to change my application to call the converter (wrapper) functions, which forwarder the call to Palm or Pocket PC library, depending on which device it is currently running. So I think you can do the same for converting GDI -> DirectX or GDI -> SDL.</p>
<p>I think DirectX or <a href="http://libsdl.org/" rel="nofollow noreferrer">SDL</a> will suit your needs. They are designed for 3D but work for 2D as well. Both support Windows CE / Mobile and SDL is also available for a bunch of non-Microsoft OS.</p> <p>Unfortunately direct compatibility with GDI is not supported in the libraries. But you can do the trick by creating a converter class, which will accept all output graphics from your GDI designed application classes and convert the format to fit the needs of DirectX or SDL classes (depending what do you want to use).</p> <p>Personally I made such converter class once. I had a game written for Pocket PC, using SDL and I needed to port it to Palm device. There I had to use different graphics library (I don't remember the name of the lib now) but I succeeded to port all SDL functions output to the format needed by the other lib. I needed to change my application to call the converter (wrapper) functions, which forwarder the call to Palm or Pocket PC library, depending on which device it is currently running. So I think you can do the same for converting GDI -> DirectX or GDI -> SDL.</p>
24,938